I'm stuck on a Java coding assignment. I'm supposed to create three methods (askInfo
, copyInfo
, and setArray
) for an existing program that lets the user input numbers into an array, and then organizes and prints that array. AskInfo
receives the array as a parameter, asks for the index values from the user, and returns the amount of inputted numbers as int. CopyInfo
copies the values into a new array with a length of the returned amount of numbers, and setArray
sorts the numbers.
My problem is that, according to the assignment, askInfo
is only supposed to return the amount of inputted numbers. Thus it leaves the values of the array printed with it inside the method, making copyInfo
unable to retrieve those values and copy them into the second array. How would you suggest I get past this problem without the ability to edit the main method?
Main method:
int[] tempArray = new int[100];
System.out.println("Type in numbers. Type zero to quit.");
int amountOfNumbers = askInfo(tempArray);
int[] realArray = new int[amountOfNumbers];
copyInfo(realArray, tempArray);
setArray(realArray);
printArray(realArray);
My code:
public static int askInfo (int[] tempArray) { //asks for numbers and assigns them to tempArray, returns the length of realArray
int count = 0;
Scanner reader = new Scanner(System.in);
for (int i =0;i<tempArray.length;i++){
System.out.print((i+1)+". number: ");
tempArray[i] = reader.nextInt();
count++;
if (tempArray[i] == 0) //stops asking for values if user inputs 0
return count;
}
return count;
}
public static int[] copyInfo (int[] realArray, int[] tempArray) { //copies tempArray's values to realArray
for (int i=0; i<realArray.length;i++){
realArray[i] = tempArray[i];
}
return realArray;
}
public static int[] setArray (int[] realArray) { //sorts realArray from largest value to smallest
for (int i=0;i<realArray.length;i++){
for (int j=i+1;j<realArray.length;j++){
if (realArray[i]<realArray[j]){
int tmp = realArray[i];
realArray[i] = realArray[j];
realArray[j] = tmp;
}
}
}
return realArray;
}
Right now the program does compile, but the values of the arrays realArray
and tempArray
get outside of the askInfo
method are null. Keep in mind that I cannot edit the main method - I can only edit the three methods I wrote.