簡體   English   中英

如何在 while 循環中使用字符串數組和掃描儀?

[英]How do I use a string array and scanner in a while loop?

有人告訴我將一個功能性的自動 for 循環通過房子里的所有房間變成一個 while 循環,允許用戶輸入他們接下來進入的房間 go。

問題是您需要在while循環中使用數組和掃描儀,我正在努力思考如何做到這一點,數組不知何故需要成為while循環中條件的一部分,我需要能夠輸入什么我想在數組中訪問房間而不修改房間數組中的字符串值。

這是我想太多了嗎?

public static void main(String[] args) {
        Scanner myInput = new Scanner(System.in);
        
        String[] rooms; 
        rooms = new String[] {"hall", "kitchen", "lounge", "bedroom", "bathroom"};
        String room = "";
        String lastRoom = "";
        room = myInput.next();
        while (! room.equals("exit")){
            System.out.print("Here we are ");
            if (room.equals(lastRoom)) {
                System.out.print("back ");
            }
            System.out.print("in the " + room + ". ");
            switch (room){
                case "kitchen": System.out.println("Can you smell the coffee? "); break;
                case "lounge": System.out.println("You can fit a nice corner sofa in here! "); break;
                case "bedroom": System.out.println("This is where all the action and snoring happens. "); break;
                case "bathroom": System.out.println("The bath also has a shower for quick washes. "); break;
                default:
                    break;
            }
            lastRoom = room;
            room = myInput.next();
        }
        myInput.close();
    } 

從技術上講,它可以工作,但我根本沒有使用數組,我需要讓它做同樣的事情,但使用數組而不是使用空字符串變量。

您通過 [index] 引用數組值,其中索引從 0 開始。

而不是 switch 使用 if else 語句(您不能將 switch 與數組值一起使用,因為 switch 需要編譯時間常量),如下所示:

if (room.equals(rooms[1])) {
     System.out.println("Can you smell the coffee? ");
} else if (room.equals(rooms[2])) {
   System.out.println("You can fit a nice corner sofa in here! ");
} // ...

暫無
暫無

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

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