簡體   English   中英

數字輸入異常線程“main”java.lang.StringIndexOutOfBoundsException:字符串索引超出范圍:0

[英]Number input Exception thread “main” java.lang.StringIndexOutOfBoundsException: String index out of range: 0

在我的程序中,您應該輸入分配給變量的距離。 然后,您可以選擇一個數字來表示您要進行的轉換類型。 例如,如果我選擇數字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處字符的問題,我的輸入是一個數字。

meters = keyboard.nextDouble(); 是問題,因為它只讀取數字而不是整行。 你需要在它之后添加keyboard.nextLine()。 因為稍后的nextLine()調用正在消耗該行的其余部分。

只要像這樣制作你的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 Exception。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM