How to loop a main method
I have to make the main method of the following program loop until a blank is entered, how would I change this to do so? thanks in advance
public static void main(String[] args) {
Scanner reader = new Scanner (System.in);
System.out.println("What is the name you want to test? ");
String name = reader.nextLine();
convertName(name);
}
public static boolean hasComma(String name){
boolean oName;
int x= name.indexOf(',');
if (x == -1) {
oName= false;
}else{
oName= (true);
}
return (oName);
}
public static boolean convertName(String name) {
boolean convert = false;
hasComma(name);
if (hasComma(name)== true) {
convert= true;
}else{
String s = name;
String[] arr = s.split(" ");
System.out.println (arr[1]+ ","+ arr[0]);
}
return (convert);
}
}
Re: How to loop a main method
You don't want to loop the main method itself, and you really can't do this in a straight-forward fashion anyway (let's avoid recursion, OK?). Instead you probably want to loop a block of code *inside* the main method, and to do this, use a loop such as a for loop or while loop.
Re: How to loop a main method
I was messing around with the code and I found that a while loop worked best for me during testing.
Re: How to loop a main method
First off, you should really wrap up your code in [code] tags so that it is much easier to read.
Code:
do{
...code...
}while(condition);
This will loop the ...code... until the condition is evaluated as false. The condition in your case is if stringVariable is equal to 'blank'. To compare a string you need to use the .equals() method; and you can use the '!' to not the condition. Just make this loop around where you get the variable name, and it will continue to loop as long as !name.equals("").
If your condition, in any case, is a boolean, you do not need to compare it to anything; as it is automatically evaluated as true or false. In your code, you have:
Code:
if (hasComma(name)== true) {
As hasComma() returns a boolean variable, if it is true, it will be evaluated as true, and if it is false, it will be evaluated as false. This means you just need to have:
Code:
if (hasComma(name)) {
The default value of any boolean variable is automatically false, so you don't need:
Code:
boolean convert = false;
You could just use:
As it does the same things.