gpt4 book ai didi

java - 如何返回包含 10 个随机整数的数组中的最大整数?

转载 作者:行者123 更新时间:2023-12-02 14:55:56 25 4
gpt4 key购买 nike

所以这是我在学校遇到的一个编码问题,我不想说“嘿伙计们帮我做作业!”,我实际上想了解这里发生了什么。我们刚刚开始使用数组,它们让我有些困惑,所以我正在寻求帮助。这是完整的问题:

Write a program in which the main method creates an array with 10 slots of type int. Assign to each slot a randomly-generated integer. Call a function, passing it the array. The called function should RETURN the largest integer in the array to your main method. Your main method should display the number returned. Use a Random object to generate integers. Create it with

Random r = new Random(7);

Generate a random integer with

x = r.nextInt();

所以,这是我目前所拥有的:

import java.util.Random;
public class Q1 {

public static void main(String[] args) {
Random r = new Random(7);
int[] count = new int[11];
int x = r.nextInt();
for (int i = 0; i < count.length; i++)
{
count[i] = x;
}
}

我创建了包含 10 个 int 的数组,然后使用 for 循环分配随机生成整数的每个槽。

不过,我很难确定下一步该怎么做。我不确定要创建哪种方法/函数,然后如何从那里获取最大的 int 并返回它。

非常感谢任何帮助,因为我真的很想了解这里发生了什么。谢谢!

最佳答案

Here is how to generate Random ints

public static void main(String[] args) {
int []count = new int[10];
Random r = new Random(7);
int x=0;
for (int i = 0; i < count.length; i++)
{
x = r.nextInt();
count[i] = x;

}
System.out.println("Max Number :"+maxNumber(count));}//Getting Max Number

Here is how to make method and get max number from list.

static int maxNumber(int[] mArray){//Passing int array as parameter
int max=mArray[0];
for(int i=0;i<mArray.length;i++){
if(max<mArray[i]){//Calculating max Number
max=mArray[i];
}
}

return max;//Return Max Number.
}

有什么不明白的就问。这就是我们如何创建返回 int 的方法。

关于java - 如何返回包含 10 个随机整数的数组中的最大整数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52922556/

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