gpt4 book ai didi

读取用户输入时发生 Java ArrayIndexOutOfBoundsException

转载 作者:行者123 更新时间:2023-12-01 11:07:01 24 4
gpt4 key购买 nike

每当我尝试使用高于 eq[0] 的任何值时,我最终得到 ArrayIndexOutOfBoundsException .

我的代码:

import java.util.Scanner;

public class Calc{
public static void main(String[] args){
Scanner in=new Scanner(System.in);
String[] eq=in.next().split(" ");

double a=Double.parseDouble(eq[0]);
double b=Double.parseDouble(eq[-1]);

if(eq[1]=="+"){
System.out.println(">>"+String.valueOf(a+b));
}else if(eq[1]=="-"){
System.out.println(">>"+String.valueOf(a-b));
}else if(eq[1]=="/"){
System.out.println(">>"+String.valueOf(a/b));
}else if(eq[1]=="*"){
System.out.println(">>"+String.valueOf(a*b));
}
}
}

最佳答案

eq[-1] -1 index is problem

eq[1]=="+" // logical error use equals() method to compare String.

           Scanner in=new Scanner(System.in);
String[] eq=in.nextLine().split(" "); // use nextLine() instead of next().

double a=Double.parseDouble(eq[0]);// 1st operand
double b=Double.parseDouble(eq[2]);// 3rd operand

if(eq[1].equals("+")){ //operator // compare string with equals method not with (==).
System.out.println(">>"+String.valueOf(a+b));
}else if(eq[1].equals("-")){
System.out.println(">>"+String.valueOf(a-b));
}else if(eq[1].equals("/")){
System.out.println(">>"+String.valueOf(a/b));
}else if(eq[1].equals("*")){
System.out.println(">>"+String.valueOf(a*b));
}

关于读取用户输入时发生 Java ArrayIndexOutOfBoundsException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32843310/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com