嗨,我有个节目:
import java.util.Scanner;
public class HowAreYou {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String input;
System.out.println("How are you?");
input = in.nextLine();
if (input.equals("I'm doing good!")) {
System.out.print("That's great to hear!");
} else if (input.equals("I'm not doing too well...")) {
System.out.print("Aw I'm sorry to hear that");
} else {
System.out.print("Sorry I didn't catch that are you doing good or bad?");
input = in.nextLine();
if (input.equals("good")) {
System.out.print("That's great to hear!");
} else if (input.equals("bad")) {
System.out.print("Aw I'm sorry to hear that");
}
}
}
}它对前两个响应很好,如果您输入了其他内容,它会打印“对不起,我没注意到,您做得好还是坏?”正确,但我希望它在打印后再次得到响应。这时,它说:“对不起,我没听清楚,你做得好还是坏?”它不允许你输入任何其他东西。
发布于 2014-06-25 11:30:37
我认为您面临的问题是,在"Sorry I didn't catch that are you doing good or bad?"消息之后,您点击enter key来给出响应,您的程序就会终止。之所以会发生这种情况,是因为input.nextLine消耗了它,并且它与任何东西都不匹配,并且程序退出。
你应该换掉
System.out.print("Sorry I didn't catch that are you doing good or bad?");使用
System.out.println("Sorry I didn't catch that are you doing good or bad?");以便在实际输入之前到达下一行。希望这能有所帮助。
发布于 2014-06-25 11:18:02
只要使用无限循环即可。就像这样
while(true){
// your code here...
if(input.equals("exit")) break;
}这是最简单的解决办法。
发布于 2014-06-25 11:20:58
您可以通过添加一个while循环来完成这一任务。
import java.util.Scanner;
public class HowAreYou {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String input;
/* loop which keeps asking for input ends when user enters Bye Bye*/
while(true){
System.out.println("How are you?");
input = in.nextLine();
if (input.equals("I'm doing good!")) {
System.out.println("That's great to hear!");
break;
} else if (input.equals("I'm not doing too well...")) {
System.out.println("Aw I'm sorry to hear that");
break;
} else if (input.equals("Bye Bye")) {
System.out.println("Bye Bye");
break;
} else {
System.out.println("Sorry I didn't catch that are you doing good or bad?");
}
}
}
}https://stackoverflow.com/questions/24407094
复制相似问题