gpt4 book ai didi

java - 阵列问题不打印中间或中位数

转载 作者:行者123 更新时间:2023-11-29 06:00:22 24 4
gpt4 key购买 nike

我希望用户能够将数字添加到数组,直到输入了预定的 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();
}
}

最佳答案

我敢肯定,如果您不知道如何构造数组,那么您不应该使用数据结构 ArrayList。这是没有 ArrayList 的完整代码版本。

  • 数组是最终的,因为它们在创建后无法更改。所以在这个例子中我使用了最大猜测数

希望这有助于...

    import java.util.Arrays;
import java.util.Scanner;

public class ArrayTest
{
Scanner input = new Scanner( System.in );

int usersGuess;
int randomNumber = 45;
int num_of_guesses = 0;

int max_guesses = 20;


public void enterNumbers()
{
int testArray [] = new int[ max_guesses ];

do
{


if ( usersGuess != randomNumber )
{
System.out.printf("Please enter numbers: ");
usersGuess = input.nextInt();

}
else
System.out.println("Correct guess");

testArray[ num_of_guesses ] = usersGuess;
num_of_guesses++;

if ( num_of_guesses >= max_guesses)
{
System.out.println("Your all out of guesses!");
break;
}

}
while ( usersGuess != randomNumber && max_guesses >= num_of_guesses );

System.out.println( "\nMiddle is: " + testArray
[ ( num_of_guesses)/ 2] );

Arrays.sort( testArray, 0, num_of_guesses );


System.out.println( "Median is: " + testArray[ ( num_of_guesses)/ 2 ] );
System.out.println();

}

}

public class Test
{
public static void main( String [] args )
{
ArrayTest arrayTest = new ArrayTest();

arrayTest.enterNumbers();
}

}

关于java - 阵列问题不打印中间或中位数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10376397/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com