Java输入/输出扫描程序类和交互面板

时间:2012-03-11 23:16:59

标签: java io java.util.scanner

我有这段代码:

Scanner sc = null;
 sc = new Scanner(System.in);
 System.out.println("Your final answer is? (Y/N)");
 String answer = sc.next();
 if(answer.equals("Y"){
//do sth
}
 else if(answer.equals("N")){
//do sth else
}

如果此人未输入“Y”或“N”,我希望再次询问该问题,直到答案是其中之一。这是我能做到的一种方式吗?

2 个答案:

答案 0 :(得分:2)

Scanner sc = new Scanner(System.in);
String answer = null;
boolean ask_again = true;
do {
     System.out.println("Your final answer is? (Y/N)");
     answer = sc.next();
     if(answer.equals("Y")){
       //do something when Yes
       ask_again = false;
     }
     else if(answer.equals("N")){
       //do something when No
       ask_again = false;
     }
     else {
       ask_again = true; 
     }
} while(ask_again == true);

答案 1 :(得分:1)

Scanner sc = new Scanner(System.in);
String answer = new String();
do {
    System.out.println("Your final answer is? (Y/N)");
    answer = sc.next();
} while((!answer.equals("Y")) && (!answer.equals("N")));
// do your bit here if "Y" or "N"