我在这个机智的结尾。我需要创建一个数组,然后使用单独的方法来调整它的大小,然后使用另一种方法来打印它。这里是我的代码至今:在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。我无法将任何代码从一种方法移动到另一种方法。