嗨,我有这个程序:
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");
}
}
}
}
它适用于前两个回复,如果你输入的内容不是那么打印"抱歉,我没有抓到你做得好不好?"正确,但我希望它在打印后再次收到响应。在它说完之后的那一刻"抱歉,我没有抓到你做得好还是坏?"它不允许你输入任何其他东西。
答案 0 :(得分:2)
只需使用无限循环。像这样的东西
while(true){
// your code here...
if(input.equals("exit")) break;
}
这是最简单的解决方案。
答案 1 :(得分:2)
您可以通过添加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?");
}
}
}
}
答案 2 :(得分:0)
我认为您遇到的问题是,在"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?");
这样你就可以在实际输入之前到达下一行。希望这会有所帮助。