为什么在此代码中出现StringIndexOutOfBoundsException? [英] Why am I getting StringIndexOutOfBoundsException in this code?

查看:151
本文介绍了为什么在此代码中出现StringIndexOutOfBoundsException?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Java中收到以下错误消息

I am getting the following error message in Java

Exception in thread "main" 

    java.lang.StringIndexOutOfBoundsException: String index out of range: 0

这是我的代码-

public static void main(String[] args) {

    double gissade = 70;
    int input;
    java.util.Scanner in = new java.util.Scanner(System.in);

    char spelaIgen = 'j';
    // char input2;

    int antal = 1;

    while (spelaIgen == 'j') {
        System.out.print("gissa ett number?");
        Input = in.nextInt();

        if (input < gissade) {
            System.out.println("du har gissat för lågt försök igen");
            antal++;
        } else if (input > gissade) {
            System.out.println("du har gissat för högt försök igen");

            antal++;
        }
        if (input == gissade) {
            System.out.println("du har gissat rätt");
            System.out.println("efter " + antal + " försök");
        }

        System.out.println("vill du försöka igen? j/n");
        char input2 = in.nextLine().charAt(0);
        // String s1=in.nextLine();
        // char c1=s1.charAt(0);

        // if (input=='n');
        // System.exit(0);

    }
}

推荐答案

这是因为nextInt()不会消耗newLine,因此在尝试执行readLine()并尝试执行时会得到一个空字符串

This is because nextInt() won't consume the newLine, so you get an empty string when you try to do the readLine(), and try to perform

"".charAt(0);

这会引发您的异常.

尝试在nextInt()之后添加一个额外的nextLine().

Try adding an extra nextLine() after your nextInt().

一个好的做法是始终使用nextLine(),然后解析得到的字符串.例如,要获取您的int,您可以这样做:

A good practice is to always use nextLine(), and then parse the string you get. To get your int for example, you could do like this:

String intInput;
do {
  System.out.print("gissa ett nummer?");
  intInput = in.nextLine();
while(!intInput.matches("\\d+"));
int number = Integer.parseInt(intInput);

这将重复进行,直到您输入有效的数字为止.

This will repeat until you enter a valid number.

这篇关于为什么在此代码中出现StringIndexOutOfBoundsException?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆