我有以下
10 30 15
89 1 3
65 48 12
我希望每行中的每个数字都包含在不同的列表中。
例如
list1 contains 10 30 15
list2 contains 89 1 3
list3 contains 65 48 12
我尝试了以下但没有成功......有人可以帮助我吗?
ArrayList<Integer> list1 = new ArrayList<Integer>();
ArrayList<Integer> list2 = new ArrayList<Integer>();
ArrayList<Integer> list3 = new ArrayList<Integer>();
Scanner sc = new Scanner(System.in);
while(sc.hasNextLine()) {
list1.add(sc.nextInt());
}
while(sc.hasNextLine()) {
list2.add(sc.nextInt());
}
while(sc.hasNextLine()) {
list3.add(sc.nextInt());
}
sc.close();
答案 0 :(得分:2)
您需要使用空格作为分隔符来拆分下一行(如果总是这样),然后在这些标记上使用Integer.parseInt()来添加列表中的元素。
public static void main(String... args){
List<Integer> list1 = new ArrayList<>();
List<Integer> list2 = new ArrayList<>();
List<Integer> list3 = new ArrayList<>();
Scanner sc = new Scanner(System.in);
String[] strArray;
if(sc.hasNextLine()) {
strArray = sc.nextLine().split("\\s+");
for(String item : strArray)
list1.add(Integer.parseInt(item));
}
if(sc.hasNextLine()) {
strArray = sc.nextLine().split("\\s+");
for(String item : strArray)
list2.add(Integer.parseInt(item));
}
if(sc.hasNextLine()) {
strArray = sc.nextLine().split("\\s+");
for(String item : strArray)
list3.add(Integer.parseInt(item));
}
sc.close();
System.out.println(list1);
System.out.println(list2);
System.out.println(list3);
}
控制台:
//input
10 30 15
89 1 3
65 48 12
//output
[10, 30, 15]
[89, 1, 3]
[65, 48, 12]
这假设总有3行输入(如OP所述)并且没有错误的输入。
答案 1 :(得分:0)
如果你总是有3行,你可以在每行创建一个String,每行创建一个整数列表。然后在String中获取一行,使用space作为分隔符拆分字符串。最后,解析整数并将它们添加到列表中。
这里是一行的代码:
String line1 = sc.nextLine();
List<int> list1 = new ArrayList<int>();
String[] ints = line1.split(" ");
for(String s : ints) {
list1.add(Integer.parseInt(s));
}
答案 2 :(得分:0)
使用扫描仪时,您可以使用方法nextInt()
和hasNextInt()
ArrayList<Integer> list1 = new ArrayList<Integer>();
ArrayList<Integer> list2 = new ArrayList<Integer>();
ArrayList<Integer> list3 = new ArrayList<Integer>();
Scanner sc = new Scanner(System.in);
while(sc.hasNextLine()) {
while (sc.hasNextInt()) {
list1.add(sc.nextInt());
}
}
sc.nextLine();
while(sc.hasNextLine()) {
while (sc.hasNextInt()) {
list2.add(sc.nextInt());
}
}
sc.nextLine();
while(sc.hasNextLine()) {
while (sc.hasNextInt()) {
list3.add(sc.nextInt());
}
}
sc.close();
答案 3 :(得分:0)
需要拆分每一行,然后需要解析拆分的每个部分:
Set<List<Integer>> myListSet = new HashSet<>();
Scanner sc = new Scanner(System.in);
while(sc.hasNextLine()) {
List<Integer> intList = new ArrayList<>();
Arrays
.stream(sc.nextLine().split("\\s+"))
.map(s -> Integer.parseInt(s))
.forEach(intList::add);
myListSet.add(intList);
}
sc.close();
myListSet
现在包含许多列表,每个列表都有n个整数