java—如果用户没有输入数字,如何在输入部分插入numberformatexception并显示“InputError”

von4xj4u  于 2021-07-08  发布在  Java
关注(0)|答案(1)|浏览(375)
import java.util.Scanner;
public class numberformat {

    public void pw(int n, String ch) {

        String one[] = { " ", " One", " Two", " Three", " Four", " Five", " Six", " Seven", " Eight", " Nine", " Ten"};

        if (n<=10)
        {
            System.out.print(one[n]);
        }
        if (n > 0)

            System.out.print(ch);

    }

        public static void main(String[] args)
        {
            int n = 0;
            Scanner scanf = new Scanner(System.in);
            System.out.println("Enter an integer number: ");
            n = scanf.nextInt();

            if (n <= 0)
            {
                System.out.println("Enter numbers greater than 0");
            }
            else{
                numberformat a = new numberformat();
                a.pw((n / 1000000000), " Hundred");
                a.pw((n / 10000000) % 100, " billion");
                a.pw(((n / 100000) % 100), " million");
                a.pw(((n / 1000) % 100), " thousand");
                a.pw(((n / 100) % 10), " hundred");
                a.pw((n % 100), " ");
            }
        }
}

如何插入 NumberFormatException 和显示器 Error ,如果用户没有输入数字。

3vpjnl9f

3vpjnl9f1#

添加输入方法,因为如果数字不大于,则必须重新输入数字zero:-

public static int inputs() {
        Scanner scanf = new Scanner(System.in);
        int n = 0;
        try {
                n = scanf.nextInt();
            } catch(Exception e) {
                System.out.println("Input Error!");
            }
        return n;
    }

在“main”中编辑method:-

public static void main(String[] args) {
            System.out.print("Enter an integer number: ");
            int n = inputs();
        if (n <= 0) {
            System.out.println("Enter numbers greater than 0");
            n = inputs();
        }
        else {
            numberformat a = new numberformat();
            a.pw((n / 1000000000), " Hundred");
            a.pw((n / 10000000) % 100, " billion");
            a.pw(((n / 100000) % 100), " million");
            a.pw(((n / 1000) % 100), " thousand");
            a.pw(((n / 100) % 10), " hundred");
            a.pw((n % 100), " ");
        }
    }

相关问题