开发者

Java error message java.lang.StringIndexOutOfBoundsException: String index out of range: 0

here is m开发者_如何学Pythony program

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");

   }
}
}

when i try and run it it gives me this error message

java.lang.StringIndexOutOfBoundsException: String index out of range: 0 at java.lang.String.charAt(String.java:687)

how do i fix it so the program loops correctly?!?


before you do this: repeat = input.charAt(0);

check if the string has at-least one character.


It seems that the user is pressing return/enter without inputing Y or N.

Here is the suggestion. No doubt that the code can be made better in many ways, but this is just a suggestion for this very issue. Get rid of the repeat variable completely, and replace respective lines with these.

do {
    .....

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

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


First, just a side note, as mootinator stated, your while condition will be false if any input is not 'Y' or 'y', thus exit and the final "\nThanks for playing! \n" will never be displayed. You should revise this construct. Perhaps something like :

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");

Now, to address your original problem, you are not checking for empty input. The error is very likely to happen only when you hit enter without entering anything. Another question is then, what to do with empty values? Is it considered to be 'N' or 'Y'? If you consider empty value to be a valid default choice, you should indicate it in your displayed question. Something like:

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

If you don't want a default value, simply change the construct to

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


IndexOutOfBoundsException means the index you're trying to access of the array does not exist. The exception shows you it's encountering the error at line 687 and it's the String.charAt() method. I'd recommend by taking a closer look at your code around that line. If you're using an IDE, you should try executing in debug with a breakpoint near that line and stepping through the code line by line to watch the variables.


Instead of this:

repeat = input.charAt(0);

Do this:

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

This way you can catch your exception and handle it. EDIT: It's better to learn a little Exception handling in Java in your first lesson, because it's not complicated and will be useful at later, more difficult tasks.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜