使用预定义的Java方法查找数组中的最大数字 [英] Finding the largest number in an array using predefined java methods
本文介绍了使用预定义的Java方法查找数组中的最大数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是我正在处理的代码段,我的目标是使用预定义的Java方法从列表中找到最大值.
Here is the code snippet that I am working on and my goal is to find the largest value from the list using predefined java methods.
import java.util.*;
public class Test {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("Enter a list of integers: ");
int array[] = new int[10];
for (int i = 0; i < array.length; i++) {
array[i] = s.nextInt();
}
for (int j = 0; j < array.length; j++) {
if (j < array.length) {
int maximum = Math.max(array[j], array[j + 1]);
}
}
System.out.println("Largest number of the list: " + maximum);
}
}
我得到的错误如下:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
maximum cannot be resolved to a variable
我希望有人能帮助我解决这个问题.
I hope someone can help me resolve this.
推荐答案
您可以仅迭代数字数组并跟踪看到的最大值:
You may just iterate the array of numbers and keep track of the largest value seen:
int largest = Integer.MIN_VALUE;
for (int j=0; j < array.length; j++) {
if (array[j] > largest) {
largest = array[j];
}
}
注意:上面的代码段假定您在输入数组中至少有一个数字.
Note: The above snippet assumes that you have at least one number in the input array.
这篇关于使用预定义的Java方法查找数组中的最大数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文