简体   繁体   English

如何在 while 循环中使用字符串数组和扫描仪?

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

I was told to turn a functional auto for loop that goes through all the rooms in the house into a while loop that allows the user to type what room they go into next.有人告诉我将一个功能性的自动 for 循环通过房子里的所有房间变成一个 while 循环,允许用户输入他们接下来进入的房间 go。

The issue is you need to use the array and scanner in the while loop and I am struggling to think on how to do this, the array somehow needs to be part of the condition in the while loop and I need to be able to type what room I want to access in the array without modifying the string values in my rooms array.问题是您需要在while循环中使用数组和扫描仪,我正在努力思考如何做到这一点,数组不知何故需要成为while循环中条件的一部分,我需要能够输入什么我想在数组中访问房间而不修改房间数组中的字符串值。

Am I overthinking this?这是我想太多了吗?

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

Technically it works but I am not using the array at all and I need to make this do the same thing but using the array rather than using an empty string variable.从技术上讲,它可以工作,但我根本没有使用数组,我需要让它做同样的事情,但使用数组而不是使用空字符串变量。

You reference array values via [index] where index starts from 0.您通过 [index] 引用数组值,其中索引从 0 开始。

Instead of switch use if else statement (you can't use switch with array value since switch requries compile time constants), like so:而不是 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