如何使用Scanner.hasNext填充多个数组值?

时间:2012-10-03 17:19:51

标签: java java.util.scanner

我有一系列骰子,对于每一个骰子,我需要提示用户是否要重新打印它。最简单的方法似乎是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]”)以使intepreter不锁定,以便在循环的每一步之后正确检查条目?

2 个答案:

答案 0 :(得分: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..
 }

答案 1 :(得分: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;


    }
  }

}