线程“主”中的异常java.util.InputMismatchException-输入字符串时应为Int

时间:2019-03-14 18:51:21

标签: java

在输入扫描器的时候,基本上是在询问另一个我不明白的整数,因为我在字符串中使用nextLine(),在int中使用nextInt()。那就是说,可以采取什么措施来解决该问题?谢谢!

我输入- 约翰 男 24 玛丽 女的,女的我下面传错了。

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

0 个答案:

没有答案