2012-12-29 19 views
3

我有這個基本程序工作得很好;當我輸入單個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

+0

是什麼通過代碼在調試器中顯示步進?你是否陷入了一個無限循環的地方(試着在'while'之後加上'println'),或者是一個函數調用沒有返回?如果你的'while(sc.hasNext())'塊中有' – Krease

+0

',那麼如果字符串的其餘部分沒有空格,'sc.Next();'語句將返回所有的字符串。 –

+0

你們是對的,它陷入了無限循環。 – nmd

回答

1

嘗試改變dilimeter爲"\\s+"擺在首位或只使用默認的

+0

哇,這工作,謝謝 – nmd

2

我試圖執行你的代碼,這就是我找到。

假設您的輸入是12 + 1。

不是s c.hasNextInt()會給你1你指定給intbefore

下一步while循環在你的代碼將無限循環COS sc.hasNext()將永遠是真實的(在這種情況下返回2)不匹配兩個,如果while循環內部條件從而使你的代碼運行在無限循環。現在繼續努力。祝一切順利。

+0

你是對的,但我忘了說,假設輸入將始終有一個空間例如:12 + 1.我將這個問題添加到 – nmd

相關問題