我无法理解为什么扫描仪没有拾取明显存在的“(”字符。当我尝试保存我的程序时,出现一个弹出窗口,指出某些字符无法识别没有以正确的编码保存。(我正在使用 Eclipse,它使用 Cp1252 编码,如果这有任何帮助的话)我将其更改为 UTF-8,现在我遇到了这些问题。
String input = "a 0 ( b 4 ( * 100 b 6 ) w 9 ( x 3 y 5 ( * 2 z 3 ) ) )";
LinkedStack<TreeNode<String>> stack = new LinkedStack<TreeNode<String>>();
Scanner in = new Scanner(input);
while (in.hasNext()) {
String temp = in.next();
System.out.println("Here's a temp:" + temp);
if (temp == "(") {
System.out.println("Continuing.");
continue;
}
else if (temp == ")") {
System.out.println("Closed Paren.");
TreeNode<String> leftChild = stack.pop();
TreeNode<String> rightChild = stack.pop();
TreeNode<String> parent = stack.pop();
parent.setLeft(leftChild);
parent.setRight(rightChild);
stack.push(parent);
}
else {
System.out.println("Hit the else block.");
String label = temp;
String distanceString = in.next();
double distance = Double.parseDouble(distanceString);
System.out.println("Here is the distance of this node: " +distance);
stack.push(new TreeNode<String>(label, null, null, distance));
}
}
最佳答案
当像这样使用 ==
时,会检查两个字符串是否具有相同的引用,在本例中将返回 false
。
您应该使用 temp.equals("(")
和 temp.equals(")")
等等。
使用 equals
方法比较字符串会检查它们的值,这里是正确的。
关于java - 如果条件明显为真,则 if-else block 不会返回 true,我该怎么办?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47731063/