我正在将带有 switch case 的参数文件扫描到 Stack
中,并且它使用 .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?
最佳答案
复制您的代码并稍微修改以使用 Stack<String>
而不是实现您的 operationNode
和numberNode
类,我发现以下内容符合(我认为)您的期望:
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
之外的循环.
关于Java Scanner nextDouble 命令使用 switch case 跳过值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46421569/