分享我的知识总是我的荣幸;
这是我的回答:
import java.util.Scanner;
public class DynamicArrayListExample {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
ArrayList<Integer> arrayList = new ArrayList<>();
System.out.println("Enter elements (type 'exit' to stop):");
while (true) {
String input = scanner.next();
if (input.equalsIgnoreCase("exit")) {
break;
}
try {
int number = Integer.parseInt(input);
arrayList.add(number);
} catch (NumberFormatException e) {
System.out.println("Invalid input. Please enter a number or 'exit' to stop.");
}
}
System.out.println("Elements in the ArrayList:");
for (int element : arrayList) {
System.out.println(element);
}
}
}
希望你觉得它有用
您需要添加大小或循环的其他终止条件, 否则会无限循环。
Scanner scanner = new Scanner(System.in);
for(int i=0; ; i++)
{
int input = scanner.nextInt();
if(input == 0) // break out of loop condition (or define size of loop)
{
break;
}
else{
arrayList.add(input);
}
}