[英]How to find the index of the largest and smallest value in an array?
我正在尝试制作将数字放入数组的方法,但我坚持如何将最大/最小值的索引“作为数组”返回。
public static void main(String[] args) {
array();
int max[];
}
public static void array() {
Scanner input = new Scanner(System.in);
System.out.println("Length of the Array");
int x = input.nextInt();
int array[] = new int[x];
System.out.println("chose the numbers");
for (int i = 0; i < x; i++) {
array[i] = input.nextInt();
}
}
public static int max(int[] array) {
int max = 0;
int index = -1;
for (int i = 0; i < array.length; i++) {
if (array[i] > max) {
max = array[i];
index = i;
}
{
return index;
第一部分是处理数组中的长度和数字,但最大的小值作为数组的返回索引。 我不知道如何继续。
这将提示您输入数组,然后 System.out.println 最小值和最大值。
我刚刚修改了此链接中的代码:
https://www.sanfoundry.com/java-program-find-largest-number-array/
import java.util.Scanner;
public class Largest_Smallest {
public static void main(String[] args)
{
int n, max, min;
Scanner s = new Scanner(System.in);
System.out.print("Enter number of elements in the array:");
n = s.nextInt();
int a[] = new int[n];
System.out.println("Enter elements of array:");
for(int i = 0; i < n; i++)
{
a[i] = s.nextInt();
}
max = a[0];
for(int i = 0; i < n; i++){
if(max < a[i])
{
max = a[i];
}
}
min = max;
for(int i = 0; i < n; i++){
if(min > a[i])
{
min = a[i];
}
}
System.out.println("Maximum value:"+max);
System.out.println("Maximum value:"+min);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.