这是一个从stdin读取字符串的简单代码,将它们添加到List< String>中,然后使用toArray将其转换为String [](如果您确实需要使用数组).
import java.util.*;
public class UserInput {
public static void main(String[] args) {
List list = new ArrayList();
Scanner stdin = new Scanner(System.in);
do {
System.out.println("Current list is " + list);
System.out.println("Add more? (y/n)");
if (stdin.next().startsWith("y")) {
System.out.println("Enter : ");
list.add(stdin.next());
} else {
break;
}
} while (true);
stdin.close();
System.out.println("List is " + list);
String[] arr = list.toArray(new String[0]);
System.out.println("Array is " + Arrays.toString(arr));
}
}
也可以看看: