java灵活的数组大小根据输入[重复]

问题描述 投票:0回答:1

这个问题在这里已有答案:

所以我想知道是否有可能初始化没有单元格的数组,然后按用户的意愿保持添加单元格。

例如:

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");}  

在这个例子中,我想取出一个过大的数组,以适应用户可能拥有的大部分可能的输入大小。换句话说,我希望有一个数组,这样在开始时,它没有单元格,然后只要用户保持键入有效值,就会添加单元格。

有人请帮忙吗?

java arrays
1个回答
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();
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.