线程主java.util.InputMismatchException错误中的异常 [英] Exception in thread main java.util.InputMismatchException error

查看:1517
本文介绍了线程主java.util.InputMismatchException错误中的异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个关于发生了什么的问题,每当我尝试编译它时它会一直给我一个错误:

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.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 Person.main(Person.java:38)

我想要的是让用户能够输入他们的年龄和姓名并将其存储在年龄和名称变量中,然后将它打印在底部字符串中。如果有人想帮我清理我的代码,也不会受到伤害..

All I want is for the user to be able to input their age and name and have it stored in the "age" and "name" variables, then have it print it out in the bottom string. And if someone would like to help me clean up my code as well, it wouldn't hurt..

import java.util.*; 
import java.io.*; 
import java.util.Scanner;

public class Person 

{

public static void main(String[]args) 

    {

    int age;
    int name;

    Scanner scan = new Scanner(System.in);

    System.out.println("Enter in your age.");
    age = scan.nextInt();

     if (age < 18) 

     {
         System.out.println("So you're a kid, huh? That's fine.");
     } 

     else if (age >= 18)

     {
        System.out.println("Ah, and adult! Good.");
     }

     @SuppressWarnings("resource")
     Scanner in = new Scanner(System.in);

     System.out.println("Enter in your name");
     name = in.nextInt();

     System.out.println("So you're " + age + " years old and your name is " + name);


}
}


推荐答案

问题

 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`

解决方案

 String name;
 ...
 System.out.println("Enter in your name");
 name = in.nextLine();

这篇关于线程主java.util.InputMismatchException错误中的异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆