我真的是 Java 的新手,但我正在尝试使用这个程序。这是一个执行基本数学计算的程序,但需要用户输入。
import java.io.*;
import java.util.Scanner;
public class Math
{
public static void main(String[] args)
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
Scanner in = new Scanner(System.in);
int sa1, sa2, ss1, ss2, sm1, sm2, s;
boolean c = false;
double sd1, sd2;
while(c==false)
{
System.out.print("Do you want to: \n[1] Add. \n[2] Subtract. \n[3] Multiply. \n[4] Divide. \n[5] Exit \nPlease insert an option number below and press enter: ");
s = in.nextInt();
if (s==1)
{
System.out.print("You have chosen option 1 \nPlease enter your first number: ");
sa1 = in.nextInt();
System.out.print("Please enter your second number: ");
sa2 = in.nextInt();
System.out.print(sa1+ " + " +sa2+ " = " +(sa1+sa2));
}
if (s==2)
{
System.out.print("You have chosen option 2 \nPlease enter your first number: ");
ss1 = in.nextInt();
System.out.print("Please enter your second number: ");
ss2 = in.nextInt();
System.out.println(ss1+ " - " +ss2+ " = " +(ss1-ss2));
}
if (s==3)
{
System.out.print("You have chosen option 3 \nPlease enter your first number: ");
sm1 = in.nextInt();
System.out.print("Please enter your second number: ");
sm2 = in.nextInt();
System.out.println(sm1+ " x " +sm2+ " = " +(sm1*sm2));
}
if (s==4)
{
System.out.print("You have chosen option 4 \nPlease enter your first number: ");
sd1 = in.nextDouble();
System.out.print("Please enter your second number: ");
sd2 = in.nextDouble();
System.out.println(sd1+ " divided by " +sd2+ " = " +(sd1/sd2));
}
if(s>=6)
{
System.out.println("You have entered an incorrect option");
}
System.out.print("Would you like to try again? (Y/N): ");
String ans = in.nextLine();//prob with this line
char ans1 = ans.charAt(0);//or this line
if (ans1=='N' || ans1=='n')
{
c = true;
}
if(s==5)
{
c = true;
}
}
}
}
当我编译它时,我收到一个错误:线程“主”java.lang.StringIndexOutOfBoundsException 中的异常:字符串索引超出范围:0 at java.lang.String.charAt(Unknown Source) at Math.main(Math.java:58 )
我试过到处寻找答案。谁能帮我这个?它需要能够从用户那里读取“Y”或“N”。