簡體   English   中英

java嵌套的for循環不起作用…請幫助

[英]java nested for loop not working…help please

我是Java的新手,我試圖用Eclipse編寫一個程序,當用戶鍵入'r'時,它將隨機選擇一把槍“給”他們五把槍之一。使命召喚僵屍。 我對為什么輸入“ r”后為什么不輸出隨機“ gun”感到困惑。 請幫忙!!!

import java.util.Random;
import java.util.Scanner;

class apples{
public static void main(String[] args){
    System.out.println("Type 'r' for a random gun");

    Random dice = new Random();
    int number;

    Scanner input = new Scanner(System.in);
    String userinput = input.nextLine();
    if (userinput=="r"){
        for (int counter=1; counter<=1; counter++){
            number = 1+dice.nextInt(5);
            if (number==1){
                System.out.println("gun 1");
            }else if (number==2){
                System.out.println("gun 2");
            }else if (number==3){
                System.out.println("gun 3");
            }else if (number==4){
                System.out.println("gun 4");
            }else if (number==5){
                System.out.println("gun 5");
            }
        }
    }else{
        System.out.println(" ");
    }

}
}

嘗試使用

int randomInt = dice.nextInt(4);
if(userInput.equals("r")){
     if (randomInt==1){
            System.out.println("gun 1");
        }else if (randomInt==2){
            System.out.println("gun 2");
        }else if (randomInt==3){
            System.out.println("gun 3");
        }else if (randomInt==4){
            System.out.println("gun 4");
        }else if (randomInt==5){
            System.out.println("gun 5");
        }

}

所以總體的最終代碼應該像

public class test {

public static void main(String[] args) {
    System.out.println("Type 'r' for a random gun");

    Random dice = new Random();
    int number;

    Scanner input = new Scanner(System.in);
    String userinput = input.nextLine();
    int randomInt = dice.nextInt(4);
    if (userinput.equals("r")) {
        if (randomInt == 1) {
            System.out.println("gun 1");
        } else if (randomInt == 2) {
            System.out.println("gun 2");
        } else if (randomInt == 3) {
            System.out.println("gun 3");
        } else if (randomInt == 4) {
            System.out.println("gun 4");
        } else if (randomInt == 5) {
            System.out.println("gun 5");
        }
    }

}

}

編輯-抱歉,呵呵! 我沒有注意到@lal的評論,顯然他首先注意到了該錯誤,因此我的回答是他的闡述。
當您這樣做時:

if (userinput=="r")

您實際上是在比較對象的引用,而不是實際的對象。operator ==比較對象的引用,因此輸出實際上是“false”而不是“true.”自然,這首先使人們感到驚訝。

要糾正此問題,您應該嘗試使用equals方法,如下所示:

 if (userinput.equals("r"))

請注意, java.lang.Object的默認equals()實現比較內存位置,並且僅當兩個引用變量指向同一內存位置(即本質上它們是同一對象)時才返回true。因此,要測試兩個對象是否相等就等同性( 包含相同的信息 )而言,您必須重寫equals()方法。(不重寫equals()方法,它的作用類似於== 。正如我在對象上使用==運算符時所說的,它只是檢查引用是否屬於同一對象,而不是引用的成員包含相同的值。)

但是,這里不需要覆蓋,因為String類已經覆蓋了它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM