要求仅插入数字

0 java

所以我正在尝试制作一个简单的计算器.

当我输入第一个数字时,如何进行,但是如果我插入"abc",它将给我一个错误.

当你写"abc"说"请输入一个数字"时,我如何按顺序制作

import java.util.Scanner;

public class calculator 
{
    public static void main(String[] args0) {
        Scanner test = new Scanner(System.in);

        int  x; 
        int  y;
        String  c;

        System.out.println("Insert a number ");
        x = test.nextInt();

        System.out.println("insert a value e.g * / + -");
        c = test.next();

        System.out.println("Insert another number");
        y = test.nextInt();

        if ( c.equals("*")) {
            System.out.println("the total is " + x*y);
        } 

        if (c.equals("+")) {
            System.out.println("the total is " + (x+y));

        }

        if (c.equals("-")) {
            System.out.println("the total is "+ (x-y));
        }

        if (c.equals("/")) {
            System.out.println("the total is "+ (x/y));
        }

    }
}
Run Code Online (Sandbox Code Playgroud)

All*_*aga 5

您可以使用scanner属性验证输入,直到成为int Scanner.hasNextInt()

Scanner scanner = new Scanner(System.in);
System.out.print("Enter number 1: ");
while (!scanner.hasNextInt()) scanner.next();
Run Code Online (Sandbox Code Playgroud)

例:

public static void main(String[] args0) {
        Scanner test = new Scanner(System.in);

        int  x; 
        int  y;
        String  c;

        System.out.println("Insert a number ");
        while (!test .hasNextInt()) test .next(); // Scanner Validation
        int x = test .nextInt();

}
Run Code Online (Sandbox Code Playgroud)

Scanner的 JavaDoc