gpt4 book ai didi

java - 我该如何修复此类的 "Possible Lossy Conversion from Double to Int"?

转载 作者:行者123 更新时间:2023-12-02 01:05:11 24 4
gpt4 key购买 nike

此类的目标是能够从用户那里获取降雨总量的输入。输入后,程序将显示全年降雨总量、月平均降雨量、降雨最多的月份和降雨最少的月份。这是我的代码:

import java.util.Scanner;

public class Rainfall {
private static final String[] months = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"};

public static void main(String[] args){
Scanner input = new Scanner(System.in);

final int MONTHSINYEAR = 12;
double[] rainfall = new double[MONTHSINYEAR];

System.out.println("Enter the monthly rain fall amount: ");
int i = 0;

for (i = 0; i < MONTHSINYEAR; i++){
do {
System.out.println("Enter rainfall for month " + (i + 1) + ": ");
rainfall[i] = input.nextDouble();
}
while (rainfall[i] < 0);
}

System.out.println("The total rainfall for the year is: " + totalRainfall(rainfall));
System.out.println("The average monthly rainfall is: " + averageRainfall(rainfall));
System.out.println("The month with the most rain is: " + months[maxRainfall(rainfall)]);
System.out.println("The month with the least rain is: " + months[minRainfall(rainfall)]);
}

public static double totalRainfall(double[] arr){
double total = 0;
for (int i = 0; i < arr.length; i++){
total += arr[i];
}

return total;
}

public static double averageRainfall(double[] arr){
double average = 0;
average = totalRainfall(arr) / arr.length;
return average;
}


public static double maxRainfall(double[] arr){
double max = arr[0];
double maximum = 0;

for (int i = 0; i < arr.length; i++){
if (arr[i] > max){
max = arr[i];
maximum = i;
}
}
return maximum;
}

public static double minRainfall(double[] arr){
double min = arr[0];
double minimum = 0;

for(int i = 0; i < arr.length; i++){
if(arr[i] < min){
min = arr[i];
minimum = i;
}
}
return minimum;
}
}

编译时,以下几行出现错误,提示“可能存在从 double 到 int 的有损转换”:

        System.out.println("The month with the most rain is: " + months[maxRainfall(rainfall)]);
System.out.println("The month with the least rain is: " + months[minRainfall(rainfall)]);

我不知道如何继续。应该更改什么以使这两行没有错误?

最佳答案

您的方法返回 double 值,请将其更改为 int(以及方法签名),以便它返回最大值的index

public static int maxRainfall(double[] arr){
double max = arr[0];
int maximum = 0;

for (int i = 0; i < arr.length; i++){
if (arr[i] > max){
max = arr[i];
maximum = i;
}
}
return maximum;
}

关于java - 我该如何修复此类的 "Possible Lossy Conversion from Double to Int"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60142749/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com