簡體   English   中英

我怎樣才能避免從循環外獲取內容?

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

如果我寫:

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

每次我回復時,我都會打印“讓我們玩另一個游戲”。 例如:

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

由於您想等待用戶輸入遠程武器,那么這意味着您需要無限循環,直到用戶輸入武器不是 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