java 我怎样才能找出用户输入的是哪种(错误的)数据类型而不是int?

c7rzv4ha  于 2023-01-01  发布在  Java
关注(0)|答案(2)|浏览(109)

我对Java和编程还是个新手,我正在做我的第一个小程序,我询问用户的年龄,判断他们是否是成年人,我想添加一个错误消息,告诉用户他们输入了错误的数据类型,而不是整数,然而,当我写一个字符串作为输入时,它显示错误消息,但它只说整数而不是字符串。

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        //create scanner object
        Scanner sc = new Scanner(System.in);

        System.out.println("What is your age?"); //ask for input
        int age = 0;
        try { //record input and check value
            age = sc.nextInt();
            if (age >= 18) {
                System.out.println("You are an adult.");
            } else {
                System.out.println("You are not an adult.");
            }
        } catch (Exception e) { //find out which wrong type the user inputted and tell it to them
            System.out.println("Error: you did not input a full number, instead you wrote a "+((Object) age).getClass().getSimpleName());
        }

    }
}

正如我所说的,我希望它说我写的是字符串而不是整数,但由于某些原因,它仍然说它是整数,我该如何修复呢?
下面是输入窗口:
您的年龄是多少?test错误:您没有输入一个完整的数字,而是写入了一个Integer
进程已完成,退出代码为0

qhhrdooz

qhhrdooz1#

你可以自己从scanner中获取字符串形式的值,然后将其转换为int类型:

Scanner sc = new Scanner(System.in);

    System.out.println("What is your age?"); //ask for input
    Object age = 0;
    try { //record input and check value
        age = sc.next();
        int intAge = Integer.parseInt((String) age);
        if (intAge >= 18) {
            System.out.println("You are an adult.");
        } else {
            System.out.println("You are not an adult.");
        }
    } catch (NumberFormatException e) { //find out which wrong type the user inputted and tell it to them
        System.out.println("Error: you did not input a full number, instead you wrote a "+ age.getClass().getSimpleName());
    }

我建议您在处理异常时使用正确的异常类型,谢谢

iovurdzv

iovurdzv2#

这是预期行为,因为您已将age声明为int。它不会考虑您作为输入提供的数据类型,但变量是在其中声明的。

相关问题