我必须制作一个简单的计算器,询问有效的运算符,并在运算符为'S'字符时停止。然后,它要求2个数字进行计算。第一次计算它的时候没有任何错误,但是一旦它尝试询问下一个运算符,我将得到以下错误:
线程“主”中的异常java.lang.StringIndexOutOfBoundsException: 字符串索引超出范围:0处 Main.main(Main.java:16)的java.lang.String.charAt(String.java:658)
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
boolean geldigeOperator;
double getal1;
double getal2;
char operator;
do {
System.out.print("Operator (S = stoppen): ");
String s = input.nextLine();
//pakt het eerste character van de string die is ingevoerd door de gebruiker
operator = s.charAt(0);
geldigeOperator = isGeldigeOperator(operator);
if (!geldigeOperator) {
System.out.println("Operator is ongeldig");
System.out.println("");
} else {
System.out.print("Eerste getal: ");
getal1 = input.nextDouble();
System.out.print("Tweede getal: ");
getal2 = input.nextDouble();
printBerekening(operator, getal1, getal2);
System.out.println();
}
} while (!(operator == 'S'));
}
public static boolean isGeldigeOperator(char karakter) {
if (karakter == '+' || karakter == '-' || karakter == '*' || karakter == '/' || karakter == '%') {
return true;
} else {
return false;
}
}
public static void printBerekening(char operator, double getal1, double getal2) {
double result = 0;
switch(operator) {
case '+':
result = getal1 + getal2;
System.out.println(getal1 + " + " + getal2 + " = " + result);
break;
case '-':
result = getal1 - getal2;
System.out.println(getal1 + " - " + getal2 + " = " + result);
break;
case '*':
result = getal1 * getal2;
System.out.println(getal1 + " * " + getal2 + " = " + result);
break;
case '/':
result = getal1 / getal2;
System.out.println(getal1 + " / " + getal2 + " = " + result);
break;
case '%':
result = getal1 % getal2;
System.out.println(getal1 + " % " + getal2 + " = " + result);
break;
}
}
}
工作代码应给出以下结果:
答案 0 :(得分:1)
在您的else块的末尾添加input.nextLine();
。
这里的问题是,当您呼叫input.nextLine()
时,它最终会消耗掉整个行以及换行符,但是当您使用input.nextDouble()
时,它将仅占用数字而不是 newLline 末尾的字符,因此当您在nextLine()
之后调用nextDouble()
时,nextLine()
仅读取 newLine 字符,您会收到错误消息。
答案 1 :(得分:0)
将扫描程序的创建移至do..while循环。 这样,您在操作结束时拥有的任何冗余输入都将被销毁,并且每次启动新的迭代时,您都会得到一个闪亮的新Scanner。
do {
Scanner input = new Scanner(System.in);
System.out.print("Operator (S = stoppen): ");
String s = input.nextLine();
....
} while (!(operator == 'S'));