【问题标题】:how to take input from the keyboard without asking the number of input he want to enter如何在不询问他要输入的输入数量的情况下从键盘获取输入
【发布时间】:2018-10-18 07:33:56
【问题描述】:

我尝试编写代码,其中代码在读取数字 42 后停止处理输入。输入处的所有数字都是整数。在此代码中,要求用户给出他想要给出的输入数。但我是不知道如何在不询问用户他想输入多少数字的情况下接受输入。

import java.util.Scanner;

public class antarahac {

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);
        int pattern[] = new int[1];
        pattern[0] = 42;
        int max, ls, lp = 1;
        System.out.println("enter the no. of values you want to enter");
        ls = sc.nextInt();
        int input[] = new int[ls];
        for (int i = 0; i < ls; i++) {
            input[i] = sc.nextInt();

        }
        max = ls - lp - 1;
        boolean flag;
        for (int i = 0; i < max; i++) {
            flag = true;
            for (int j = 0; j < lp && flag == true; j++) {
                if (pattern[j] != input[j + i]) {
                    flag = false;
                    System.out.println("" + input[i]);

                }
            }
            if (flag == true) {

                break;
            }
        }
    }

}

【问题讨论】:

  • while (!input.equals("endInput")) 例如。 if ( flag == true ) 可以重写为 if ( flag ) (不太可能包含类型错误
  • int input; while((input = sc.nextInt()) != 42) 但您需要在不知道大小的情况下声明一个数组或学习使用List。 PS:为什么pattern 使用 1 个单元格的数组?

标签: java input keyboard


【解决方案1】:

您可以简单地使用循环,直到获得所需的值。您提到当用户输入42 时停止:

int tmp;
while((tmp = sc.nextInt()) != 42){
    // do something
}

这将读取输入,直到输入 42

Scanner sc = new Scanner(System.in);
int tmp;
while((tmp = sc.nextInt()) != 42){
    System.out.println(tmp);
}
sc.close();

输入:

1、2、3、5、48、42

输出:

1
2
3
5
48

更多信息

现在,如果你想存储这些,如果你使用数组,你需要创建一个有足够空间的数组(有风险),比如:new int[1000]; 或者你可以使用List 来使用动态大小的集合.如果您不知道,只需知道要创建List,您只需要:

List<Integer> input = new ArrayList<>(); //int[] input = new int[####];

然后在末尾添加一个值即可:

input.add(i); //input[index] = i;

并读取值(获取):

input.get(index);  // input[index]

然后,我注意到您使用ls,在数组大小之前,您可以使用size() 方法知道列表中添加了多少值:

ls = input.size();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-10
    • 1970-01-01
    • 1970-01-01
    • 2013-07-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多