如何开始操作输入的数据?我只是找不到从哪里开始



所以我正在为Java类制作一个程序,需要找到我输入的一组温度的平均值、模式、最大值、最小值和中值。到目前为止,我拥有的是:

import javax.swing.*;
public class Temps {
    private int temp[] = new int[5];
    String inputStr;
    int inputInt = 0;
    public void startApp()
    {
        for (int i = 0; i < temp.length; i++)
        {
            inputStr = JOptionPane.showInputDialog("Enter new temp.");
            inputInt = Integer.parseInt(inputStr);
            temp[i] = inputInt; 
        }
    }

    public static void main(String[] args)
    {
        Temps obj = new Temps();
        obj.startApp();     
    } 
}

在哪里以及如何开始操作数组中的值?我不知道从哪里开始,任何帮助都会很棒。

我将为您提供一种入门方法。假设您的阵列是int[] nums = {1,1,2,2,3};

我们知道平均值计算为(1+1+2+2+3)/5=9/5=1.8,这里有一种方法可以做到这一点:

public double calculateMean(int[] nums) {
    double sum = 0; //<--if you use int here, your value would be 1.0 not 1.8
    for(int i = 0; i < nums.length; i++) {
        sum += nums[i];
    }
    return sum / nums.length;
}

你可以在你的主要方法中使用它:

int[] nums = {1,1,2,2,3};
double d = calculateMean(nums);
System.out.println(d); //the result is 1.8

我已经为您完成了均值方法,这样您就可以了解应该如何完成它。我猜你可以根据我的代码自己解决剩下的问题。注意:这不是最有效或最优雅的方法,但它可以完成任务。祝你好运

import javax.swing.*;
public class Temps {
    private static int temp[] = new int[5];
    String inputStr;
    int inputInt = 0;
    public void startApp() {
        for (int i = 0; i < temp.length; i++) {
            inputStr = JOptionPane.showInputDialog("Enter new temp.");
            inputInt = Integer.parseInt(inputStr);
            temp[i] = inputInt;
        }
    }
    public static int meanMethod(int temp[]) {
        int mean, sum;
        mean = 0;
        sum = 0;
        for (int i = 0; i < temp.length; i++) {
            sum += temp[i];
            if (i == (temp.length - 1)) {
                mean = sum / temp.length;
                return mean;
            }
        }
        return mean;
    }

    public static void main(String[] args) {
        Temps obj = new Temps();
        obj.startApp();
        System.out.println(obj.meanMethod(temp));
        /*
        You could do JOptionPane instead of System.out.println here. Just do:
        JOptionPane.showMessageDialog(null, obj.meanMethod(temp));
        */
    }
}

相关内容

最新更新