所以我想知道是否有可能初始化一个没有单元格的数组,然后继续按照用户的意愿添加单元格。
例如:
boolean exit = false;
int count = 0;
double [] array = new double [99999];
try{
while(!exit){
System.out.println("please type in the values you wish to compose this array with. (flag: any value other than a double)");
Scanner read = new Scanner(System.in);
double x = read.nextDouble();
array[count] = x;
count++;}}
catch(Exception e){System.out.println("end of reading");}
在此示例中,我想删除一个过大的数组,以适应用户可能具有的很大一部分输入大小。换句话说,我希望有一个数组,使其在开始时没有任何单元格,然后只要用户继续输入有效值,就添加单元格。
有人请帮忙吗?
答案 0 :(得分:0)
您可以使用String,然后一次创建double数组:
import java.util.Scanner;
public class App {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
String nextEntry;
System.out.println("Enter double values (0 to quit)");
StringBuilder sb = new StringBuilder();
while (!(nextEntry = scnr.next()).equals("0")) {
sb.append(nextEntry).append(":");
}
String[] stringValues = sb.toString().split(":");
double[] doubleValues = new double[stringValues.length];
for (int i = 0; i < stringValues.length; i++) {
doubleValues[i] = Double.valueOf(stringValues[i]);
}
for (int i = 0; i < doubleValues.length; i++) {
System.out.println(doubleValues[i]);
}
scnr.close();
}
}