我有一个非常好的基本程序;当我输入单个数字时。但是当做一个像1337 - 456 + 32这样的表达时,程序不会继续前进并且表现得像我什么也没做。 它没有冻结或输出错误信息,它只是停止了。\
这是代码:
import java.io.*;
import java.util.*;
public class Tester {
public static void main(String args[]) {
Scanner kb = new Scanner(System.in);
System.out.print("Enter number: ");
String s = kb.nextLine();
Scanner sc = new Scanner(s);
//Set delimiters to a plus sign surrounded by any amount of white space...or...
// a minus sign surrounded by any amount of white space.
sc.useDelimiter("\\s*");
int sum = 0;
int temp = 0;
int intbefore = 0;
if (sc.hasNext("\\-")) {
sc.next();
if (sc.hasNextInt()) {
intbefore = sc.nextInt();
int temper = intbefore * 2;
intbefore = intbefore - temper;
}
}
if (sc.hasNextInt()) {
intbefore = sc.nextInt(); //now its at the sign (intbefore = 5)
}
sum = intbefore;
while (sc.hasNext()) {
if(sc.hasNext("\\+")) { //does it have a plus sign?
sc.next(); //if yes, move on (now at the number)
System.out.println("got to the next();");
if(sc.hasNextInt()) { //if there's a number
temp = sc.nextInt();
sum = sum + temp; //add it by the sum (0) and the sum of (5) and (4)
System.out.println("added " + sum);
}
}
if(sc.hasNext("\\-")) {
sc.next();
System.out.println("got to the next();");
if (sc.hasNextInt()) {
temp = sc.nextInt();
sum = sum - temp; //intbefore - temp == 11
System.out.println("intbefore: " + intbefore + " temp: " + temp);
System.out.println("subtracted " + sum); // subtracted by 11
}
}
}
System.out.println("Sum is: " + sum);
}
}
帮助解决为什么会发生这种情况以及如何解决这个问题? (如果有帮助,我正在使用netbeans)
另外,假设输入在每个数字Ex:123 + -23 - 5
之间有一个空格答案 0 :(得分:2)
我尝试执行你的代码,这就是我找到的。
假设您的输入为12 + 1。
不是c.hasNextInt()
会将1
分配给intbefore
。
接下来,代码中的while
循环将进入无限循环cos sc.hasNext()
将始终为真(并且在这种情况下返回2)并且它与{2}中的条件不匹配{1}}循环因此使您的代码在无限循环中运行。现在继续努力吧。一切顺利。
答案 1 :(得分:1)
首先尝试将分隔符更改为"\\s+"
,或者只使用默认分隔符