2016-03-07 64 views
0

我有两个类,其中一个类调用另一个类。在java中输入输出和解析错误

下面是一类Stack创建一个变量类型stack

import java.util.Iterator; 
import java.util.NoSuchElementException; 

public class Stack<Item> { 
    private Node first = null; 

    private class Node { 
     private Item item; 
     private Node next; 
    } 
    public boolean isEmpty() { return first == null; } 
    public void push(Item item) { 
     Node second = first; 
     first = new Node(); 
     first.item = item; 
     first.next = second; 
    } 
    public Item pop() { 
     Item item = first.item; 
     first = first.next; 
     return item; 
    } 
} 

在这里,我有一个名为Evaluate类,它呼吁Stack并创建基于输入堆栈。

import edu.princeton.cs.algs4.StdIn;  
import edu.princeton.cs.algs4.StdOut; 

    public class Evaluate { 
    public static void main(String[] args) { 
     Stack<String> ops = new Stack<String>(); 
     Stack<Double> vals = new Stack<Double>(); 
     while (!StdIn.isEmpty()) { 
      String s = StdIn.readString(); 
      if (s.equals("(")) ; 
      else if (s.equals("+")) ops.push(s); 
      else if (s.equals("*")) ops.push(s); 
      else if (s.equals(")")) { 
       String op = ops.pop(); 
       if (op.equals("+")) vals.push(vals.pop() + vals.pop()); 
       else if (op.equals("*")) vals.push(vals.pop() * vals.pop()); 
      } 
      else vals.push(Double.parseDouble(s)); 
      //When seeing a number, it gets pushed on to the stack 
     } 
     StdOut.println(vals.pop()); 
    } 
} 

我试过两个不同的输入:(1 + ((2 + 3) * (4 * 5)))1+2

在第一个输入案例中,终端要求另一个输入。在第二种情况下,它会返回以下错误消息:

`java.lang.NumberFormatException: For input string: "1+2" 
    at sun.misc.FloatingDecimal.readJavaFormatString(Unknown Source) 
    at java.lang.Double.parseDouble(Unknown Source) 
    at Evaluate.main(Evaluate.java:18)` 

我使用http://www.cs.princeton.edu/courses/archive/spr15/cos126/lectures/43stack.pdf作为一种资源来学习Java和上面的代码是直接从讲义。我已经看了看代码,我没有看到一个明显的错误(我认为是一个讲义,很可能现在没有。)

我知道,它会过去isEmpty,因为我的同时,有条件的正下方添加StdOut.println(3);isEmpty ),并且当我输入时它确实打印出3次三次当我输入时1 + 2

回答

0

StdIn.readString()从标准输入中读取由空白分隔的令牌。你的第二个输入不包含任何空格,所以整个字符串被解释为一个标记。 1+2不是有效的双精度型,并引发您引用的错误。尝试使用1 + 2作为输入,而不是

+0

然后结果与'(1 +((2 + 3)*(4 * 5)))'一样,它只是要求更多的输入。 – stratofortress

+0

然后isEmpty的测试失败。在输入 – egilhh

+0

中可能有空格(也许是换行符?)我试过'1 + 2'和'1 + 2'。他们都不断要求更多的输入 – stratofortress