我有一個 50 的固定變數。我有兩個不同的陣列(具有固定數字)。我需要將第一個變數 (50) 與第一個陣列的元素相加,然后將結果除以另一個陣列的每個元素。然后我需要列印該陣列的最大數量,但顯示索引號(應該是 2)。我無法通過參考最大數字來弄清楚如何拉索引。
我的代碼使用硬代碼顯示索引,我需要修復它,你能幫我嗎?
public static void main(String[] args) {
int h = 50;
int d [] = { 10, 25, 5 };
int z [] = { 2, 3, 1 };
String result = "";
for (int i = 0; i < d.length; i ) {
result = ((h d[i]) / z[i]) ",";
}
String str = result;
String[] string = str.replaceAll("\\[", "").replaceAll("]", "").split(",");
int[] arr = new int[string.length];
for (int i = 0; i < string.length; i ) {
arr[i] = Integer.valueOf(string[i]);
}
// CAN'T USE HARD CODE HERE, PLEASE HELP
Arrays.stream(arr).max().getAsInt();
System.out.println("The largest number index is: " findIndex(arr, 55));
}
public static int findIndex(int arr[], int t) {
ArrayList<Integer> list = new ArrayList<>();
for (int i : arr)
list.add(i);
return list.indexOf(t);
}
}
uj5u.com熱心網友回復:
我不明白你為什么將結果存盤為字串,然后將此字串轉換為 int 陣列。可以直接保存int陣列。
public static void main(String[] args) {
int h = 50;
int d [] = { 10, 25, 5 };
int z [] = { 2, 3, 1 };
int result [] = new int[d.length];
int max = -1;
int indexMax = -1;
for (int i = 0; i < d.length; i ) {
result[i] = ((h d[i]) / z[i]);
if(result[i]>max){
max = result[i];
indexMax = i;
}
}
System.out.println(max);
System.out.println(indexMax);
}
uj5u.com熱心網友回復:
這是我對您的問題的解決方案
這個答案是通用的(您可以更改陣列的值,但它必須在索引中相等)
import java.util.Arrays;
import java.util.Collections;
public class Main{
public static void main(String[] args) {
int h = 50;
int d [] = { 10, 25, 5 };
int z [] = { 2, 3, 1 };
// here we sum every element of the first array to variable h (that equals 50)
for (int i = 0 ; i < d.length ; i ){
d [i] = d[i] h ;
}
// here we divide every element of the first array to other array .
for (int i = 0 ; i < d.length ; i ){
d [i] = d[i] / z[i] ;
}
// here we want to find the max
int max = Arrays.stream(d).max().getAsInt();
// here we get the index of the max value
int index = 0;
for (int i = 0 ; i < d.length ; i ){
if (d[i] == max){
index = i;
break;
}
}
System.out.println("The largest number index is: " index);
}}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/421100.html
標籤:
