【问题标题】:Why is my string index out of range?为什么我的字符串索引超出范围?
【发布时间】:2017-03-16 10:45:29
【问题描述】:

为抛硬币程序编写嵌套的 while 循环,但我不知道为什么我的代码无法编译。 最后的用户输入给了我索引超出范围错误。谁能告诉我如何解决这个问题?

 Scanner lit = new Scanner(System.in);
 int numHeads = 0;
 int numTails = 0;
 int counter = 0;
 boolean tryAgain = false;
 String replayResponse = "";
 char replay = '0';

 System.out.println("Enter how many times a coin should be flipped");
 int numFlipped = lit.nextInt();

 do {

     do{


     if (Math.random() > 0.5){
         System.out.println("H");
         numHeads++; counter++;
     }

     else if (Math.random() < 0.5){
         System.out.println("T");
         numTails++; counter++;
     }


 } while(counter < numFlipped);

     tryAgain = true;

 } while (!tryAgain);

 System.out.println("Number of heads is " + numHeads);
 System.out.println("Number of tails is " + numTails);
 System.out.println("");
 System.out.println(" Would you like to play again? : Y/N ");


    replayResponse = lit.nextLine();
    replay = replayResponse.charAt(0);
    if (replay == 'Y' || replay == 'y') {
        tryAgain = false;
    } else {
        tryAgain = true;


     }

        lit.close(); 
        System.out.println();
        System.out.println("You exited out of the game.");
        System.out.println("Goodbye!");
     }

【问题讨论】:

  • 在哪一行抛出错误?
  • 这是与 replayResponse.charAt(0);感谢 BlackhatSamurai,我现在关闭了扫描仪,但我似乎遇到了输入不匹配异常

标签: java loops indexing nested out


【解决方案1】:

扫描 int 时,您需要重置输入。目前扫描仪正在寻找下一个整数。所以像这样添加lit.nextLine();

 lit.nextLine();
 replayResponse = lit.nextLine();
    replay = replayResponse.charAt(0);
    if (replay == 'Y' || replay == 'y') {
        tryAgain = false;
    } else {
        tryAgain = true;

     }

你也可以这样做:

if(lit.hasNextInt()) 
{
   numFlip = lit.nextInt();
}

解决类型不匹配异常。

【讨论】:

  • 确实解决了问题!虽然现在当我输入 Y 尝试循环程序时,我似乎得到了输入不匹配异常。是另一个扫描仪错误吗?
  • @EricSmith 扫描仪在使用 int 和字符串等时有点棘手。它与扫描仪有关,所以如果他们想再次播放,我会关闭扫描仪然后重新打开。跨度>
  • 我现在没有编译错误了!看起来我一定有一个逻辑错误,因为当我输入 Y 时它会输出我的退出游戏线
  • @EricSmith 很好,如果它有效,请随时接受并投票 :)
猜你喜欢
  • 1970-01-01
  • 2014-03-10
  • 1970-01-01
  • 2014-03-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多