我试图在 Java 中将以下行作为输入,但没有得到所需的输出。我希望所有这些整数都在数组列表中。
输入:
- 2(测试用例(
- 5(第一个测试用例数组的大小(
- 1 2 3 5 4(第一个测试用例数组中的元素(
- 4(第二个测试用例数组的大小(
- 66 45 778 51(第二个测试用例数组中的元素(
法典:
import java.util.*;
import java.lang.*;
public class Main
{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
//System.out.println("Hello World");
int tc = sc.nextInt();
for(int i = 0; i < tc; i++){
ArrayList<Integer> list = new ArrayList<Integer>();
int t = sc.nextInt();
String line = sc.next();
String[] arr = line.split(" ");
for(int j = 0; j < t; j++)
list.add(Integer.parseInt(arr[j]));
System.out.print(list);
}
}
}
输出
1
5
1 2 3 4 5
[1]
我不太确定你的问题是什么,但我认为你只是对阅读一串数字(1 2 3 4 5 4(并将其转换为数组[1,2,3,4,5,4]感兴趣。
String input= "1 2 3 4 5 4";
String[] stringList = input.split(" ");
int[] integerList = new int[stringList .length()];
for(int i = 0; i < listOfS.length(); i++) {
integerList[i] = Integer.parserInt(stringList[i]);
}
首先,您必须使用 input.split(" "( 将字符串字符串拆分为其元素。这将在每个空格符号处拆分字符串输入。 然后你必须将 String[] 转换为 int[]。这是通过遍历字符串 [] 并使用 Integer.parseInt(( 将其内容解析为整数来完成的。
这能做你想做的事吗?
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int tc = sc.nextInt();
for (int i = 0; i < tc; i++) {
List<Integer> list = new ArrayList<>();
int nElements = sc.nextInt();
while (nElements-- > 0) {
list.add(sc.nextInt());
}
System.out.print(list);
}
}
}
使用sc.nextLine()
.它返回一个String
,但是通过在每个空格之后拆分输入,你会得到一个包含所有整数的String[]
。如果循环访问它们并将它们转换为int
,则可以将它们添加到列表中。
以下是我如何做到这一点的示例:
import java.util.ArrayList;
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("How many numbers?");
int tc = Integer.valueOf(sc.nextLine());
for(int i = 0; i < tc; i++) {
System.out.println("Next number");
ArrayList<Integer> list = new ArrayList<Integer>();
String line = sc.nextLine();
String[] arr = line.split("\s");
for(int j = 0; j < arr.length; j++){
list.add(Integer.parseInt(arr[j]));
}
System.out.print(list);
}
sc.close();
}
}
下面是使用流进行数字处理的简单解决方案:
List<Integer> list = new ArrayList<>();
Scanner scanner = new Scanner(System.in);
int testCases = Integer.parseInt(scanner.nextLine());
for (int i = 0; i < testCases; i++) {
scanner.nextLine(); // skip "size" line as we don't use it in this solution
Arrays.stream(scanner.nextLine().trim().split("\s+"))
.map(Integer::parseInt)
.forEach(list::add);
}
list.forEach(e -> System.out.printf("%d ", e));
输入
2
4
2 3 4 5
2
99 77
输出
2 3 4 5 99 77
解释
Arrays.stream(...)
- 从提供的数组的元素创建一个stream
scanner.nextLine().trim().split("\s+")
- 从Scanner
中读取一行,在开头和结尾trim
空格,split
一个或多个空格将其变成一个String[]
.map(Integer::parseInt)
- 将每个String
元素转换为Integer
.forEach(list::add)
- 将每个Integer
元素添加到list