2016-03-05 67 views
-1

我想把一个扫描仪内的案件。这是发生了什么:开关柜式扫描仪Java问题

[中]计算

[中] 5

[出]对不起,我不明白 '[空格]'。再试一次。

while (running) { 
     stringInput = in.nextLine(); 
     switch (stringInput) { 
      case "help": 
       System.out.println("[NYI]"); 
       break; 
      case "calc": 
       longInput = in.nextLong(); 
       if (longInput > Long.MAX_VALUE) { 
        System.err.print("Sorry, that is too big, try again."); 
        break; 
       } else if (Math.signum(longInput) < 1) { 
        System.err.println("Sorry, that number is negative/zero , try again."); 
        continue; 
       } else { 
        sleep(longInput); 
        calc += cps * (longInput/1000); 
        break; 
       } 
      default: 
       System.err.println("Sorry, I don't understand '" + stringInput + "'. Try again."); 
     } 
    } 

我不知道为什么会发生这种情况。请帮忙!

+1

switch中的continue关键字的用途是什么? – Theo

+0

输入是什么? – gidim

回答

1

当您在switch语句中使用continue语句时,您将需要使用标签。要做到这一点只需更改您的代码如下:

Mainloop: 
while (running) { 
    stringInput = in.nextLine(); 
    switch (stringInput) { 
     case "help": 
      System.out.println("[NYI]"); 
      continue Mainloop; 
     case "calc": 
      longInput = in.nextLong(); 
      if (longInput > Long.MAX_VALUE) { 
       System.err.print("Sorry, that is too big, try again."); 
       continue Mainloop; 
      } else if (Math.signum(longInput) < 1) { 
       System.err.println("Sorry, that number is negative/zero , try again."); 
       continue Mainloop; 
      } else { 
       sleep(longInput); 
       calc += cps * (longInput/1000); 
       continue Mainloop; 
      } 
     default: 
      System.err.println("Sorry, I don't understand '" + stringInput + "'. Try again."); 
    } 
} 

略高于while循环线Mainloop:分配标签while循环。标签就像一个名字,当你在一个switch case中有一个continue语句时,你需要告诉它哪个循环要继续。要做到这一点,只需将标签添加到continue语句。这样continue Mainloop; 此问题也已在this question.

或者解释的,你可以只更换一个break;语句continue语句。 break语句将会跳出switch case而不是while循环。

希望这有助于:)