我在 java 中使用扫描器,并试图在选项 2 的输入中输入一个空格(从哈希图中删除用户),但是当我在答案中添加一个空格时,我得到了一个 InputMismatchException。在研究时我遇到了这个线程 Scanner Class InputMismatchException and Warnings 说要使用这行代码来解决问题:
.useDelimiter(System.getProperty("line.separator"));
我已经添加了这个,现在我的选项 2 进入了我输入数据的永无止境的循环.这是我的代码:
public class Test {
public static void main(String[] args) {
Scanner scan = new Scanner (System.in);
AddressBook ad1 = new AddressBook();
String firstName="";
String lastName="";
String key="";
int choice=0;
do{
System.out.println("********************************************************************************");
System.out.println("Welcome to the Address book. Please pick from the options below.\n");
System.out.println("1.Add user \n2.Remove user \n3.Edit user \n4.List Contact \n5.Sort contacts \n6.Exit");
System.out.print("Please enter a choice: ");
choice = scan.nextInt();
if(choice==1){
//Add user
System.out.print("Please enter firstname: ");
firstName=scan.next();
System.out.print("Please enter lastname: ");
lastName=scan.next();
Address address = new Address();
key = lastName.concat(firstName);
Person person = new Person(firstName,lastName);
ad1.addContact(key,person);
System.out.println("key: " + key);
}
else if(choice==2){
//Remove user
System.out.println("Please enter name of user to remove: ");
scan.useDelimiter(System.getProperty("line.separator"));
key=scan.next();
System.out.println("name:" + key);
ad1.removeContact(key);
}
else if(choice==3){
//Edit user
}
else if(choice==4){
//List contact
ad1.listAllContacts();
}
else if(choice==5){
//Sort contacts
}
}while(choice!=6);
}
}
我需要使用空格的原因是从我的哈希图中删除用户我需要输入他们的全名,因为键是他们姓氏和名字的串联,任何帮助将不胜感激
nextInt()
的行为类似于 next()
,即当它读取一行时,它将光标放在它后面。
例子: 你给 6 作为输入
6
^(scanner's cursor)
所以下次你打电话给
nextLine()
。它将返回该光标之后的整行,在这种情况下为空。
要解决此问题,您需要调用一个额外的
nextLine()
,以便扫描器关闭它正在读取的上一行并移至下一行。
你可以这样做
System.out.print("Please enter a choice: ");
choice = scan.nextInt(); // Reads the int
scan.nextLine(); // Discards the line
在选择 2 中,因为你想要用户的全名,你可以使用
nextLine()
来获得整行和空格。
//Remove user
System.out.println("Please enter full name of user to remove: ");
key=scan.nextLine();
System.out.println("name:" + key);
ad1.removeContact(key);
或者你可以做一些与你在选择 1 中所做的类似的事情
System.out.print("Please enter firstname: ");
firstName=scan.next();
System.out.print("Please enter lastname: ");
lastName=scan.next();
key = lastName.concat(firstName);
System.out.println("name:" + key);
ad1.removeContact(key);
scan.nextLine(); // This is will make sure that in you next loop `nextInt()` won't give an input mismatch exception