我需要在下面的代码中向 roomType 添加说明。现在我只能在 roomType 中添加一个单词,但我希望能够添加多个单词,例如“double suite room”。
Scanner input = new Scanner(System.in);
Map<String, String> rooms = new HashMap<String, String>();
String roomNumber = "0";
String roomType = null;
System.out.println( "Enter room numbers and type : [ Enter 'stop' to quit ]" );
while(!roomNumber.equals("stop")){
input.useDelimiter(", *");
roomNumber = input.next();
if(roomNumber.equals("stop")){
break;
}
roomType = input.next();
rooms.put(roomNumber, roomType);
}
我也试过这种方法:
Map<String, List<String>> rooms = new HashMap<String, List<String>>();
List<String> roomTypeList= new ArrayList<String>();
List<String> description= new ArrayList<String>();
String roomNumber = "0";
String roomType = null;
System.out.println( "Enter room numbers and type : [ Enter 'stop' to quit ]" );
while(!roomNumber.equals("stop")){
roomNumber = input.next();
if(roomNumber.equals("stop")){
break;
}
roomType = input.next();
description.add(roomType);
rooms.put(roomNumber, description);
}
但扫描仪不能正常工作。 谢谢 附:还欢迎任何其他言论
答案 0 :(得分:0)
看起来您想要将扫描程序默认分隔符从空格更改为逗号空间。
// Set delimiters to space and comma.
// ", *" tells Scanner to match a comma and zero or more spaces as
// delimiters.
input.useDelimiter(", *");
现在,当你进入&#34;双人套房&#34;接下来应该拿起双倍,然后再次调用将拿起套件等...通过将分隔符更改为&#34;,&#34;
你可以输入任意数量的空格,直到你点击逗号,然后它就会停止接受输入。有意义吗?
答案 1 :(得分:0)
我不确定你想要使用什么样的描述,但我会在某个对象/枚举中包装类型和描述。
也许像
public enum RoomType {
SOME_ROOM_TYPE("description of first type"),
SOME_OTHER_TYPE("description of other type");
String description;
public RoomType(String description) {
this.description = description;
}
public static RoomType convert(String original) {
// some code for converting the string from the scanner,
// maybe Enum.valueOf(...)
}
}
然后在你的扫描仪循环中:
rooms.put(roomNumber, RoomType.convert(description));
答案 2 :(得分:0)
我建议使用Apache Commons Collections library中的MultiValueMap
类。
// create multimap to store key and values
MultiMap multiMap = new MultiValueMap();
// put multiple values for "key"
multiMap.put("key", "Apple");
multiMap.put("key", "Aeroplane");
multiMap.put("key", "Hello World");