有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何强制用户为int输入固定数量的数字?

我想强制用户输入一个长度为5的数字( 并将它们存储在一个int变量中,这包括一个前导0

例如,程序应允许用户输入:

12345
04123
00012

但它不应适用于:

123456
4123
001

我试过

  if(int x < 99999){
  //continue with code
  }

只有当用户输入的长度超过5时,这才有效,但它不能解决用户输入的int长度小于5的问题


共 (3) 个答案

  1. # 1 楼答案

    两个功能。首先,要验证输入:

    static boolean is_valid_number(String x) {
        // returns true if the input is valid; false otherwise
        if(x.length != 5 || Integer.valueOf(x) > 99999) {  
            // Check that both:
            //    - input is exactly 5 characters long
            //    - input, when converted to an integer, is less than 99999
            // if either of these are not true, return false
            return false;
        }
        // otherwise, return true
        return true;
    }
    

    第二,获取用户输入:

    static int get_user_input() {
        // Create a scanner to read user input from the console
        Scanner scanner = new Scanner(System.in);
        String num = "";
        do {
            // Continuously ask the user to input a number
            System.out.println("Input a number:");
            num = scanner.next();
            // and continue doing so as long as the number they give isn't valid
        } while (!is_valid_number(num));
        return Integer.valueOf(num);
    

    如果给定的输入根本不是整数,您可能还需要进行一些错误处理。您可以这样简单地实现is_valid_number()

    static boolean is_valid_number(String x) {
        try {
            return (x.length == 5 && Integer.valueOf(x) <= 99999);
        } catch (NumberFormatException e) {
            // Integer.valueOf(x) throws this when the string can't be converted to an integer
            return false;
        }
    }
    
  2. # 2 楼答案

    像这样疯狂简单的事情。缺少边缘案例处理(读取:负值)

    boolean matchesLength(int n, int lengthLim){
        char[] charArr = (n + "").toCharArray();
        return (charArr.length == lengthLim);
    }
    
  3. # 3 楼答案

    我认为您应该以字符串而不是int形式获取输入,然后如果验证正确,您可以将其解析为整数,如下所示:

    import java.util.Scanner;
    
    public class main {
    
    public static void main(String[] args) {
        /// take input
        String userInput = "";
        Scanner sc = new Scanner(System.in);
        userInput = sc.nextLine();
        int input ;
        // validation test
        if(userInput.length() == 5) {
            input = Integer.parseInt(userInput);
        }else {
            // you can display an error message to user telling him that he should enter 5 numbers!
        }
    }
    
    }
    

    但你必须知道,在把它解析成int之后,如果有一个前导零,它可能会消失