IndexOutOfBoundsException when taking character input from the user

最后都变了- 提交于 2019-12-02 13:41:01

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.

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