-4

第 15 行ch = s1.charAt(0);,为什么 ch 没有得到 s1 的第 0 个字,即 operator 。

我尝试过不使用 try-catch 方法,但错误与异常有关

现在没有异常,没有错误,但程序不要求操作员,直接在输入第一个和第二个值后,它显示异常“不能这样做”

请发表您的友好回复,谢谢

import java.util.Scanner;

class apples {
    public static void calcu() {
        try{
            int a, b;
            String s1;
            char ch;
            Scanner sc = new Scanner(System.in);
            System.out.print("Enter the 1st value : ");
            a = sc.nextInt();
            System.out.print("Enter the 2nd value : ");
            b = sc.nextInt();
            System.out.print("Enter the operator : ");
            s1 = sc.nextLine();
            ch = s1.charAt(0);
            System.out.println("yo");

                switch(ch){
                case '+' : System.out.print("sum is " + (a+b));
                case '-' : System.out.print("Substraction is : " +(a-b));
                case '*' : System.out.print("Multiplication is : " + (a*b));
                case '/' : System.out.print("Multiplication is : " + (a/b));
                default  : System.out.print("wtf yo");
                }
        }
        catch(Exception e) {
            System.out.println("cant do that ");
        }

    }

    public static void main(String args[]) {
        apples obj = new apples();
        obj.calcu();
    }
}
4

1 回答 1

3

您应该替换nextIntnextLine

        System.out.print("Enter the 1st value : ");
        a = Integer.parseInt(sc.nextLine());
        System.out.print("Enter the 2nd value : ");
        b = Integer.parseInt(sc.nextLine());
        System.out.print("Enter the operator : ");
        s1 = sc.nextLine();
        ch = s1.charAt(0);

s1 = sc.nextLine();follow时b = sc.nextInt(),它返回一个空字符串,因为它返回包含该 int 的行的结尾。当您尝试获取空字符串的第一个字符时,您会收到 IndexOutOfBoundsException。

于 2014-12-23T11:59:29.687 回答