Exception in thread main java.util.InputMismatchException error

前端 未结 5 2047
孤街浪徒
孤街浪徒 2020-12-22 10:39

I have a question on what\'s going on, whenever I try to compile it it keeps giving me an error like this:

Exception in thread \"main\" java.util.InputMismat         


        
相关标签:
5条回答
  • 2020-12-22 10:43

    It means that your program has tried to read a value that as an integer that is not an integer.

    when using name = in.nextInt();

    it should be string.not int

    0 讨论(0)
  • 2020-12-22 10:51
    import java.util.*;
    class Employe
    {
        private int id;
        private String name;
        Employe(int id,String name)
        {
            this.id=id;
            this.name=name;
        }
        public int getId() {
            return id;
        }
        public void setId(int id) {
            this.id = id;
        }
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
    }
    public class Quarantine {
    public static void main(String[] args) {
        Employe empList[]=new Employe[2];
        Scanner sc=new Scanner(System.in);
        for(int index=0;index<empList.length;index++) {
        int id=sc.nextInt();
        String name=sc.nextLine(); 
        empList[index]=new Employe(id,name);
        }
        for(int index=0;index<empList.length;index++) {
            System.out.println(empList[index].getId()+" "+empList[index].getName());
            }}
    }
    

    if I give input as 1, a

    it will show error because both are taken as character

    I need to give input as 124, a run

    0 讨论(0)
  • 2020-12-22 11:03

    Issues

     int name; //Name should be of type String
     ...
     System.out.println("Enter in your name");
     name = in.nextInt(); //It doesn't handle the string since your using `nextInt`
    

    Solution

     String name;
     ...
     System.out.println("Enter in your name");
     name = in.nextLine();
    
    0 讨论(0)
  • 2020-12-22 11:03

    name = in.nextInt(); as you required user name so obviously it will be String type so use either name=in.next() or name=in.nextLine(). i hope it will work now.

    0 讨论(0)
  • 2020-12-22 11:04

    Why is name an integer? int name;

    I suspect you are using alpha characters to input your name...and are getting the exception at this line: name = in.nextInt();

    name should not be an integer. It should be a string.

    Therefore, string name; and name = in.nextLine();

    0 讨论(0)
提交回复
热议问题