作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我希望用户能够将数字添加到数组,直到输入了预定的 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/
我是一名优秀的程序员,十分优秀!