4 回答
TA贡献1873条经验 获得超9个赞
解决这个问题的方法是跟踪最高降雨量的指数而不是值。您现在遇到的问题是您有 2 个不同的数组,并且其中一个数组的值与另一个数组不相关。
为此,你可以这样做:
public int getMaxRainfallIndex(double[] rainfall) {
int max = 0;
for (int i = 1; i < rainfall.length; i++)
if (rainfall[i] > rainfall[max]) {
max = i;
}
return max;
}
然后,您可以使用此返回值从原始 2 个数组中获取实际降雨量和月份。
然而,一种更简洁的方法是创建一个单独的类来存储这两条信息,这样您就可以返回包含这两条信息的整个对象。这样你甚至不必担心保留两个单独的数组。
可以这样做:
public static void main(String[] args) {
Rainfall[] rainfall = new Rainfall[12];
//Do everything else
}
public class Rainfall {
private String month;
private double rainfall;
//Constructor, Getters + Setters
}
TA贡献1946条经验 获得超3个赞
一个可能的解决方案是返回月份的索引,例如您的getMaxRainfall方法应如下所示:
public int getMaxRainfallIndex(double[] rainfall)
{
int maxIndex = 0;
double max = rainfall[0];
for(int i = 1; i < rainfall.length; i++)
if(rainfall[i] > max)
{
max = rainfall[i];
maxIndex = i;
}
return maxIndex;
}
在您的中,main您应该使用该索引来获取月份和降雨量:
int index = amazon.getMaxRainfallIndex(rainfall);
system.out.println("month of max rainfall: " + months[index]);
system.out.println("max rainfall: " + rainfall[index]);
TA贡献1752条经验 获得超4个赞
您可以创建一个单独的数组,而不是单独管理两个数组class:
public class RainfallByMonth {
private double rainfall;
private String month;
// Getter/Setters here
}
在你的主要方法中:
public static void main(String[] args) {
RainfallByMonth[] rainfallByMonths = new RainfallByMonth[12];
String[] months = new DateFormatSymbols().getMonths(); // array of months
Scanner scanner = new Scanner(System.in);
for (int i = 0; i < rainfallByMonths.length; i++) {
System.out.println("How much rainfall did you receive, in inches, for the month of: " + months[i]);
rainfallByMonths[i].setMonth(months[i]);
rainfallByMonths[i].setRainfall(scanner.nextDouble());
}
RainfallByMonth maxRainfall = getMaxRainfall(rainfallByMonths);
// Now you can print the results here
}
按月计算最大降雨量:
public static RainfallByMonth getMaxRainfall(RainfallByMonth[] rainfallByMonths) {
RainfallByMonth maxRainfall = rainfallByMonths[0];
for(int i = 1; i < rainfallByMonths.length; i++) {
if(rainfallByMonths[i].getRainfall() > maxRainfall.getRainfall()) {
maxRainfall = rainfallByMonths[i];
}
}
return maxRainfall;
}
同样,情况反之亦然min(只是条件不同)。这将更容易管理。
TA贡献1805条经验 获得超9个赞
public static void main(String[] args) {
String[] months = {"January", "February", "March","April","May","June","July","August","September","October","November","December"};
int[] weather = {10, -1, 7,44,33,6,22,54,89,21,8,51};
int max = 0;
int index= 0;
for (int i=0;i<weather.length-1;i++ ){
if (weather[i] > m){
max = weather[i];
index= i;
}
}
System.out.println(months[index]);
}
查找最高月份的示例程序。要查找最低月份降雨量,请在if条件中使用小于符号
添加回答
举报