簡體   English   中英

我可以在不使用循環的情況下從 Java 的單行輸入中讀取多個整數嗎

[英]Can i read multiple integers from single line of input in Java without using a loop

我在找到一段代碼將一堆整數讀入列表時遇到了問題,我試過這個但徒勞無功:

public static void main(String[] args){
    int[] a = in.readInts(); //in cannot be resolved
    StdOut.println(count(a)); //StdOut cannot be resolved
}

你能幫我嗎?

試試這個示例代碼,看看它是否適合你。

import java.util.ArrayList;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        int amount = 3; // Amount of integers to be read, change it at will.
        Scanner reader = new Scanner(System.in);
        System.out.println("Please input your numbers: ");

        int num; // integer will be stored in this variable.
        // List that will store all the integers.
        ArrayList<Integer> List = new ArrayList<Integer>();
        for (int i = 0; i < amount; ++i) {
            num = reader.nextInt();
            List.add(num);
        }
        System.out.println(List);
    }
}

此代碼在控制台中輸入1 2 3產生:

Please input your numbers:
1 2 3 
[1, 2, 3]

問:我可以在不使用循環的情況下從一行輸入中讀取多個整數嗎?

A. 使用並行處理,可能是; 但是對於正常的順序處理,不,總會有一個循環。

問:但是,如果沒有並行處理的好處,我可以從一行輸入中讀取多個整數而不使用forwhiledo循環語句for嗎?

A:是的,使用流。 但是不要認為通過消除顯式循環語句就消除了實際循環本身 它仍然存在,只是隱藏在流機制中,而不是在您自己的代碼中清晰可見。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM