简体   繁体   English

当我运行程序时,出现错误java.lang.StringIndexOutOfBoundsException:字符串索引超出范围:0

[英]When I run my program i get the error java.lang.StringIndexOutOfBoundsException: String index out of range: 0

here is my code 这是我的代码

import java.io.*;
import java.util.*;
public class weightOnOtherPlanets {
public static void main(String[] args) {
    Scanner kbReader = new Scanner(System.in);
    System.out.println("Enter your weight");
    double weight = kbReader.nextDouble();
    System.out.println("choose a planet by entering the corresponging letter\n");
    System.out.println("A.     Voltar");
    System.out.println("B.     Krypton");
    System.out.println("C.     Fertos");
    System.out.println("D      Servantos");
    String choice = kbReader.nextLine( );
    char p = choice.charAt(0);
    String answerPhrase = "Your weight is " + " " ;
    switch(p){
    case 'A':
    case 'a':
        System.out.println(answerPhrase +(.091*weight));
    break;
    case 'B':
    case 'b':
        System.out.println(answerPhrase + (.720*weight));
        break;
    case 'C':
    case 'c':
        System.out.println(answerPhrase + (.865*weight));
        break;
    case 'D':
    case 'd':
        System.out.println(answerPhrase + (4.612*weight));
        break;
    default:
        System.out.println("Please enter either A,B,C,or D");
        break;
    }
}
}

I have used almost the exact same code for another similar practice project and it worked just fine. 我在另一个类似的实践项目中使用了几乎完全相同的代码,并且效果很好。 When i run the program it goes to the point where it asks for a weight input, then it displays the choice list, but with the error message exception in "main": 当我运行该程序时,它会要求输入重量,然后显示选择列表,但在“ main”中显示错误消息异常:

 java.lang.StringIndexOutOfBoundsException: String index out of range: 0
    at java.lang.String.charAt(String.java:686)
    at weightOnOtherPlanets.main(weightOnOtherPlanets.java:14)

I don't know why it gives this error before allowing keyboard input for String choice. 我不知道为什么在允许键盘输入进行字符串选择之前会出现此错误。

This is because of the way Scanner scans lines. 这是因为Scanner扫描线的方式。

After you enter a double (the weight), you press Return . 输入倍数(重量)后,按回车键。 This tells System.in to take all the characters you entered and pass them to the scanner. 这告诉System.in接受您输入的所有字符并将它们传递给扫描仪。 The scanner then reads the part that interests it - the double number - but leaves everything else waiting for the next operation. 然后,扫描仪将读取其感兴趣的部分-双精度号-但剩下的一切都等待下一个操作。

This means the Return you pressed - the end-of-line - is still there. 这意味着你按下回车 -最终的线-仍然存在。 Now, the next thing is nextLine() . 现在,接下来是nextLine() The scanner sees it, and it reads all the characters it has until it finds an end-of-line. 扫描程序将看到它,并读取它具有的所有字符,直到找到行尾。 But as we said, the end-of-line is right there. 但是正如我们所说,行尾就在那里。 So it reads that, and gives you all the characters it found before it. 因此,它会读取该内容,并为您提供它之前找到的所有字符。 Which is none at all, because there were no other characters between the double number and the end-of-line. 根本没有,因为在双精度数字和行尾之间没有其他字符。

This means you get an empty string. 这意味着您将得到一个空字符串。 And an empty string doesn't have a character at position 0 , because that would mean it was not empty. 并且空字符串在位置0处没有字符,因为那将意味着它不为空。

So what you should do is, after receiving the double, you should add a kbReader.nextLine(); 因此,您应该做的是,在收到两倍后,应添加kbReader.nextLine(); - just like that, without putting the value anywhere. -就像那样,而没有把价值放在任何地方。 This will skip the end-of-line you entered for the double, and then you'll get the next line properly. 这将跳过为双精度输入的行尾,然后您将正确获得下一行。

When you do your menu reading, though, you should be checking that the string is not empty before you call charAt(0) . 但是,在读取菜单时,应在调用charAt(0)之前检查字符串是否为空。 After all, the user can decide to press Return rather than make a valid choice. 毕竟,用户可以决定按Return键而不是做出有效选择。 So your system should either ignore that or tell him that it's not a legal input, rather than fail with an exception. 因此,您的系统应该要么忽略它,要么告诉他这不是合法的输入,而不是因异常而失败。

You call nextDouble(); 您调用nextDouble(); and after that you call nextLine() to get your answer phrase. 然后,您调用nextLine()获得答案。 But that call to nextLine(); 但是对nextLine();调用nextLine(); will only consume the rest of the line on which you entered your double and it will be empty, therefore choice.charAt(0); 只会消耗您在其中输入了double的行的其余部分,该行将为空,因此, choice.charAt(0); will throw an exception. 会抛出异常。

Try doing something like this to consume the rest of the line and then call the nextLine() to get the answer phrase. 尝试执行类似的操作以消耗其余的行,然后调用nextLine()以获得答案。

System.out.println("Enter your weight");
double weight = kbReader.nextDouble();
kbReader.nextLine(); // Consume the rest of the line

// ...

String choice = kbReader.nextLine(); // Get the actual input
char p = choice.charAt(0);

try this: 尝试这个:

public static void main(String[] args) {
    Scanner kbReader = new Scanner(System.in);
    System.out.println("Enter your weight");
    double weight = kbReader.nextDouble();
    System.out.println("choose a planet by entering the corresponging letter\n");
    System.out.println("A.     Voltar");
    System.out.println("B.     Krypton");
    System.out.println("C.     Fertos");
    System.out.println("D      Servantos");
    String choice = kbReader.nextLine();
    if (choice.isEmpty()) {
        choice = kbReader.nextLine();
    }
    char p = choice.charAt(0);
    String answerPhrase = "Your weight is " + " ";
    switch (p) {
        case 'A':
        case 'a':
            System.out.println(answerPhrase + (.091 * weight));
            break;
        case 'B':
        case 'b':
            System.out.println(answerPhrase + (.720 * weight));
            break;
        case 'C':
        case 'c':
            System.out.println(answerPhrase + (.865 * weight));
            break;
        case 'D':
        case 'd':
            System.out.println(answerPhrase + (4.612 * weight));
            break;
        default:
            System.out.println("Please enter either A,B,C,or D");
            break;
    }
}

You need to read for input differently. 您需要阅读不同的输入内容。 That's why you are throwing an exception. 这就是为什么您引发异常。

char p = choice.charAt(0); // why not just do a string comparison instead?

is where the error comes up. 错误出现的地方。 This is because choice is null / has no charAt(0). 这是因为选择为null /没有charAt(0)。

Irregardless I would use something like this instead 不管我会用这样的东西代替

char p = ''
while(in.hasNext()) {
    String input = in.nextLine();
    if (p.length()>0){
        p = choice.charAt(0);
    }
    //do whatever you wanted to with p

This should give you the behavior you are looking for. 这应该为您提供所需的行为。

Don't forget to consider changing the double input to work roughly the same though. 但是不要忘记考虑将double输入更改为大致相同。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 我收到如下错误消息:线程“ main”中的异常java.lang.StringIndexOutOfBoundsException:字符串索引超出范围:0 - I get an error message as follows: Exception in thread “main” java.lang.StringIndexOutOfBoundsException: String index out of range: 0 我不断收到此错误:线程“main”中的异常 java.lang.StringIndexOutOfBoundsException: String index out of range: 28 - I keep getting this error : Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 28 Java错误java.lang.StringIndexOutOfBoundsException:字符串索引超出范围:0 - Java Error java.lang.StringIndexOutOfBoundsException: String index out of range: 0 我的程序出现运行时错误:线程“ main”中的异常java.lang.StringIndexOutOfBoundsException:字符串索引超出范围:27 - My program has a runtime error: exception in thread “main” java.lang.StringIndexOutOfBoundsException: String index out of range: 27 该程序不断给我一个错误:线程“ main”中的异常java.lang.StringIndexOutOfBoundsException:字符串索引超出范围:4 - This program keeps on giving me an error: Exception in thread “main” java.lang.StringIndexOutOfBoundsException: String index out of range: 4 为什么程序会抛出这个错误??:线程“main”中的异常java.lang.StringIndexOutOfBoundsException:字符串索引超出范围:36 - Why is the program throwing this error??: Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 36 我无法解决此问题:java.lang.StringIndexOutOfBoundsException:字符串索引超出范围:54 - I am unable to solve this :java.lang.StringIndexOutOfBoundsException: String index out of range: 54 为什么我不断收到:线程“主”java.lang.StringIndexOutOfBoundsException 中的异常:字符串索引超出范围:4 - Why do I keep geting: Exception in thread “main” java.lang.StringIndexOutOfBoundsException: String index out of range: 4 我收到“ java.lang.StringIndexOutOfBoundsException:字符串索引超出范围:-3” - I am getting “ java.lang.StringIndexOutOfBoundsException: String index out of range: -3 ” 构建成功,但我不断收到“线程“main”中的异常 java.lang.StringIndexOutOfBoundsException: String index out of range: 1' - Build is successful but I kept getting the 'Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 1'
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM