我在這個機智的結尾。我需要創建一個數組,然後使用單獨的方法來調整它的大小,然後使用另一種方法來打印它。這裏是我的代碼至今:在Java中使用專用方法調整數組的大小
import java.util.Scanner;
public class Lab07 {
public static void main(String[] args)
{
//Variables
int userSize;
int newSize;
int diff;
//Scanner
@SuppressWarnings("resource")
Scanner kb = new Scanner(System.in);
do{
System.out.println("Input an array size: ");
userSize = kb.nextInt();
}while(!(userSize>0));
double[] userNums = new double[userSize];
System.out.println("Now please enter "+userSize+" numbers.");
//Gathering Input
for(int i= 0; i < userNums.length; i++)
{
System.out.println("Input a number into your array: ");
userNums[i] = kb.nextDouble();
}
//Print Array
System.out.println("Here are all the numbers in your array:");
printArray(userNums);
//New Size
System.out.println();
do{
System.out.println("Input a new size: ");
newSize = kb.nextInt();
}while(!(newSize>userSize));
diff = newSize-userSize;
System.out.println("You need to add "+diff+" new values.");
//Resize
arrayResize(userNums, newSize);
//New input
for(int i= userNums.length; i <= newSize; i++)
{
System.out.println("Input a number into your array: ");
newArray[i] = kb.nextDouble();
}
printArray(newArray);
}
public static void printArray(double[] arr)
{
System.out.print("[");
for(int j=0; j<arr.length; j++){
if(!(j==(arr.length-1)))
{
System.out.print(+arr[j]+", ");
}
else{
System.out.print(+arr[j]);
}
}
System.out.print("]");
}
public static double[] arrayResize(double[] oldArray, int newSize)
{
double[] newArray = new double[newSize];
for(int i=0; i<newArray.length; i++)
{
if(i<oldArray.length)
{
newArray[i] = oldArray[i];
}
else
{
newArray[i] = 0.0;
}
}
return newArray;
我需要我的結果是這樣的:
Input an array size: 5
Now please enter 5 numbers
Input a number into your array: 10.0
Input a number into your array: 6.5
Input a number into your array: 4.4
Input a number into your array: 0.0
Input a number into your array: 15.0
Here are all the numbers in your array:
[10.0, 6.5, 4.4, 0.0, 15.0]
Input a new size: 7
You need to add 2 values
Input a number to add to your array: 42.42
Input a number to add to your array: 84.99
Here are all the numbers in your new array:
[10.0, 6.5, 4.4, 0.0, 15.0, 42.42, 84.99]
我的問題是,當談到時間打電話arrayResize。我不知道如何獲得新的值到數組中,我不知道如何使用它與printArray。我無法將任何代碼從一種方法移動到另一種方法。