且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Java:在用户设置的整数列表中找到最大的数字

更新时间:2023-11-26 08:05:10

此处的关键是使用

The key here is to use Collections.max.

根据其元素的自然顺序返回给定集合的最大元素.

Returns the maximum element of the given collection, according to the natural ordering of its elements.

Integer的自然顺序是从最小到最大,即升序.这使它非常适合在这里使用.

The natural ordering for Integer is from least-to-greatest, i.e. ascending. This makes it perfect to use here.

int largest = Collections.max(Arrays.asList(integer1, integer2, integer3,
    integer4, integer5));

或者,您可以仅使用循环来构建List.请参阅下面的代码,该代码提示用户输入要输入的整数.

Alternatively, you could just build the List using a loop instead. See below for code that prompts the user to input the number of integers to enter.

int n = Integer.parseInt(
    JOptionPane.showInputDialog("How many integers do you want in your list?"));
List<Integer> inputs = new ArrayList<Integer>(n);
for (int i = 0; i < n; ++i) {
  inputs.add(Integer.parseInt(
      JOptionPane.showInputDialog("Enter an integer:")));
}
int largest = Collections.max(inputs);
JOptionPane.showMessageDialog(null, "The largest number is: " + largest);