0

While giving input the Scanner is basicly asking for another integer, which I dont understand , since im using nextLine() for strings and nextInt() for int's. That said what could be changed to resolve the issue? Thanks !

I inputed - John Male 24 Mary Female , after female I got the error down bellow.

package testPackage;

import java.util.Scanner;

public class Main {

        public static void main(String[] args) {

            int  age1, age2;
            String name1, gender1, name2, gender2;

            Scanner sc = new Scanner(System.in);
            Student std1 = new Student(name1 = sc.nextLine(), gender1 = sc.nextLine(),  age1 = sc.nextInt());
            Student std2 = new Student(name2 = sc.nextLine(), gender2 = sc.nextLine(), age2 = sc.nextInt());


            System.out.println("STD1 : " + std1.getName() + "\nSTD2 : " + std2.getName());
        }

}


package testPackage;

public class Student {

    String name , gender;
    int age;

    public String getName() {
        return name;
    }

    public Student(String name, String gender, int age) {
        this.name = name;
        this.gender = gender;
        this.age = age;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }


}


Exception in thread "main" java.util.InputMismatchException
    at java.base/java.util.Scanner.throwFor(Scanner.java:939)
    at java.base/java.util.Scanner.next(Scanner.java:1594)
    at java.base/java.util.Scanner.nextInt(Scanner.java:2258)
    at java.base/java.util.Scanner.nextInt(Scanner.java:2212)
    at testPackage.Main.main(Main.java:14)

Process finished with exit code 1
Lock It
  • 3
  • 2
  • 1
    https://stackoverflow.com/questions/13102045/scanner-is-skipping-nextline-after-using-next-or-nextfoo – achAmháin Mar 14 '19 at 18:54
  • simply take the integer input using age= Integer.parseInt(sc.nextLine()); if you want to avoid the newLine business. If not then refer to the above mention answer. – shelholmes221 Mar 14 '19 at 19:10

0 Answers0