如何在 while 循环中使用字符串数组和扫描器?
How do I use a string array and scanner in a while loop?
我被告知要将遍历房子中所有房间的功能自动 for 循环变成 while 循环,允许用户键入他们接下来要进入的房间。
问题是你需要在 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 开始。
使用 if else 语句代替 switch(你不能将 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! ");
} // ...
我被告知要将遍历房子中所有房间的功能自动 for 循环变成 while 循环,允许用户键入他们接下来要进入的房间。
问题是你需要在 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 开始。
使用 if else 语句代替 switch(你不能将 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! ");
} // ...