首页 > 解决方案 > 错误:StringIndexOutOfBoundsException:字符串索引超出范围:0

问题描述

首先,很抱歉成为一个菜鸟......我正在尝试通过在 Windows 控制台中编写一个简单的计算器来训练自己。但是出现了这个错误:

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 
 0  
at java.base/java.lang.StringLatin1.charAt(StringLatin1.java:48)  
at java.base/java.lang.String.charAt(String.java:711)  
at app.main(app.java:58)

我尝试了很多方法来更改我的代码并修复错误,但我看不出我做错了什么!

我读了很多关于这个异常的答案,但我很确定 ->choice1 在键盘输入之前不是空的......

最后一件事,我不使用 IDE ......只有 cmd.exe ......

谢谢您的帮助!

这是代码:

    import mypackage.*;
import java.util.Scanner;

public class app
{
    public static void main(String[]args)
    {
        Scanner sc = new Scanner(System.in);
        char choice1 = 'y';

    while(choice1 == 'y')
    {
        System.out.print("\nWhich calcul ?\n");
        System.out.print("\n1 Addition | 2 Soustraction | 3 multiplication | 4 Division\n");
        
        int choice2 = sc.nextInt();

        switch(choice2)
        {
            case 1: System.out.print("\nAddition!\n\nEnter the first number:\n");
                    double x = sc.nextInt();
                    System.out.print("\nEnter the second number:\n");
                    double y = sc.nextInt();
                    add addition = new add(x, y);
                    break;

            case 2: System.out.print("\nSoustraction!\n\nEnter the first number:\n");
                    double a = sc.nextInt();
                    System.out.print("\nEnter the second number:\n");
                    double b = sc.nextInt();
                    sous soustraction = new sous(a, b);
                    break;

            case 3: System.out.print("\nMultiplication!\n\nEnter the first number:\n");
                    double c = sc.nextInt();
                    System.out.print("\nEnter the second number:\n");
                    double d = sc.nextInt();
                    mul multiplication = new mul(c, d);
                    break;

            case 4: System.out.print("\nDivision!\n\nEnter the first number:\n");
                    double e = sc.nextInt();
                    System.out.print("\nEnter the second number:\n");
                    double f = sc.nextInt();
                    div division = new div(e, f);
                    break;

            default: System.out.print("\nError, choose a number for operation!\n");
                    break;
        }

        choice1 = ' ';

        while(choice1 != 'y' && choice1 != 'n')
        {
            System.out.print("\nTry again ?\n");
            System.out.print("y | n\n");
            choice1 = sc.nextLine().charAt(0);
        };

    };
    
}

}

标签: javaexception

解决方案


问题是您使用的是 sc.nextLine() 而不是 sc.next()。next() 方法返回下一个输入值,而 nextLine() 方法跳过一行并返回输入。将 nextLine() 方法与 next() 方法交换应该可以修复错误


推荐阅读