gpt4 book ai didi

java - 我可以在不使用循环的情况下从Java中的单行输入读取多个整数吗

转载 作者:太空宇宙 更新时间:2023-11-04 09:02:48 25 4
gpt4 key购买 nike

我在寻找一段代码来将一堆整数读入列表时遇到问题,我尝试了这个但没有成功:

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]

关于java - 我可以在不使用循环的情况下从Java中的单行输入读取多个整数吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60576914/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com