Having a problem here with this error which the solution to is simply beyond me.
FAIL: PersonalInformationCollectionTest testInputFirst Something weird occurred. It could be that the void main (String[] args) method of the class class PersonalInformationCollection has disappeared or your program crashed due to an exception. More information: java.util.NoSuchElementException.
It then says the same thing but for testInputSecond as well.
Can't find any reason for whats wrong. Looked online at a correct solution and perhaps it's just my poor eye sight but i couldn't see a single difference between my somehow incorrect code and their correct code.
Thanks for any help in advance.
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());
}
}
}
CodePudding user response:
- You can try to use
scanner.hasNext()
. Please check the java documentation for Scanner#hasNext() - Scanner#next() can throw
NoSuchElementException - if no more tokens are available
while (scanner.hasNext()) {
System.out.println("First name: ");
String firstName = scanner.next();
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));
}
CodePudding user response:
Solved by using scanner.nextLine() rather than scanner.next(). No idea how that made such a difference in this case