这个程序给出错误我想在一行中输入[重复]

问题描述 投票:-2回答:1

计划是:

String main() throws IOException
{
    int c=0,b=0;
    double ans=0;
    int a[]=new int[55];
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    String  lines = br.readLine();    
    char op;
    Operators oop = new Operators();
    String[] strs = lines.trim().split(" ");
    String ch=" ";
    op = ch.charAt(0);
    for (int i = 0; i < strs.length; i++) {
        a[i] = Integer.parseInt(strs[i]); 
        System.out.println(a[i]);
        if (op=='+'||op=='-'||op=='*'||op=='/'||op=='%')
        {
            switch (op)
            {
                case '+':   ans = a[i-1]+a[i]; break;
                case '-':   ans = a[i-1]-a[i]; break;
                case '*':   ans = a[i-1]*a[i]; break;
                case '/':   ans = a[i-1]/a[i]; break;
                case '%':   ans = a[i-1]%a[i]; break;
            }
        }
        i++;
        ch = strs[i];
        op = ch.charAt(0);
    }
    return ("Answer is "+ans);
}

它给出了一个错误说:

"java.lang.ArrayIndexOutOfBoundsException: 3"

错误即将到来

ch = strs[i];

在多行我能够做但不是单行

阵列是流过的还是问题是别的

java indexoutofboundsexception
1个回答
0
投票

请根据以下内容更新您的代码:

Scanner sc = new Scanner(System.in);
String str = sc.nextLine();
String[] strs = str.trim().split(" ");
// for the following input: 2 3 +
// strs[0] is 2, strs[1] is 3, strs[2] is +  
© www.soinside.com 2019 - 2024. All rights reserved.