我希望用户能够将数字添加到数组中,直到randomNumber
输入预定值。然后我想打印数组的中间和中位数。
该代码适用于用户输入,但我从中间或中位数没有得到任何东西,它只是说0
。
谁能帮我解决这个问题?这是我的代码:
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();
}
}