I want user to be able to add number(s) to an array until a predetermined randomNumber has been entered. Then I want to print the middle and median of the array.
The code works for the user inputs but I get nothing from the middle or median, it just says 0.
Could anyone please help me with this? Here is my code:
import java.util.Arrays;
import java.util.Scanner;
public class ArrayTest {
Scanner input = new Scanner( System.in );
int usersGuess;
int randomNumber = 45;
public void enterNumbers() {
do {
System.out.printf("Please enter numbers: ");
usersGuess = input.nextInt();
if ( usersGuess != randomNumber ) {
System.out.printf("Please enter numbers: ");
usersGuess = input.nextInt();
}
else
System.out.println("Correct guess");
}
while ( usersGuess != randomNumber );
int testArray [] = new int[ 20 ];
boolean correctGuess = false;
for ( int i = 0; i < testArray.length; i++ ) {
testArray[ i ] = usersGuess ;
if ( testArray[ i ] == randomNumber ) {
correctGuess = true;
break;
}
}
System.out.println();System.out.println( "Middle is: " + testArray
[ ( testArray.length + 1)/2] );
Arrays.sort( testArray );
System.out.println( "Median is: " + testArray[ testArray.length/2] );
System.out.println();
}
public class Test {
public static void main( String [] args ){
ArrayTest arrayTest = new ArrayTest();
arrayTest.enterNumbers();
}
}
I am pretty sure if you do not know how to structure arrays then you should not be using the data structure ArrayList yet. Here is a completed version of the code without an ArrayList.
Hope this helps…