所以我有一个任务,在控制台中从用户处取双打,然后将这些双打存储在数组中。这些双打实际上是我稍后会用到的坐标。用户输入存储在数组中的双数。数组大小未知,应该动态增长
该程序应该能够从用户采取未知数量的双打。我遇到的问题是允许数组大小动态增长。我们不能使用arrayList或任何Java库集合类。以下是我迄今为止:
import java.util.Scanner;
public class testMain{
public static void main(String[] args){
Scanner userInput = new Scanner(System.in);
boolean debug = true;
//Two array's where i'll store the coordinates
double[] coord1 = new double[3];
double[] coord2 = new double[3];
//Array for user commands
String[] commands = { "random", "exit", "help"};
for(int i = 0; i < coord1.length; i++){
System.out.println("Enter Coordinates: ");
double index = userInput.nextDouble();
//If more doubles needed for array we want to resize array
if(coord1[i] >= coord1.length){
for(int j = 0; j < 10; j++){
coord1[j] = j + 10;
}
double newItems[] = new double[20];
System.arraycopy(coord1, 0, newItems, 0 ,10);
coord1 = newItems;
}
coord1[i] = index;
}
if(debug == true){
printArray(coord1);
}
}
public static void printArray(double arr[]){
double n = arr.length;
for (int i = 0; i < n; i++) {
System.out.print(arr[i] + " ");
}
}
}
我似乎无法弄清楚如何识别何时到达坐标1月底执行代码,以增加规模,并继续循环更多的双打。
稍后当用户完成后,控制台的空条目应退出循环并显示数组。
相关:http://stackoverflow.com/questions/1647260/java-dynamic-array-sizes?rq=1 – 2017-02-16 16:41:35
你可能想'如果(我==坐标1 .length){'(注意'i'不是'coord [i]'),'i'是指数(0,1,2,3,4,...),'coord [i]'是index-i的内容(在你的情况下如此坐标) – 2017-02-16 16:42:11