2017-09-26 42 views
1

我正在掃描一個帶有開關盒的參數文件到一個Stack,並且它跳過了一個.nextDouble命令的值?Java掃描器nextDouble命令跳過切換大小寫的值?

這裏是我的代碼片段:

while (stackScanner.hasNextLine()) {   

    switch(stackScanner.next()) { 

    case"+": { 
     operator= new operationNode("+"); 
     stack.push(operator);} 

    case"-":{ 
     operator= new operationNode("-"); 
     stack.push(operator);} 

    case"*":{ 
     operator= new operationNode("*"); 
     stack.push(operator);} 

    case"/":{ 
     operator= new operationNode("/"); 
     stack.push(operator);} 

    case"^":{ 
     operator= new operationNode("^"); 
     stack.push(operator);} 

    while(stackScanner.hasNextDouble()) { 
     stack.push(new numberNode(stackScanner.nextDouble())); 
    } 
} 

的問題是在這裏最後一行,在參數文件包含以下內容:^ 2 - 3/2 6 * 8 + 2.5 3

然而,掃描儀只收集:^ 2 - 3/6 * 8 + 3

所以它跳過了第一個數字在這裏來了一對(2和2.5)。

事情是,當我在while循環的末尾添加stackScanner.next();時,它保存的唯一數字是那些值2和2.5?

+0

你有沒有注意到你的情況沒有中斷,並且while循環在switch語句中? –

+0

@MauricePerry我將它作爲默認值:但它沒有讀取某些值。也打破似乎沒有影響我的結果(?) – Gege

+0

你確定你已經發布了真實的代碼嗎?當我複製並粘貼它時,我沒有看到你說你看到的結果。特別是,我的堆棧如下所示:'[^,2.0, - ,*,/,^,3.0,/,^,2.0,6.0,*,/,^,8.0,+, - ,*,/,^, 2.5,3.0]',這與@ MauricePerry的觀察一致,即你缺少'break'語句。 – DaveyDaveDave

回答

1

複製你的代碼,並稍微修改使用Stack<String>而不是實現您operationNodenumberNode班,我發現了以下工作爲(我覺得)你想到:

public static void main(String... args) { 
    Scanner stackScanner = new Scanner("^ 2 - 3/2 6 * 8 + 2.5 3"); 

    Stack<String> stack = new Stack<>(); 

    while (stackScanner.hasNextLine()) { 

     switch (stackScanner.next()) { 
      case "+": { 
       stack.push("+"); 
       break; 
      } 

      case "-": { 
       stack.push("-"); 
       break; 
      } 

      case "*": { 
       stack.push("*"); 
       break; 
      } 

      case "/": { 
       stack.push("/"); 
       break; 
      } 

      case "^": { 
       stack.push("^"); 
       break; 
      } 
     } 

     while (stackScanner.hasNextDouble()) { 
      stack.push(Double.toString(stackScanner.nextDouble())); 
     } 
    } 

    System.out.println(stack); 
} 

也就是說,我已經添加了您似乎不需要的break;語句(也許某種類型的JVM差異?),並將while循環移至switch之外。

0

你需要用switchwhile和移動的double處理成default塊,例如:

while (stackScanner.hasNextLine()) { 
    String nextToken = stackScanner.next(); 
    switch(nextToken) { 

    case"+": { 
     System.out.println("+"); 
     break; 
     } 

    case"-":{ 
     System.out.println("-"); 
     break; 
    } 

    case"*":{ 
     System.out.println("*"); 
     break; 
    } 

    case"/":{ 
     System.out.println("/"); 
     break; 
    } 

    case"^":{ 
     System.out.println("^"); 
     break; 
    } 

    default: 
     if(isDouble(nextToken)){ 
      //Do something 
     } 
     break; 
    } 
} 

您還需要編寫檢查double的方法。它看起來像這樣:

private boolean isDouble(String number){ 
    try{ 
     Double.parseDouble(number); 
     return true; 
    }Catch(Exception e){ 
     return false; 
    } 
} 
+0

對不起 - 我不認爲這是真的。這將只處理每行一個令牌。如果輸入是單行 - 「^ 2 - 3/2 6 * 8 + 2.5 3」,它將處理「^」然後停止。 – DaveyDaveDave