So I'm trying to compute a Simple program that has an n number of objects of the type Person and each person has a name, id, passport and driving licence.
It goes like this:
public class Person {
private String name;
private int id;
private int passport;
private int licence;
Person(String name, int id, int passport, int licence) {
this.name=name;
this.id=id;
this.passport=passport;
this.licence=licence;
}
}
public class Main {
public static void main(String[] args) {
Scanner jin=new Scanner(System.in);
int n=jin.nextInt(), i;
Person[] dudes=new Person[n];
for(i=0; i<n; i++) {
String name=jin.nextLine();
int id=jin.nextInt();
int passport=jin.nextInt();
int licence=jin.nextInt();
dudes[i]=new Person(name, id, passport, licence);
}
}
}
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at test.Main.main(Main.java:20)
If you change String name = jin.nextLine();
to String name = jin.next();
it works how you have it.
An easier way would be to clear the buffer after typing an int like so for first and last names.
for(i=0; i<n; i++)
{
jin.nextLine(); // add this to clear the input from before.
String name=jin.nextLine();
int id=jin.nextInt();
int passport=jin.nextInt();
int licence=jin.nextInt();
dudes[i]=new Person(name, id, passport, licence);
}