【发布时间】:2012-12-14 07:23:12
【问题描述】:
我有这个基本程序,在输入个位数时效果很好。但是当计算一个包含多个数字的表达式时,比如 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)
另外,我假设输入在每个数字之间都有一个空格,例如:123 + -23 - 5
【问题讨论】:
-
在调试器中单步执行代码会显示什么?您是在某处陷入无限循环(尝试在
while之后立即添加println调用),还是函数调用未返回? -
在您的
while(sc.hasNext())块中,如果字符串的其余部分没有空格,sc.Next();语句将返回所有剩余的字符串。 -
你们是对的,它陷入了无限循环。
标签: java numbers delimiter arithmetic-expressions