Java错误消息java.lang.StringIndexOutOfBoundsException:字符串索引超出范围:0

时间:2010-10-28 02:47:40

标签: java

这是我的程序

import java.util.Scanner;
import java.util.Random;

public class Project3
{
    public static void main(String[] args)
    {

        int low;
        int high;
        int answer;
        int guess;
        int numGuess = 0;
        int x;
        int y;

       char repeat; // this will hold y or n 
       String input; //holds input to perform entire loop


        System.out.println( "Hello and welcome to Guess That Number!");

            Scanner keyboard = new Scanner(System.in);

        System.out.println("For starters you get to pick the range the number falls in!" +
                            " HOW EXCITING!");


        System.out.println( "Now what would you like the lowest possible number to be?");
                      low = keyboard.nextInt();

        System.out.println( "and the highest?");
                      high = keyboard.nextInt();
 do  
  {    Random randomNumber = new Random();

        answer = randomNumber.nextInt();
       while (answer < low || answer > high)
       { 
        answer = randomNumber.nextInt();
    }



       guess = -1;

       while(guess != answer)
       {

           System.out.println("What is your guess?");
          System.out.println("Don't forget has to be in between "+ low + " and " + high);

                   guess = keyboard.nextInt();

                   numGuess = (numGuess + 1);

                if (guess < answer)
                {
                    System.out.println("TOO LOW!");

                }

                else if (guess > answer)
                {
                    System.out.println("TOO HIGH!");



                }


            }





       System.out.println("YOU GOT IT WOOOO!");
       System.out.println("The number was " + answer);
       System.out.println("Nice it only took " + numGuess + "!");

       for ( x = 1; x <= numGuess; x++)

      {

          for ( y = 1; y <= answer; y++)

            {
                System.out.print("*");
            }

            System.out.println();



      }


      System.out.println("\nWould you like to play again? \n" +        // this is to loop the entire game
                      "Enter Y for yes or N for no. \n");

                      input = keyboard.nextLine();
                      repeat = input.charAt(0);

  } while (repeat == 'Y' || repeat == 'y');

    if (repeat == 'n' || repeat == 'N')             
    {

    System.out.println("\nThanks for playing! \n");

   }
}
}

当我尝试运行它时,它会给我这个错误消息

java.lang.StringIndexOutOfBoundsException:字符串索引超出范围:0  在java.lang.String.charAt(String.java:687)

如何修复它以便程序正确循环?!?

5 个答案:

答案 0 :(得分:3)

之前:repeat = input.charAt(0);

检查string是否有at-least个字符。

答案 1 :(得分:2)

首先,只是旁注,如mootinator所述,如果任何输入不是while'Y',则'y'条件将为false,因此退出并返回永远不会显示"\nThanks for playing! \n"。你应该修改这个结构。也许是这样的事情:

boolean playing = true;

while (playing) {
   // play game here

   // ask to play again?

   if (answer == 'N') {
      playing = false;
   }
}

System.out.println("\nThank you for playing!\n");

现在,为了解决您的原始问题,您不会检查空输入。只有在没有输入任何内容的情况下按Enter键时,才会发生错误。那么另一个问题是,如何处理空值?它被认为是'N'还是'Y'?如果您认为空值是有效的默认选项,则应在显示的问题中指明它。类似的东西:

System.out.print("\nWould you like to play again?\n" + 
                 "Enter Yes or No (default Yes) : ");
do {
   input = keyboard.nextLine().toUpperCase();  // 'Y' == 'y';
   if (input.length() == 0) {  // if the input is empty, we default the value
      repeat = 'Y';     // default value, change this to 'N' if default is No
   } else {
      repeat = input.charAt(0);
      if (repeat != 'N' && repeat != 'Y') {
         System.out.print("Ooops! Please enter Yes or No :");
         repeat = '\0';
      }
   }
} while (repeat == '\0');
// At this point, repeat is either 'Y' or 'N' only, so no need to check for lowercase

如果您不想要默认值,只需将构造更改为

即可
System.out.print("\nWould you like to play again?\n" + 
                 "Enter Yes or No : ");
do {
   input = keyboard.nextLine().toUpperCase();  // 'Y' == 'y';
   if (input.length() == 0) {  // if the input is empty...
      repeat = '\0';     // null character for empty value
   } else {
      repeat = input.charAt(0);
   }
   if (repeat != 'N' && repeat != 'Y') {
      System.out.print("Ooops! Please enter Yes or No :");
      repeat = '\0';     // make sure the character is null so we don't exit the loop yet
   }
} while (repeat == '\0');
// At this point, repeat is either 'Y' or 'N' only, so no need to check for lowercase

答案 2 :(得分:2)

用户似乎在没有输入return/enterY的情况下按N

这是建议。毫无疑问,代码可以在很多方面做得更好,但这只是对这个问题的一个建议。完全删除repeat变量,并用这些变量替换相应的行。

do {
    .....

} while ("y".equalsIgnoreCase(input));

if (!"y".equalsIgnoreCase(input)) {
  System.out.println("\nThanks for playing! \n");
}

答案 3 :(得分:0)

IndexOutOfBoundsException表示您尝试访问该数组的索引不存在。异常显示它在第687行遇到错误,它是String.charAt()方法。我建议您仔细查看该行周围的代码。如果您正在使用IDE,则应尝试在调试中执行,并在该行附近使用断点并逐行逐步执行代码以查看变量。

答案 4 :(得分:0)

而不是:

repeat = input.charAt(0);

这样做:

try
{
    repeat = input.charAt(0);
}
catch (java.lang.StringIndexOutOfBoundsException exception)
{
//Solve the problem
}

这样你就可以捕获异常并处理它。 编辑:在第一课中学习Java中的一点异常处理会更好,因为它并不复杂,在以后更困难的任务中会很有用。