![](/img/trans.png)
[英]I am trying to set my program to print out the part of my month array that correlates to the index of the largest value in my temp array
[英]why does my program print the numbers in my array as zeros but still print the largest value out of the array?
import java.util.*;
import java.util.Arrays;
import java.util.Random;
class EZD_maxTester
{
static int variables[] = new int[10];
static int maximum()
{
Random rand = new Random();
int max = variables[0];
for (int i = 0; i < 10; i++)
{
variables[i] = rand.nextInt(100)+1;
}
for (int a = 0; a < variables.length; a++)
{
if (variables[a] > max)
{
max = variables[a];
}
}
return max;
}
public static void main(String Args[])
{
int option;
do{
Scanner kbReader = new Scanner(System.in);
System.out.println("Integers that will be compared: " + Arrays.toString(variables));
System.out.println("");
System.out.println("The maximum value is " + maximum());
System.out.println("");
System.out.println("Type 1 to run again. Type 0 to end the program.");
option = kbReader.nextInt();
while(option !=1 && option !=0)
{
if (option != 1 && option != 0)
{
System.out.println("Please enter 1 to run again or 0 to end the program.");
option = kbReader.nextInt();
}
}
System.out.println("");
kbReader.close();
}while(option==1);
}
}
(我對編碼非常新,所以我的代碼可能不盡如人意!這也是我第一次在這里問一個問題)
我們正在學習類中的數組,我必須編寫一個程序,找到隨機生成數字數組中的最大整數,但是當我運行程序時,數組只是打印為零但它仍然給我最大的值(? ?)。 當我使用static int variables[] = new Random().ints(10, 0, 100).toArray();
時,它會正確打印static int variables[] = new Random().ints(10, 0, 100).toArray();
,但是當我再次運行程序時,它只會打印同一組隨機數。 如何讓它打印出數組而不用零掩蓋我的數字?
您正在調用System.out.println(Arrays.toString(variables));
在maximum()
之前 - 第二個實際設置數組中的值,因此在打印時它們都為零。 在調用maximum();
之后將打印移動到maximum();
// System.out.println("Integers that will be compared: " + Arrays.toString(variables));
System.out.println("The maximum value is " + maximum());
System.out.println("Integers that were compared: " + Arrays.toString(variables));
你打電話的時候
System.out.println(Arrays.toString(variables));
你還沒有填寫數組。
數組以maximum
方法填充。
一個簡單的改變是在填充數組后打印數組
您需要在此語句之前調用maximum()
方法:
System.out.println("Integers that will be compared: " + Arrays.toString(variables));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.