数字输入异常线程“main”java.lang.StringIndexOutOfBoundsException:字符串索引超出范围:0

时间:2014-03-24 19:19:11

标签: java

在我的程序中,您应该输入分配给变量的距离。然后,您可以选择一个数字来表示您要进行的转换类型。例如,如果我选择数字1并按下回车键,它会将我的米转换为千米。

我去做了一次试运行,进入了米并按下了进入。我无法进入我想要做的转换,因为例外情况就是这样:

Please enter the distance in meters: 500
Please enter the number of the conversion you want to make: 
1. Convert to Kilometers 
2. Convert to Inches 
3. Convert to Feet 
4. Quit ProgramException in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 0
at java.lang.String.charAt(String.java:658)
at ConversionWilson.main(ConversionWilson.java:41)

不确定导致此异常的原因。

public static void main (String [] args)
{

// Scanner object to read input
Scanner keyboard = new Scanner (System.in);
// Prompt the user for distance and conversion.
System.out.println("Welcome to the Conversion Program.");
System.out.println("With this program, you can enter a distance and convert it to another form of measurement.");
System.out.print("Please enter the distance in meters: ");

if (meters >= 0)
{
   meters = keyboard.nextDouble();
}
else
{
   System.out.println("Meters cannot be a negative number. Please choose a positive number.");
}

System.out.print("Please enter the number of the conversion you want to make: \n" +
                 "1. Convert to Kilometers \n" + "2. Convert to Inches \n" + "3. Convert to Feet \n" +
                 "4. Quit Program");
input = keyboard.nextLine();
conversion = input.charAt(0);

// Deciding what conversion method to call.

switch (conversion)
{
  case '1':
     showKilometers(meters);
     break;

  case '2':
     showInches(meters);
     break;

  case '3':
     showFeet(meters);
     break;

  case '4':
     System.out.println("Beep boop bop. Quitting the program now. Later.");
     break;

  default:
     System.out.println("You did not select a possible choice. Please run the program again and be sure to choose a correct number.");
}         

我试过看看我是否可以通过搜索找到一个解决方案,但是大多数人似乎都遇到了索引0处字母的问题,我输入的是一个数字。

2 个答案:

答案 0 :(得分:2)

meters = keyboard.nextDouble();是问题,因为它只读取数字而不是整行。你需要在它之后添加keyboard.nextLine()。因为稍后的nextLine()调用正在消耗该行的其余部分。

答案 1 :(得分:0)

只需制作这样的if语句,

        if (meters >= 0)
        {
           meters = keyboard.nextDouble();
           keyboard.skip("\n"); //This will skip the '\n' you entered after entering the meters.
        }

因为' \ n'仍然在缓冲区中keyboard.nextLine()之后将会读取该内容并且您将获得ArrayIndexOutOfBounds异常。