Java:如果未知,我如何初始化数组大小?
我要求用户输入1到100之间的一些数字并将它们分配到一个数组中。 数组大小未初始化,因为它取决于用户输入数字的次数。 我应该如何分配数组长度? 如果用户输入5 6 7 8 9(5个数字),那么
int[] list;
变
int[] list = new int[5];
我正在尝试使用循环,但它不会停止。
int[] integers; int j = 0; do { integers = new int[j + 1]; integers[j] = in.nextInt(); j++; } while((integers[j-1] >= 1) ||(integers[j-1]) <= 100);
你应该使用List
的东西,而不是数组。 作为一般经验法则,当您不知道将在手数中添加多少元素时,请使用List
。 大多数人可能会通过使用ArrayList
来解决这个问题。
如果你真的不能使用List
,那么你可能不得不使用一些初始大小的数组(可能是10?)并跟踪你的数组容量与你要添加的元素数量,并将元素复制到如果你的空间不足,这是一个新的,更大的数组(这基本上是ArrayList
内部的工作)。 另请注意,在现实世界中,您永远不会这样做 – 您将使用专门为此类情况制作的标准类之一,例如ArrayList
。
我认为你需要使用基于它的List或类。
例如,
ArrayList integers = new ArrayList (); int j; do{ integers.add(int.nextInt()); j++; }while( (integers.get(j-1) >= 1) || (integers.get(j-1) <= 100) );
您可以阅读本文以获取有关如何使用它的更多信息。
我同意像List这样的数据结构是最好的方法:
List values = new ArrayList (); Scanner in = new Scanner(System.in); int value; int numValues = 0; do { value = in.nextInt(); values.add(value); } while (value >= 1) && (value <= 100);
或者您可以只分配一个最大大小的数组并将值加载到其中:
int maxValues = 100; int [] values = new int[maxValues]; Scanner in = new Scanner(System.in); int value; int numValues = 0; do { value = in.nextInt(); values[numValues++] = value; } while (value >= 1) && (value <= 100) && (numValues < maxValues);
如果你想坚持一个arrays,那么你可以使用这种方式。 但与List相比并不好,不推荐。 但它会解决您的问题。
import java.util.Scanner; public class ArrayModify { public static void main(String[] args) { int[] list; String st; String[] stNew; Scanner scan = new Scanner(System.in); System.out.println("Enter Numbers: "); // If user enters 5 6 7 8 9 st = scan.nextLine(); stNew = st.split("\\s+"); list = new int[stNew.length]; // Sets array size to 5 for (int i = 0; i < stNew.length; i++){ list[i] = Integer.parseInt(stNew[i]); System.out.println("You Enterred: " + list[i]); } } }
int i,largest = 0; Scanner scan = new Scanner(System.in); System.out.println("Enter the number of numbers in the list"); i = scan.nextInt(); int arr[] = new int[i]; System.out.println("Enter the list of numbers:"); for(int j=0;j
上面的代码效果很好。 我已经获取了列表中元素数量的输入并相应地初始化了数组。