Java扫描器nextDouble命令跳过切换大小写的值?
我正在扫描一个带有开关盒的参数文件到一个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?
复制你的代码,并稍微修改使用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
之外。
你需要用switch
到while
和移动的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;
}
}
对不起 - 我不认为这是真的。这将只处理每行一个令牌。如果输入是单行 - “^ 2 - 3/2 6 * 8 + 2.5 3”,它将处理“^”然后停止。 – DaveyDaveDave
你有没有注意到你的情况没有中断,并且while循环在switch语句中? –
@MauricePerry我将它作为默认值:但它没有读取某些值。也打破似乎没有影响我的结果(?) – Gege
你确定你已经发布了真实的代码吗?当我复制并粘贴它时,我没有看到你说你看到的结果。特别是,我的堆栈如下所示:'[^,2.0, - ,*,/,^,3.0,/,^,2.0,6.0,*,/,^,8.0,+, - ,*,/,^, 2.5,3.0]',这与@ MauricePerry的观察一致,即你缺少'break'语句。 – DaveyDaveDave