【问题标题】:Java - Returning multiple strings in an arrayJava - 返回数组中的多个字符串
【发布时间】:2016-03-20 15:39:06
【问题描述】:

我目前正在为学校的作业处理一个问题集,我真的快要完成了,但是在运行我的程序时遇到了逻辑错误。

问题集包括显示平均周数。温度、最高温度、最低温度以及一周中最热和最冷的日子(如果也有多个显示的话)。

我目前遇到的问题是,如果有多个日子是最热或最冷的,很可能是由于我的方法,我的程序不会显示星期几。 (工作日)。

例如我想要的: 示例 1:

输入一周内每天的最高温度(从周日开始):

11 21 15 12 21 15 9

一周平均气温:14.86度

本周最高气温:21度

本周最冷的温度是:9度

一周中最热的日子是:周一、周四 最冷的日子是:星期六

但是我遇到的问题是,当我尝试运行我的代码时会发生这种情况(从示例 1 复制相同的温度):

示例 2:

输入一周内每天的最高温度(从周日开始):

11 21 15 12 21 15 9

一周平均气温:14.86度

本周最高气温:21度

本周最冷的温度是:9度

一周中最热的日子是:MondayMonday // 这是我当前的问题。

我认为问题出在我的名为“weekDay”的方法中,很可能是它没有调用一周中的两个不同的日子,而是只调用一个,并且它会根据温度的多少显示 x 次与最大值或最小值相同。如果能得到这方面的指导就太好了,谢谢。

http://ideone.com/DAUcdR

public class test2
{
// 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 
    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");


    // Display hottest days of the week
    int[] maxTempList = searchTemp(tempList, maxTemp);
    System.out.print("The hottest days of the week are: ");
    for(int i = 0; i < maxTempList.length; i++)
        System.out.print(weekDay(maxTemp,tempList));

    // Display the coldest days of the week
    int[] minTempList = searchTemp(tempList, minTemp);
    System.out.println("\n The coldest days of the week are: ");
    for(int i = 0; i < minTempList.length; i++)
        System.out.print(weekDay(minTemp,tempList));
}

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

    // Add all temperature values
    for(int i = 1; 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)
{
    // Set hottest day variable
    int max = array[0];

    // Check and replace max temperature
    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)
{
    // Set coldest day variable
    int min = array[0];

    // Check and replace coldtest temperature
    for(int i = 1; i < array.length; i++){
        if(min > array[i])
            min = array[i];
    }
    return min;
}

public static String weekDay(int i, int[] array)
{
    int[] displayWeekDay = searchTemp(array, i);
    String[] weekDay = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};
    for(int j = 0; j < displayWeekDay.length; j++){
        int days = displayWeekDay[j];
        return weekDay[days];
    }
    return null;
}
// Finds the index of the hottest/coldest days
public static int[] searchTemp(int[] temp, int key)
{

    int count = 0;
    // Searches the array for the index where the element value is the same
    for(int i = 0; i < temp.length; i++){
        // When the number is the same as the key, increase count
        if(temp[i] == key)
            count++;
    }

    // Create index array based on same number to the key
    int[] index = new int[count];
    // Copy index numbers of the key into index array
    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;
}

}

【问题讨论】:

    标签: java arrays methods


    【解决方案1】:

    修改您的 weekDay 方法,如下所示,它将返回一个具有最高温度的工作日数组,然后您可以使用它来打印那些日子:

    public class DisplayWeekTempStat {
    // 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
        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");
    
        // Display hottest days of the week
    
        System.out.print("The hottest days of the week are: ");
        String[] tempMaxWeekDay = weekDay(maxTemp, tempList);
        for (int num = 0; num < tempMaxWeekDay.length; num++) {
            if (tempMaxWeekDay[num] != null)
                System.out.println(tempMaxWeekDay[num]);
        }
    
        // Display the coldest days of the week
        System.out.println("\n The coldest days of the week are: ");
        String[] tempMinWeekDay = weekDay(minTemp, tempList);
        for (int num = 0; num < tempMinWeekDay.length; num++) {
            if (tempMinWeekDay[num] != null)
                System.out.println(tempMinWeekDay[num]);
        }
    }
    
    // Average the temperature
    public static double avgTemp(int[] array) {
        // Set a total temperature variable
        int tempTotal = array[0];
    
        // Add all temperature values
        for (int i = 1; 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) {
        // Set hottest day variable
        int max = array[0];
    
        // Check and replace max temperature
        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) {
        // Set coldest day variable
        int min = array[0];
    
        // Check and replace coldtest temperature
        for (int i = 1; i < array.length; i++) {
            if (min > array[i])
                min = array[i];
        }
        return min;
    }
    
    public static String[] weekDay(int i, int[] array) {
        String[] maxWeekDays = new String[7];
        String[] weekDay = { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" };
        int k = 0;
        for (int j = 0; j < weekDay.length; j++) {
            if (array[j] == i) {
                maxWeekDays[k] = weekDay[j];
                k++;
            }
        }
        return maxWeekDays;
    }
    

    }

    【讨论】:

    • 你必须在 out 代码中替换这个,以打印从这个 weekDay 方法返回的数组中的天数: // 显示一周中最热的天 int[] maxTempList = searchTemp(tempList, maxTemp); System.out.print("一周中最热的日子是:"); for (String s : weekDay(maxTemp,tempList)) { if (s != null) System.out.println(s); }
    • 我已经为你编辑了整个代码,请尝试现在它会工作:)
    • 只需从我上面的解决方案中复制粘贴整个代码就可以了
    • 你没有改变 weekDay 方法的返回类型,我在我的答案中修改了完整的代码,请使用它。
    • 如果是,你想使用普通的 for 循环,是的,也可以使用普通的 for 循环,但是对于数组和集合,这个增强的循环效果更好
    【解决方案2】:

    您的 weekDay() 方法与 searchTemp() 方法基本相同。如果您查看 weekDay(),您将在内部看到您正在调用 searchTemp()。从 weekDay() 方法中删除 searchTemp(),可能是这样的:

    public static String weekDay(int i)
    {   int currentDay = 0;
        if((i / 7) == 0){
            currentDay = i;
        }
        else{
            currentDay = i % 7;
        }
        String[] weekDay = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};
        return weekDay[currentDay];
    }
    

    这假设您不关心现在是几月,并且该月总是从星期日开始

    【讨论】:

    • 我在运行代码时收到此错误:一周中最热的日子是:线程“main”中的异常 java.lang.ArrayIndexOutOfBoundsException: 15 at javaTest.weekDay(javaTest.java:100)在 javaTest.main(javaTest.java:45)
    • 你 weekDay() 函数需要做一些工作,试试看我在我编辑的答案上做了什么
    • 我不确定你为什么要尝试使用 currentDay = i%7;?
    • 您将月份中的日期传递给 weekDay() 方法,i % 7 所做的是返回星期几。然后将其插入 weekDay 数组以获取星期几的名称。
    • 你的意思是我将星期几传递给 weekDay() 方法?这是没有意义的,因为已经给出了最热天的索引,它给了我一周中的随机一天,比如最高温度是在星期一(元素 1),然后如果它进入你的“int currentDay = i %7;"它给出了 6 作为显示星期六的余数...
    猜你喜欢
    • 2011-11-06
    • 1970-01-01
    • 2014-01-16
    • 2021-03-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-27
    相关资源
    最近更新 更多