public class Main {
public static void main(String[] args)throws Exception {
Boolean yn;
String answer;
String name;
do{
Scanner in = new Scanner(System.in);
System.out.println("Enter your name");
name = in.nextLine();
System.out.println("Hi "+name);
System.out.println("Do you want to enter another name?");
System.out.println("y/n?");
answer = in.nextLine().toLowerCase();
if(answer.equals("y")){
yn = true;
break;
}else if(answer.equals("n")){
yn = false;
break;
}
}while(yn = true );
}
}
i have to make it go back to asking the name when i get a yes for the last question. super noob here sorry please help.
Your break
is the culprit...
When you use break
it breaks out of the loop.
So use, (Note: You don't need an else if, just else should be sufficient).
if(answer.equals("y")){
yn = true;
} else {
yn = false;
}
without break
statement.
Also use a condition (not assignment) inside while,
while(yn == true)
or simply,
while(yn)
该break
不应该在被使用if
只是如果你想关闭语句loop
,取出break
的if
。
use continue instead of break as below
if(answer.equals("y")){
yn = true;
break; //use continue here
} else if(answer.equals("n")){
yn = false;
break;
}
You can do this :
public static void main(String[] args)throws Exception {
Boolean yn;
String answer;
String name;
do {
Scanner in = new Scanner(System.in);
System.out.println("Enter your name");
name = in.nextLine();
System.out.println("Hi "+name);
System.out.println("Do you want to enter another name?");
System.out.println("y/n?");
answer = in.nextLine().toLowerCase();
if(answer.equals("y")){
yn = true;
continue; //Continue does not terminate the loop instead of break
}else {
yn = false;
break;
}
}while(yn = true );
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.