简体   繁体   English

我怎样才能避免从循环外获取内容?

[英]How i can avoid getting content from outside the loop?

If I write:如果我写:

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");
        }
    }
    
}

Each time I take a response I will also get "let's play another game" printed.每次我回复时,我都会打印“让我们玩另一个游戏”。 For example:例如:

https://i.stack.imgur.com/bEjkP.png https://i.stack.imgur.com/bEjkP.png

Since you want to wait for the user to enter a long range weapon then it means you need to loop infinitely until user input weapon is not 3. You were thinking in right direction but the code block placement wasn't right.由于您想等待用户输入远程武器,那么这意味着您需要无限循环,直到用户输入武器不是 3。您的想法是正确的,但代码块的位置不正确。 Try this code which wait indefinitely until userChoice is not 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");
    
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM