使用Java将多个令牌验证为整数

mwkjh3gx  于 2022-09-18  发布在  Java
关注(0)|答案(3)|浏览(141)

/我的目标是使用终端接收2个整数,并在Java程序中将它们相加。我需要确认两个终端条目都是整数。如果是,我将继续将整数相加。如果不是,我应该打印“输入无效。正在终止…”
我试图使用带有hasNextInt()的if语句,但我的程序仅验证第一个扫描仪输入。如何确认两个扫描仪输入都是整数?任何帮助都将不胜感激。
这是我的Java代码:
/

import java.util.Scanner;
public class Calculator {
  public static void main(String[] args) {

    Scanner input = new Scanner (System.in);

    System.out.println("List of operations: add subtract multiply divide alphabetize");
    System.out.println("Enter an operation:");
    String operationInput = input.next().toLowerCase();

    switch (operationInput){

     case "add":// for addition
     System.out.print("Enter two integers:");

      if (input.hasNextInt() == false) { //confirm the numbers are integers, otherwise terminate
        System.out.println("Invalid input entered. Terminating...");
        break;
      }
      else {
         int a1 = input.nextInt();
         int a2 = input.nextInt();
         int at = a1 + a2;
         System.out.println("Answer: " + at);
         input.close();
         break;
      }
gijlo24d

gijlo24d1#

如果int可用,您已经读取了它,基本上,您只需要重复这个步骤。您可以使用附加标志来指示程序是否能够成功读取两个整数:

int a1, a2;
boolean gotTwoInts = false;
if (input.hasNextInt()) {
    a1 = input.nextInt();
}
if (input.hasNextInt()) {
    a2 = input.nextInt();
    gotTwoInts = true;
}

if (!gotTwoInts) {
    System.out.println("Invalid input entered. Terminating... ");
    break;
}

更新

完整示例:

import java.util.Scanner;
public class Calculator {
    public static void main(String[] args) {
        Scanner input = new Scanner (System.in);

        System.out.println("List of operations: add subtract multiply divide alphabetize");
        System.out.println("Enter an operation:");
        String operationInput = input.next().toLowerCase();

        switch (operationInput){
            case "add": { // curly braces because local variables are block scoped.
                System.out.print("Enter two integers:");

                int a1 = -1, a2 = -1; // local variables need to be initialized
                boolean gotTwoInts = false;
                if (input.hasNextInt()) {
                    a1 = input.nextInt();
                }
                if (input.hasNextInt()) {
                    a2 = input.nextInt();
                    gotTwoInts = true;
                }

                if (!gotTwoInts) {
                    System.out.println("Invalid input entered. Terminating... ");
                    break;
                }

                System.out.println("Answer: " + (a1 + a2));
            }
        }
    }
}
e4yzc0pl

e4yzc0pl2#

你可以改变结构。您可以使用try块和catch块代替if ( ! input.hasNextInt())else块。如果没有两个整数,input.nextint()将抛出异常。扫描仪API#nextInt

System.out.print("Enter two integers:");
try {
  int a1 = input.nextInt();
  int a2 = input.nextInt();
  System.out.println("Answer: " + (a1 + a2));
}
catch (InputMismatchException ex) {
   System.out.println("Invalid input entered. Terminating...");
   System.exit (100); }
catch (NoSuchElementException ex) {
   System.out.println("Missing input. Expected two integers."
                        + " Terminating...");
   System.exit (100); }
finally { 
   input.close();
}
imzjd6km

imzjd6km3#

我将使用方法nextLine–而不是方法nextInt,让用户在一行中输入两个整数,用空格分隔。
此外,我认为将代码划分为方法是一个好主意,而不是在方法main中编写所有代码。
似乎您还打算进行加法减法乘法除法运算,因此下面的部分代码可以被视为帮助您完成程序的模板。

import java.util.Scanner;

public class Calculator {
    private static final int NUMBER_OF_OPERANDS = 2;
    private static Scanner input = new Scanner(System.in);
    private static int[] operands = new int[NUMBER_OF_OPERANDS];

    private static int add() {
        getOperands();
        return operands[0] + operands[1];
    }

    private static void getOperands() {
        System.out.print("Enter two integers separated by space: ");
        String value = input.nextLine();
        String[] parts = value.split("\\s+");
        if (parts.length < NUMBER_OF_OPERANDS) {
            throw new RuntimeException("Less than two integers entered.");
        }
        operands[0] = Integer.parseInt(parts[0]);
        operands[1] = Integer.parseInt(parts[1]);
    }

    public static void main(String[] args) {
        System.out.println("List of operations: add subtract multiply divide alphabetize");
        System.out.print("Enter an operation: ");
        String operationInput = input.nextLine().toLowerCase();
        int result = 0;
        switch (operationInput) {
            case "add":// for addition
                result = add();
                break;
            case "subtract":
                break;
            case "multiply":
                break;
            case "divide":
                break;
            case "alphabetize":
                break;
            default:
                System.out.println("Invalid operation: " + operationInput);
                System.exit(1);
        }
        System.out.println("Result: " + result);
    }
}

请注意,RuntimeException是未经检查的exception,并且类java.lang.Integer的[static]方法parseInt可能会抛出NumberFormatException,这也是未经检查异常。

相关问题