根据用户想要输入的项目数量限制用户输入

问题描述 投票:0回答:0

我在根据用户想要输入的数字数量停止代码时遇到问题...... 我有这个代码:

private static void inputN(Scanner scanner) {
    System.out.print("Enter the number of physical frames (2-8): ");
    int n = scanner.nextInt();
    if (n < 2 || n > 8) {
        System.out.println("Invalid input! N must be between 2 and 8.");
        return;
    }
    N = n;
    System.out.println("N set to " + N);
}

private static void inputReferenceString(Scanner scanner) {
    System.out.print("Enter the reference string (maximum length 20, each element between 0 and 9, at least " +
            " " + N + " elements): ");
    ArrayList<Integer> list = new ArrayList<>();
    while (scanner.hasNextInt() && list.size() < 20) {
        int page = scanner.nextInt();
        if (page < 0 || page > 9) {
            System.out.println("Invalid input! Each element must be between 0 and 9.");
            return;
        }
        list.add(page);
    }
    if (list.size() < N) {
        System.out.println("Invalid input! The reference string must have at least " + N + " elements.");
        return;
    }
    referenceString = new int[list.size()];
    for (int i = 0; i < list.size(); i++) {
        referenceString[i] = list.get(i);
    }
    System.out.println("Reference string set to " + list);
}

代码有效,但它强制用户输入所有 20 个数字,我想询问用户有多少个数字并让它停止,或者让用户输入数字,他们有办法在完成后停止。

实际上我已经尝试了几种不同的方法来输入代码(先转换为字符串,然后再转换为数字等),但是我对如何添加代码来询问用户“你想输入多少数字?”有一个想法。然后基于该数字,他们只能添加那么多数字。最小数字个数是输入N,最大数字个数是20.

java arrays user-input limiting demand-paging
© www.soinside.com 2019 - 2024. All rights reserved.