Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
61 views
in Technique[技术] by (71.8m points)

java - Exactly n numbers in a row

I am solving a task, but stuck in one moment with input numbers.

Input example:

//n and k

3 2

// inputing random n numbers (this time 3 numbers)
2 3 4

In the first line I have 2 digits (n and k seperated by space). In the second line I need to input n numbers (which is given in the fist line) seperated by space . How can I solve this? This is what I have now.

public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String  lines = br.readLine();
        String[] strs = lines.trim().split("\s+");
        int n = Integer.parseInt(strs[0]);
        int k = Integer.parseInt(strs[1]);

//here starts my problem
        List<Integer> numbers = new ArrayList<>();
        for (int i = 0; i < n; i++) {
            int number = Integer.parseInt(br.readLine());
            numbers.add(number);
        }

    }

I managed to take the first two digits in first line. But I couldn't solve taking n digits of the second line. I need it to be int. Thanks for the assistance.

question from:https://stackoverflow.com/questions/65905994/exactly-n-numbers-in-a-row

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use a similar approach to that you used for reading and processing the first line.

String  line = br.readLine();
String[] strs = line.trim().split("\s+");
List<Integer> numbers = new ArrayList<>();
for (int i = 0; i < strs.length; i++) {
    int number = Integer.parseInt(strs[ i ]);
    numbers.add(number);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...