两种方法编写程序,创建包含 10 个数的数组,使用循环语句为数组赋值,输出 其中最大值及对应的元素下标。考虑整型、小数、字符等不同类型数组的情况
时间: 2024-05-15 10:17:59 浏览: 84
您好!感谢您向我提出问题。
针对您提出的问题,以下是一种解决方法:
方法一:使用泛型,创建一个可以适用于不同类型数组的函数,实现求最大值及对应下标的功能。
```java
import java.util.Arrays;
public class MaxValueFromArray {
public static <T extends Comparable<T>> void findMaxValueAndIndex(T[] array) {
int maxIndex = 0;
T maxValue = array[maxIndex];
for (int i = 1; i < array.length; i++) {
if (array[i].compareTo(maxValue) > 0) {
maxIndex = i;
maxValue = array[maxIndex];
}
}
System.out.println("The maximum value is: " + maxValue);
System.out.println("The index of the maximum value is: " + maxIndex);
}
public static void main(String[] args) {
Integer[] intArray = new Integer[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
findMaxValueAndIndex(intArray);
Double[] doubleArray = new Double[]{1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7, 8.8, 9.9, 10.0};
findMaxValueAndIndex(doubleArray);
Character[] charArray = new Character[]{'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'};
findMaxValueAndIndex(charArray);
}
}
```
输出结果:
```
The maximum value is: 10
The index of the maximum value is: 9
The maximum value is: 10.0
The index of the maximum value is: 9
The maximum value is: j
The index of the maximum value is: 9
```
方法二:针对不同类型数组,分别创建对应的函数,实现求最大值及对应下标的功能。
```java
public class MaxValueFromArray {
public static void findMaxValueAndIndex(int[] array) {
int maxIndex = 0;
int maxValue = array[maxIndex];
for (int i = 1; i < array.length; i++) {
if (array[i] > maxValue) {
maxIndex = i;
maxValue = array[maxIndex];
}
}
System.out.println("The maximum value is: " + maxValue);
System.out.println("The index of the maximum value is: " + maxIndex);
}
public static void findMaxValueAndIndex(double[] array) {
int maxIndex = 0;
double maxValue = array[maxIndex];
for (int i = 1; i < array.length; i++) {
if (array[i] > maxValue) {
maxIndex = i;
maxValue = array[maxIndex];
}
}
System.out.println("The maximum value is: " + maxValue);
System.out.println("The index of the maximum value is: " + maxIndex);
}
public static void findMaxValueAndIndex(char[] array) {
int maxIndex = 0;
char maxValue = array[maxIndex];
for (int i = 1; i < array.length; i++) {
if (array[i] > maxValue) {
maxIndex = i;
maxValue = array[maxIndex];
}
}
System.out.println("The maximum value is: " + maxValue);
System.out.println("The index of the maximum value is: " + maxIndex);
}
public static void main(String[] args) {
int[] intArray = new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
findMaxValueAndIndex(intArray);
double[] doubleArray = new double[]{1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7, 8.8, 9.9, 10.0};
findMaxValueAndIndex(doubleArray);
char[] charArray = new char[]{'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'};
findMaxValueAndIndex(charArray);
}
}
```
输出结果:
```
The maximum value is: 10
The index of the maximum value is: 9
The maximum value is: 10.0
The index of the maximum value is: 9
The maximum value is: j
The index of the maximum value is: 9
```
以上是两种数组求最大值及对应下标的实现方法,希望对您有所帮助。
阅读全文