第一次使用 try、catch 和标签

Using try, catch and a label for the first time

我们刚刚在昨晚的讲座中讨论了 try-catch 主题。不需要将其放入此作业中,但我想我会试一试。

我已经为此苦苦挣扎了一段时间。使用 continue 语句将其踢回 catch 块的开头,以便其中的 println 在永无止境的循环中执行。

很明显,这些东西叫做标签。我发现当我试图弄清楚如何解决继续问题时。我尝试按照我在示例代码中看到的那样放入一个标签,现在它只是在 break 语句上给我一个编译器错误,提示“进程标志丢失”。

我做错了什么?

    do {
        // Prompt
        
    try {
       process: nbPlayers = keyboard.nextInt(); 
        
        }
        catch(Exception e) {

            nbPlayers=0;    
            if (attempts<4) {
                System.out.println("Incorrect input type. You have now made " + attempts +". Please enter an integer from 2 to 4.");
                ++attempts;
                break process;              

            }
            else {
                System.out.println("Invalid input. You have now made " + attempts +". This game only allows 4 chances to input the requested number of players.\n Shutting down the program now.");
                System.exit(0);
            }
            
        }
    
        if(attempts < 4 && nbPlayers >= 2 && nbPlayers <= 4) {
            valid = true;
        } else if(attempts < 3) {
            System.out.println("Invalid input. You have now made " + attempts +". This game only allows 4 chances to input the requested number of players.\nYou are allowed to try again.");
        } else if(attempts == 3) {
            System.out.println("Invalid input. You have now made " + attempts +". This game only allows 4 chances to input the requested number of players.\nYou are allowed to one more time.");
        } else if(attempts == 4) {
            System.out.println("Invalid input. You have now made " + attempts +". This game only allows 4 chances to input the requested number of players.\n Shutting down the program now.");
            System.exit(0);
        }

        ++attempts;
        
    } while(!valid);

你的问题不是很清楚。让我们谈谈代码。 你怎么看这个?

 int attempts = 0; // is it a good initialization ?
 int nbPlayers = 0; // is it a good initialization ?
 boolean valid = false; // is it a good initialization ?
 String nbPlayersString = "";
 do {
        // Prompt
        
    try {
           nbPlayersString = keyboard.nextLine(); 
           nbPlayers = Integer.parseInt(nbPlayersString);
           if(2<= nbPlayers  && nbPlayers <= 4) {
               valid = true;
           }
           else {
               System.out.println("Bad Attempt " + (attempts + 1) +". Invalid number of players.");
           }
        }
        catch(Exception e) {
            nbPlayers=0; 
            System.out.println("Bad Attempt " + (attempts + 1) +". Wrong input type. ");
  
        }
    
        

        ++attempts;
        
    } while(!valid && attempts < 4);
 
 if(valid)
     System.out.println("GOOD JOB!");
 else {
     System.out.println("You have exhausted all your chances. Program will terminate!");
     System.exit(0);
 }

最终编辑 在输入无效值(字符串而不是整数)后,您似乎也遇到了 Scanner.nextInt() 的缓存问题。因此,在接下来的尝试中,Scanner 缓存仍然有错误的值并考虑了它。