IndexOutOfBounds从用户获取字符输入时出现异常 [英] IndexOutOfBoundsException when taking character input from the user

查看:201
本文介绍了IndexOutOfBounds从用户获取字符输入时出现异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

我试过没有使用try-catch方法,但是错误是关于例外

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"

请发表您的回复,谢谢

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();
    }
}


推荐答案

你应该用 nextLine 替换 nextInt

        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的行的结尾。当您尝试获取一个空字符串的第一个字符时,您会得到一个IndexOutOfBoundsException。

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.

这篇关于IndexOutOfBounds从用户获取字符输入时出现异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆