• We’re currently investigating an issue related to the forum theme and styling that is impacting page layout and visual formatting. The problem has been identified, and we are actively working on a resolution. There is no impact to user data or functionality, this is strictly a front-end display issue. We’ll post an update once the fix has been deployed. Thanks for your patience while we get this sorted.

Java help.

mikysee

Senior member
How do I test to see if there is something in a string?
If I typed in the console:
java Test hello
There is a string.

And if I typed:
java Test
There is no string.

I got the first part but I keep getting an error when I try the second one.

Thanks for any help.
 
You can use:

the .length() function of String.

You have to differentiate between a String object that you have access to and one that you do not.

In your example, you'd have a mian that looks like this:

static public void main(String[] args) {

}

You must check that args.length isn't 0 to know if a string was passed as a parameter to the program. After that you can check args[0].length() (though you shouldn't have to. As far as I know no empty strings can be passed in from the command line).
 
You have to get access to the string first from the array args: String[] args

After which you test whether there is a string inside the array or not.
 
Originally posted by: mikysee
How do I test to see if there is something in a string?
If I typed in the console:
java Test hello
There is a string.

And if I typed:
java Test
There is no string.

I got the first part but I keep getting an error when I try the second one.

Thanks for any help.

Assuming the string in question is the only parameter then:

public static void main (String[] argv) {
if (argv[0] != null && argv[0].length != 0 && !argv[0].equals("")) {
// You have a valid string
} else {
// You do not have a valid string.
}
}

 
Originally posted by: m0ti
You can use:

the .length() function of String.

You have to differentiate between a String object that you have access to and one that you do not.

In your example, you'd have a mian that looks like this:

static public void main(String[] args) {

}

You must check that args.length isn't 0 to know if a string was passed as a parameter to the program. After that you can check args[0].length() (though you shouldn't have to. As far as I know no empty strings can be passed in from the command line).

class NullParam {
public static void main(String[] args) {
for (int i = 0; i < args.length; i++) {
System.out.println(args[ i ]);
}
}
}

manly@p3-800:~/java-dev> javac -g NullParam.java
manly@p3-800:~/java-dev> java NullParam "" abcde

abcde
manly@p3-800:~/java-dev>
 
Back
Top