从用户获取字符输入时的IndexOutOfBoundsException

时间:2014-12-23 11:54:16

标签: java exception charat

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

我已尝试过不使用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();
    }
}

1 个答案:

答案 0 :(得分:3)

您应该将nextInt替换为nextLine

        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();跟随b = sc.nextInt()时,它返回一个空字符串,因为它返回包含该int的行的结尾。当您尝试获取空String的第一个字符时,会得到IndexOutOfBoundsException。