You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用If语句校验输入必须为整数且不可输入英文单词?

如何用If语句实现整数输入校验(禁止英文单词输入)

Hey there, let's work through this input validation problem. First off, the big issue with your current code is that sc.nextInt() will throw an InputMismatchException the second someone enters non-integer content (like English words) — that means your if condition never even runs! Let's fix this properly while leaning into if statements for the validation logic.

Core Approach

We need to:

  • Read input as a string first (to avoid immediate exceptions)
  • Use if statements to check if the string can be safely converted to an integer (which automatically rules out English words)
  • Add extra checks if needed (like ensuring the integer is positive for weight)
  • Only proceed with business logic if all checks pass

Fixed Code Example

Here's a revised version of your code with proper validation:

import java.util.Scanner;

// Assume your existing Salad class, menu array, etc. are already defined
public class OrderValidation {
    private static Scanner sc = new Scanner(System.in);

    public static void main(String[] args) {
        // Example placeholder values for your existing variables
        int itemNum = 1;
        Object[] menu = new Object[]{new Salad()};
        Object[] orderedItem = new Object[10];
        int TtlOrderNum = 0;

        System.out.print("Enter weight (must be an integer): ");
        String userInput = sc.nextLine();

        // First check: Is the input a valid integer (no English words allowed)?
        if (userInput.matches("^-?\\d+$")) {
            int numWeight = Integer.parseInt(userInput);
            
            // Second check: Ensure weight is a positive integer (makes sense for a salad!)
            if (numWeight > 0) {
                ((Salad) menu[itemNum - 1]).setWeight(numWeight);
                System.out.println(menu[itemNum - 1].showOrderDetails());
                System.out.println("-------------------------------------------");
                System.out.println("Total No. of items ordered :");
                orderedItem[TtlOrderNum] = menu[itemNum - 1];
                TtlOrderNum += 1;
                Continue(); // Your custom continue method
            } else {
                System.out.println("Error: Weight must be a positive integer!");
            }
        } else {
            System.out.println("Error: Input must be an integer — no English words or other non-numeric content allowed!");
        }
    }

    // Mock implementation of your Continue method
    private static void Continue() {
        System.out.println("Proceeding with order...");
    }
}

// Mock Salad class for context
class Salad {
    private int weight;
    public void setWeight(int weight) {
        this.weight = weight;
    }
    public String showOrderDetails() {
        return "Salad Weight: " + weight + "g";
    }
}

Key Details Explained

  • Reading as String: Using sc.nextLine() lets us capture the entire input, so we can validate it before trying to convert to an integer.
  • Regex Check: The matches("^-?\\d+$") condition uses a regular expression to ensure:
    • ^ = start of the string, $ = end of the string (no extra characters allowed)
    • -? = optional negative sign (remove this if you don't allow negative weights)
    • \\d+ = one or more digits (so no letters or symbols can slip through)
  • Nested Ifs: We first confirm the input is an integer, then check if it's logically valid (positive weight) before executing your order logic.

Alternative: Try-Catch + If (No Regex)

If you prefer not to use regular expressions, you can use a try-catch block paired with if statements to validate:

System.out.print("Enter weight (must be an integer): ");
String userInput = sc.nextLine();
int numWeight = 0;
boolean isValid = true;

if (userInput.isEmpty()) {
    isValid = false;
} else {
    try {
        numWeight = Integer.parseInt(userInput);
        // Extra check: Make sure all characters are digits (or a leading minus)
        if (!userInput.replace("-", "").matches("\\d+")) {
            isValid = false;
        }
    } catch (NumberFormatException e) {
        isValid = false;
    }
}

if (isValid && numWeight > 0) {
    // Execute your order logic here
} else {
    System.out.println("Error: Input must be a positive integer — no English words allowed!");
}

内容的提问来源于stack exchange,提问作者Karl

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 07:34:17