我有這個基本程序工作得很好;當我輸入單個diget數字。但是當做一個像1337 - 456 + 32這樣的表達時,程序不會繼續前進,就像我什麼都不做。 它沒有凍結或輸出錯誤信息,它只是停止\在java中有2個或多個帶分隔符的數字號碼
下面的代碼:
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())'塊中有' – Krease
',那麼如果字符串的其餘部分沒有空格,'sc.Next();'語句將返回所有的字符串。 –
你們是對的,它陷入了無限循環。 – nmd