0

我有一系列骰子,对于每个骰子,我都需要提示用户是否愿意重新掷骰子。最简单的方法似乎是 Scanner 类的提示 - 我检查他们输入的内容并正确处理。但是,如果用户输入中不存在请求的数据,scanner.next() 将抛出异常。所以,scanner.hasnext() 需要以某种方式适应这里。

这是我的代码;它会将条目输入到响应数组中,但如果用户输入既不包含 Y 也不包含 N,则会引发异常。

public Boolean[] chooseDice(int diceNum){
    Boolean[] responses = new Boolean[diceNum];
    Scanner scansworth = new Scanner(System.in);
    for (int i=0; i<diceNum; i++){
        System.out.printf("Reroll this die? (%d)\n",i);
                responses[i] = (scansworth.next("[YN]")) == "Y" ? true : false;
    }
        return responses;

如何调用 scansworth.hasNext("[YN]") 以便解释器不会锁定并在循环的每个步骤之后正确检查条目?

4

2 回答 2

1

您可以将读取用户输入的代码用一段时间包围,以检查用户输入是否处于给定模式.. 使用hasNext("[YN]").. 此外,您不需要scanner.next([YN]).. 只需使用next().. 它会获取您输入的下一行,您可以将其与“Y”进行比较..

 for (int i=0; i<diceNum; i++){
           int count = 0;
           System.out.printf("Reroll this die? (%d)\n",i);

           // Give three chances to user for correct input.. 
           // Else fill this array element with false value..

           while (count < 3 && !scansworth.hasNext("[YN]")) {
               count += 1;  // IF you don't want to get into an infinite loop
               scansworth.next();
           }    

           if (count != 3) {
                /** User has entered valid input.. check it for Y, or N **/
                responses[i] = (scansworth.next()).equals("Y") ? true : false;
           } 
           // If User hasn't entered valid input.. then it will not go in the if  
           // then this element will have default value `false` for boolean..
 }
于 2012-10-03T17:28:32.847 回答
0

我想你可以试试这样的......

public Boolean[] chooseDice(int diceNum){
    Boolean[] responses = new Boolean[diceNum];
    boolean isCorrect = false;
    Scanner scansworth = new Scanner(System.in);
    for (int i=0; i<diceNum; i++){

while(!isCorrect){

if((scansworth.hasNext().equalsIgnoreCase("Y")) ||  (scansworth.hasNext().equalsIgnoreCase("N")))`{



    responses[i] = scansworth.next();
    isCorrect = true;

}else{

       isCorrect = false;


    }
  }

}
于 2012-10-03T17:39:56.393 回答