【问题标题】:Java - Displaying the temperature statistics of the week using arraysJava - 使用数组显示一周的温度统计数据
【发布时间】:2016-03-19 21:49:48
【问题描述】:

我目前正在为学校的作业处理一个问题集,我真的快要完成了,但是我遇到了一些编译错误。

问题集包括显示平均周数。温度、最高温度、最低温度以及一周中最热和最冷的日子。

目前我正在尝试做的是显示一周中最热的日子,如果我解决了这个问题,我可以很容易地找到一周中最冷的日子。

我在尝试编译包含以下内容的代码时遇到一些编译错误

  • 不兼容的类型:int[] 无法转换为 int

  • 错误:找不到符号

如果我能得到一些关于该做什么的指导,那就太好了,我现在迷路了。

http://ideone.com/rOqV2Z

public class test1
{
// Main method
public static void main(String[] args)
{
    // Create a new scanner
    Scanner input = new Scanner(System.in);

    // Set array list
    int[] tempList = new int[7];

    // Prompt user for input and store input
    System.out.println("Enter the hightest temperature of each day for a week (starting on Sunday): ");
        for(int i = 0; i < tempList.length; i++)
            tempList[i] = input.nextInt();

    // Averages temperature - @@@@@@@ ASK WHY IT THERE ARE SO MANY DECIMALS ON THE SIDE WHEN AVERAGE ALL 1's
    double avgTemp = avgTemp(tempList);
        System.out.printf("The average temperature of the week is: %.2f degree %n", avgTemp);

    // Display hottest temperature
    int maxTemp = maxTemp(tempList);
        System.out.println("The highest temperature of the week is: " + maxTemp + " degree");

    // Display coldest temperature
    int minTemp = minTemp(tempList);
        System.out.println("The coldest temperature of the week is: " + minTemp + " degree");


    int[] maxTempList = searchTemp(tempList, maxTemp);

    for(int i = 0; i < maxTempList.length; i++){
        System.out.print("The hottest days of the week are: " +maxTempList[i]);

    System.out.print(weekDay(tempList,maxTemp));
    }
}

// Average the temperature
public static double avgTemp(int[] array)
{
    int tempTotal = array[0];

    // Total temperature values
    for(int i = 0; i < array.length; i++)
        tempTotal = array[i]+tempTotal;

    // Return temperature average.
    return ((double)tempTotal/array.length);
}

// Get hottest temperature
public static int maxTemp(int[] array)
{
    int max = array[0];

    // Check and replace max temp
    for(int i = 1; i < array.length; i++){
        if(max < array[i])
            max = array[i];

    }
    return max;
}

// Get coldest temperature
public static int minTemp(int[] array)
{
    int min = array[0];
    for(int i = 1; i < array.length; i++){
        if(min > array[i])
            min = array[i];
    }
    return min;
}


// Return days
public static String weekDay(int i, int[] array)
{
    int[] displayWeekDay = searchTemp(array, i);

    for(i = 0; i < displayWeekDay.length; i++){

        String weekDay = "";
        switch(i)
        {
            case 0: return "Sunday";
            case 1: return "Monday";
            case 2: return "Tuesday";
            case 3: return "Wednesdays";
            case 4: return "Thursday";
            case 5: return "Friday";
            case 6: return "Saturday";
        }
    }
    return weekDay;
}


// Finds the index of the hottest/coldest days
public static int[] searchTemp(int[] temp, int key)
{
    int count = 0;
    for(int i = 0; i < temp.length; i++){
        if(temp[i] == key)
            count++;
    }

    int[] index = new int[count];
    for(int j = 0; j < index.length; j++){
        for(int i = 0; i < temp.length; i++){
            if(temp[i] == key){
                if(j > 0 && index[j - 1] == i)
                    continue;
                else{
                    index[j] = i;
                    break;
                }
            }
        }
    }
    return index;
}

}

【问题讨论】:

  • 我建议您不要再犯学生错误,即专注于用户交互和输入,而忽略了开发 API 和思考计算应该如何工作。通过硬连线或简单的测试输入来获得正确的输入,然后担心用户将如何提供您需要的数据。

标签: java arrays


【解决方案1】:

我使用您链接的网站检查了代码。

  1. 首先,您应该学会使用调试器,因为它通常会告诉您错误是什么以及在哪里找到它。
Main.java:42: error: incompatible types: int[] cannot be converted to int
System.out.print(weekDay(tempList,maxTemp));
                             ^

这里指出tempList的数据类型有错误。意思是int数组不能转换为int。如果您查看weekDay() 函数,您会看到第一个参数要求一个int,但您传递的是一个int 数组。它不会工作。

public static String weekDay(int i, int[] array)

编辑:如果您想将特定值从数组传递给函数,只需使用

System.out.print(weekDay(tempList[IntegerPosition],maxTemp));
                                        ^

  1. Main.java:104: error: cannot find symbol
    return weekDay;
           ^
    

这仅仅意味着它在当前范围内找不到变量。这方面有很多东西要学,但我会直奔主题。

    // Return days
    public static String weekDay(int i, int[] array)
    {
        int[] displayWeekDay = searchTemp(array, i);
        String weekDay = "";
        for(i = 0; i < displayWeekDay.length; i++){

            //String weekDay = ""; Declare weekDay outside of the loop
            switch(i)
            {
                //Assign a value to weekDay, simply returning won't do it
                case 0: weekDay = "Sunday"; break;
                case 1: weekDay = "Monday"; break;
                case 2: weekDay = "Tuesday"; break;
                case 3: weekDay = "Wednesdays"; break;
                case 4: weekDay = "Thursday"; break;
                case 5: weekDay = "Friday"; break;
                case 6: weekDay = "Saturday"; break;
            }
        }
        return weekDay;
    }

编辑 2:根据讨论,这是为了能够打印温度最高的多天

//Call the function directly without putting a print statement around it
weekDay(maxTemp,tempList)); 
//...
// Return days
public static void weekDay(int i, int[] array) //Change the return type to void
{
    int[] displayWeekDay = searchTemp(array, i);
    for(i = 0; i < displayWeekDay.length; i++){
        switch(displayWeekDay[i])
        {
            //Print each one
            case 0: System.out.println("Sunday"); break;
            case 1: System.out.println("Monday"); break;
            case 2: System.out.println("Tuesday"); break;
            case 3: System.out.println("Wednesday"); break;
            case 4: System.out.println("Thursday"); break;
            case 5: System.out.println("Friday"); break;
            case 6: System.out.println("Saturday"); break;
        }
    }
}

【讨论】:

  • 我遇到了一个奇怪的逻辑错误,当它显示一周中最热的那一天时,它一直显示星期六,而且只有星期六。 ideone.com/MYlbyS这是我更新的代码
  • @Flinze 我忘了在每个案例之后添加 break 语句。请查看我的编辑。
  • 再次运行我的程序后,我的“工作日”方法似乎有问题,因为每次运行它时,无论如何它只显示“星期六”。我试图用这种方法做的是显示一周中最热的日子。假设用户输入 10、18、15、15、17、18、12。由于 18 是最高的,它应该显示“星期一”和“星期五”作为一周中最热的一天。我已经更新了我的代码,我仍然不确定现在出了什么问题。 ideone.com/MYlbyS
  • @Flinze 嗯,在您的第一个版本的 weekday 函数中,您在每种情况下都返回了 [day]。这是您的意图还是您打算将其分配给变量 weekDay?
  • @Flinze 在这种情况下,您可以简单地说 return "";或返回空值;该函数希望您在每个相关案例中返回一个字符串。
【解决方案2】:

单独解决每个问题:

  1. “不兼容的类型:int[] 无法转换为 int”问题

这是由System.out.print(weekDay(tempList,maxTemp)); 行引起的。 weekDay 方法的方法签名是 public static String weekDay(int i, int[] array),但是使用错误顺序调用该方法 - tempList 的类型为 int[]maxTemp 的类型为 int。反转方法调用或方法签名中的参数将解决错误。

  1. “错误:找不到符号”

这是一个与变量范围有关的问题。声明变量时(例如int i;String name = "John";),该变量只能在声明它的范围内使用。在weekDay 方法中,weekDay 变量在for 循环内声明(即在与for 循环关联的大括号内)。因此,weekDay 变量仅具有for 循环的范围,并且不能在该范围之外被引用。将weekDay 的声明移到for 循环之外将解决此问题。有关变量范围规则的更多信息,请参阅here

【讨论】:

    【解决方案3】:

    就像我说的,先考虑 API,然后再输入。此实现假定 JDK 8 和 lambdas:

    import java.util.Date;
    import java.util.Map;
    import java.util.TreeMap;
    import java.util.stream.Collectors;
    
    /**
     * Created by Michael
     * Creation date 3/19/2016.
     * @link https://stackoverflow.com/questions/36107614/java-displaying-the-temperature-statistics-of-the-week-using-arrays
     */
    public class TemperatureHistory {
    
        private Map<Date, Double> temperatureHistory = new TreeMap<>();
    
        public void addDataPoint(Date date, Double temperature) {
            if (date != null && temperature != null) {
                this.temperatureHistory.put(date, temperature);
            }
        }
    
        public Double getAverageTemperature() {
            double averageTemperature = 0.0;
            if (this.temperatureHistory.size() > 0) {
                averageTemperature = this.temperatureHistory.values()
                        .stream()
                        .collect(Collectors.averagingDouble(value -> value));
            }
            return averageTemperature;
        }
    
        public Double getMaxTemperature() {
            return this.temperatureHistory.entrySet()
                    .stream()
                    .max((e1, e2) -> e1.getValue().compareTo(e2.getValue()))
                    .get()
                    .getValue();
        }
    
        public Double getMinTemperature() {
            return this.temperatureHistory.entrySet()
                    .stream()
                    .min((e1, e2) -> e1.getValue().compareTo(e2.getValue()))
                    .get()
                    .getValue();
        }
    
        public Date getFirstDateForTemperature(Double temperature) {
            return this.temperatureHistory.entrySet()
                    .stream()
                    .filter(e -> e.getValue().equals(temperature))
                    .map(Map.Entry::getKey)
                    .findFirst()
                    .orElse(null);
        }
    
        public Date getDateMinTemperature() {
            return this.getFirstDateForTemperature(this.getMinTemperature());
        }
    
        public Date getDateMaxTemperature() {
            return this.getFirstDateForTemperature(this.getMaxTemperature());
        }
    }
    

    【讨论】:

    • Lambda 对于初学者来说有点难以消化。但可能对其他读者有用。
    • 同意。我这样做是为了练习。
    【解决方案4】:

    在你的 main 方法的最后一条语句中你做了System.out.print(weekDay(tempList,maxTemp)); weekDay 将 int 作为第一个参数,但 tempList 的类型为 int[]。您应该在方法调用或定义中交换 tempList 和 maxTemp 的顺序。

    【讨论】:

      【解决方案5】:
      public static String weekDay(int i, int[] array)
      

      在这个方法中,你假设返回一个字符串类型的值

      edit:将字符串变量更改为其他名称。你不能让它和方法的名字一样

      【讨论】:

        猜你喜欢
        • 2012-04-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-09-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多