IndexOutOfBoundsException when taking character input from the user

后端 未结 1 1711
终归单人心
终归单人心 2021-01-29 15:16

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

相关标签:
1条回答
  • 2021-01-29 15:58

    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.

    0 讨论(0)
提交回复
热议问题