我有这个程序,我需要制作一个随机生成的10个数字的行,我需要找到行上最大,最小,第一个和最后一个数字。我已经有了数字线,我找到了最大和最小的数字。我需要帮助找出如何找到线上的第一个和最后一个数字。这是我到目前为止的代码:
// variables
Random generator = new Random();
int max = 0, min = 100, random, first, last;
// for
System.out.println("Here are 10 random numbers: \n");
for (int count = 1; count <= 10; count++) {
// get random number and output
random = 1 + generator.nextInt(100);
System.out.print(random + " ");
// Max number
if (random > max)
max = random;
// Min number
if (random < min)
min = random;
}
// output
System.out.print("\n\nThe first number is " + last);
System.out.print("\nThe last number is " + first);
System.out.println("\nThe largest random number is " + max);
System.out.print("The smallest random number is " + min);
答案 0 :(得分:1)
Collection和Collections是存储对象并在其上应用某些算法的非常好的工具。
试试这个:
Random generator = new Random();
final int MIN = 0, MAX = 100;
LinkedList<Integer> numberLine = new LinkedList<>();
for (int count = 1; count <= 10; count++) {
int random = generator.nextInt(MAX) + 1;
numberLine.add(random);
}
int last = numberLine.getLast();
int first = numberLine.getFirst();
int max = Collections.max(numberLine);
int min = Collections.min(numberLine);
答案 1 :(得分:0)
如果可能的话,我总是喜欢将特殊情况从循环中取出。这绝对有可能:
// variables
Random generator = new Random();
int max = 0, min = 100, random, first, last;
public FirstAndLast() {
// for
System.out.println("Here are 10 random numbers: \n");
first = nextRandomNumber();
for (int count = 2; count <= 9; count++) {
nextRandomNumber();
}
last = nextRandomNumber();
// output
System.out.print("\n\nThe first number is " + first);
System.out.print("\nThe last number is " + last);
System.out.println("\nThe largest random number is " + max);
System.out.println("The smallest random number is " + min);
}
private int nextRandomNumber() {
// get random number and output
random = 1 + generator.nextInt(100);
System.out.print(random + " ");
// Max number
if (random > max)
max = random;
// Min number
if (random < min)
min = random;
return random;
}
我介绍了一种辅助方法来处理每个数字。
顺便说一下,您似乎在输出中交换了first
和last
。
答案 2 :(得分:0)
import java.util.Random;
public class RandomGenerated {
public static void main(String[] args) {
// variables
Random generator = new Random();
int max = 0, min = 100, random, first = 0, last = 0;
// for
System.out.println("Here are 10 random numbers: \n");
for (int count = 1; count <= 10; count++) {
// get random number and output
random = 1 + generator.nextInt(100);
System.out.print(random + " ");
// last
if (count == 10) {
last = random;
}
// first
if (count == 1) {
first = random;
}
// Max number
if (random > max)
max = random;
// Min number
if (random < min)
min = random;
}
// output
System.out.print("\n\nThe first number is " + first);
System.out.print("\nThe last number is " + last);
System.out.println("\nThe largest random number is " + max);
System.out.print("The smallest random number is " + min);
}
}