3

我有这个基本程序,在输入个位数时效果很好。但是当计算一个多位数的表达式时,比如 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

4

2 回答 2

2

我试图执行你的代码,这就是我发现的。

假设您的输入是 12+1。

Not sc.hasNextInt()会给你1你要分配的东西intbefore

接下来while,您的代码中的循环将进入无限循环 cos sc.hasNext()将始终为真(在这种情况下返回 2 )并且它与循环内的两个 if 条件不匹配,while从而使您的代码在无限循环中运行。现在继续努力。祝一切顺利。

于 2012-12-29T07:18:08.717 回答
1

尝试像一开始一样更改测光仪,"\\s+"或者只使用默认的测光仪

于 2012-12-29T07:18:16.613 回答