赫尔辛基Mooc第1部分第4周练习18 Java怪异事件



在这里有一个问题,这个错误的解决方案简直超出了我的能力范围。

FAIL: PersonalInformationCollectionTest testInputFirst奇怪的事情发生了。它可能是类class PersonalInformationCollection的void main (String[] args)方法已经消失,或者您的程序由于异常而崩溃。更多信息:java.util.NoSuchElementException.

然后它说同样的事情,但对于testInputSecond也是如此。

找不到任何原因。我在网上找了一个正确的解决方案,也许只是我的视力不好,但我看不出我的错误代码和他们的正确代码之间有什么区别。

谢谢你的帮助。


import java.util.ArrayList;
import java.util.Scanner;
public class PersonalInformationCollection {
public static void main(String[] args) {
// implement here your program that uses the PersonalInformation class
ArrayList<PersonalInformation> infoCollection = new ArrayList<>();
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.println("First name: ");
String firstName = scanner.next();
if (firstName.isEmpty()){
break;
}
System.out.println("Last name: ");
String lastName = scanner.next();
System.out.println("Identification number: ");
String idNumber = scanner.next();
infoCollection.add(new PersonalInformation(firstName, lastName, idNumber));
}
for (PersonalInformation personalInfo : infoCollection){
System.out.println(personalInfo.getFirstName() + " " +  personalInfo.getLastName());
}
}
}

通过使用scanner.nextLine()而不是scanner.next()解决。不知道在这种情况下,这有什么不同

  1. 尽可能使用更一般的变量类型,因为如果您使用LinkedList而不是Arraylist,它不会改变逻辑,并且它具有与您使用的方法相同。
  2. 字符串使用扫描器,nextLine()
  3. numberId或简单的id应该是一个数字整数会很好,所以使用scanner.nextInt()在这里只获得整数
  4. 在你的类PersonalInformation中实现/重写toString方法,使字符串表示在一个点上

类个人信息

public class PersonalInformation {
private final int id;
private final String firstName;
private final String lastName;
public PersonalInformation(int id, String firstName, String lastName) {
this.id = id;
this.firstName = firstName;
this.lastName = lastName;
}
private int getId() {
return id;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
@Override
public String toString() {
return "PersonalInformation{" +
"id=" + id +
", firstName='" + firstName + ''' +
", lastName='" + lastName + ''' +
'}';
}
}

类PersonalInformationCollection

public static class PersonalInformationCollection {
public static void main(String[] args) {
// implement here your program that uses the PersonalInformation class
List<PersonalInformation> infoCollection = new ArrayList<>();
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.print("Identification number: ");
int id = scanner.nextInt();
if (id < 0){
break;
}
System.out.print("First name: ");
String firstName = scanner.nextLine();
System.out.print("Last name: ");
String lastName = scanner.next();
infoCollection.add(new PersonalInformation(id, firstName, lastName));
}
for (PersonalInformation personalInfo : infoCollection){
System.out.println(personalInfo);
}
scanner.close();
}
}

最新更新