2017-05-07 53 views
0
Story.direct3(); 
      br.readLine(); 
      Story.des(); 
      try{ 
      short choice1 = Short.parseShort(br.readLine()); 

      switch(choice1){ 
       case 1: 
        Display.yes(); 
        br.readLine(); 
        Story.rid(); 
        String answ = br.readLine(); 

        if ("Gravity".equals(answ) || "gravity".equals(answ)){ 
         Display.correct(); 
         Short choice2 = Short.parseShort(br.readLine()); 

         switch(choice2){ 
          case 1: 

           break; 
         } 
        } 
        else{ 
         int less = player.hp - 10; 
         System.out.println("Wrong answer! Your hp will be lessen by 10. The correct answer is : 'Gravity'"); 
         System.out.println("Your remaining HP is: " + less + "[press enter to continue...]"); 
         br.readLine(); 
         Story.wrong(); 
         br.readLine(); 

        } 
        break; 
       case 2: 
        Story.wrong1(); 
        br.readLine(); 
        break; 
      } 
      break; 
    } 
      catch(NumberFormatException ex){ 
       System.out.println("Would you like to change your battle item?" 
      + "\n[1] Yes" 
      + "\n[2] No"); 
      } 

我刚开始编写Java代码近2个月,问我的朋友的代码,并试图尝试就可以了。事情是我不知道如何把try/catch。我错过了什么吗?的try/catch似乎我不知道在哪里把它

+2

你在哪里需要它?代码现在有什么问题?请多解释一下你遇到的问题。 –

+0

@SamiKuhmonen当我输入错误的答案时,玩家应该可以装备战斗物品。这就是“你想改变你的战斗项目吗?”出来。我应该怎么做? –

回答

1

当涉及到异常处理时,您应该只放入可能在try-catch块内导致一些异常的行/代码块。例如,在你的情况,你可以拥有的try-catch用户输入以确保他提供的整数:

try{ 
     short choice1 = Short.parseShort(br.readLine()); 
}catch(NumberFormatException ex){ 
    System.out.println("Would you like to change your battle item?" 
     + "\n[1] Yes" 
     + "\n[2] No"); 
} 

但这只会检查自己的输入号码,如果他写的东西下来3或4,你的开关不处理?您应该包含默认情况下的开关或检查数字是否大于2或小于1并重复问题。

String s = br.readLine(); 
while(!s.equals("2") || s.equals("1")){ 
    System.out.println("Invalid input, try again:");// change message to fit your game 
    s = br.readLine(); 
} 
if(s.equals("1")){ 
    //Do something 
}else{ 
    //Do something 
} 

请记住,你应该尽量避免使用try-catch代码是否可以做到这一点,而不使代码过于复杂:

而且这种类型的输入可以不依赖于错误处理的处理更容易。在这种情况下,你最终得到更简单的代码。

相关问题