IndexOutOfBoundsException when taking character input from the user

删除回忆录丶 提交于 2019-12-20 07:56:25

问题


In the 15th line ch = s1.charAt(0);, why ch is not getting the 0th word of s1, i.e., the operator .

I've tried without using the try-catch method but then the error was regarding the exception

and now no exception, no errors but the program don't ask for operator and directly after inputting the 1st and 2nd value , it shows the exception"can't do that"

please post your kind replies, thanks

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:


You should replace nextInt with 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);

When s1 = sc.nextLine(); follows b = sc.nextInt(), it returns an empty String, since it returns the end of the line that contained that int. When you try to get the first character of an empty String, you get an IndexOutOfBoundsException.



来源:https://stackoverflow.com/questions/27619851/indexoutofboundsexception-when-taking-character-input-from-the-user

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!