我想在ArrayList中存储指定数量的整数序列。
序列的数量将由用户定义。
例如,如果用户输入3,则程序将知道将插入3个序列。
每个序列在插入0时结束。例如,下一个用户输入可能是: 1 2 3 0 4 5 6 7 8 0 11 12 0
我想存储这些序列,然后对每个序列进行一些计算。我该怎么做?
这是我到目前为止所做的:
public static void main (String[] args){
Scanner scan = new Scanner (System.in);
System.out.println("number of sequences: ");
int size = scan.nextInt();
List<Integer> arr = new ArrayList<Integer>();
//How to get the input sequences by sequence?
scan.close();
}
答案 0 :(得分:1)
如果要使用ArrayLists,可以使用泛型类型:
ArrayList<ArrayList<Integer>> myList = new ArrayList<ArrayList<Integer>>();
您可以使用ArrayList of Integers填充此列表。 你可以使用for循环创建这个新的整数ArrayList,它在给定的列表数量时退出循环。 例如:
for (int i=0; i < userInputNumber; i++) {
ArrayList<Integer> newList = new ArrayList<Integer>();
// fill the newList object with the user input list of integers
myList.add(newList)
}
答案 1 :(得分:0)
这里有一些帮助你入门的半伪代码
//beginning number
int numOfSequences = readUserInputAsInt()
//make an array big enough to hold all the sequences
List<Integer>[] sequences = new List<Integer>[numOfSequences];
// read all the next input as one big string
String userInput = readUserInputAsString();
//this method would split the userInput string up by spaces to get each integer
int[] numbers = convertStringToIntArray(userInput);
//put each number in to the correct sequence list
int sequenceNumber = 0;
for(int number : numbers) {
// if we haven't used this sequence before, create a new list to hold it
if(sequences[sequenceNumber] == null){
sequences[sequenceNumber] = new ArrayList<Integer>();
}
// if number is 0, end that sequence, else add the number to the sequence
if(number == 0) {
sequenceNumber++;
} else {
sequences[sequenceNumber].add(number);
}
}
// do work on 'sequences'