Java 如何避免从循环外部获取内容?

Java 如何避免从循环外部获取内容?,java,Java,如果我写: import java.util.Scanner; public class Application { public static void main(String[] args) { System.out.println("please select a weapon to kill this long range zombie: "); System.out.println(" ");

如果我写:

import java.util.Scanner;

public class Application {
    public static void main(String[] args) {

        System.out.println("please select a weapon to kill this long range zombie: ");
        System.out.println(" ");
        System.out.println("Choose: ");
        System.out.printf("1:Knife  %n2:Shutgun %n3:Sniper" );
        
                
        while(true) {
        
        Scanner myWeapons = new Scanner(System.in);  // Create a Scanner object
        System.out.println(" ");
        

        int userChoice = myWeapons.nextInt();
        
      
            
        if( userChoice != 3 )  {
            System.out.println("you selected the wrong weapon,please select a long range weapon");
            
            
        } else {
            
            System.out.println("great you selected the sniper");
            
            break;
            
        }   
            System.out.println("let's play another game");
        }
    }
    
}
每次我回复时,我也会打印“让我们玩另一个游戏”。例如:


既然你想等待用户进入远程武器,那就意味着你需要无限循环,直到用户输入的武器不是3。您的思路是正确的,但代码块的位置不正确。请尝试此代码,该代码将无限期地等待,直到
userChoice
不是3

public static void main (String[] args) throws java.lang.Exception
{
    System.out.println("please select a weapon to kill this long range zombie: ");
    System.out.println(" ");
    System.out.println("Choose: ");
    System.out.printf("1:Knife  %n2:Shutgun %n3:Sniper" );
            
    Scanner myWeapons = new Scanner(System.in);  // Create a Scanner object
    System.out.println(" ");

    int userChoice = myWeapons.nextInt();
    while(userChoice != 3)  {
        System.out.println("you selected the wrong weapon,please select a long range weapon");
        userChoice = myWeapons.nextInt();
    }
    
    System.out.println("great you selected the sniper");
    
    System.out.println("let's play another game");
    
}
你说的“循环外的内容”是什么意思?你的“让我们玩另一个游戏”在循环中。虽然你的压痕被弄乱了;也许这误导了你。你说的“圈外内容”是什么意思?你的“让我们玩另一个游戏”在循环中-我在想通过“中断”;我会让循环停止,特别是因为我用“}”关闭了else,正如答案所说,这只是我的位置不好,谢谢你的问题,我对此表示感谢。