對不起,我會重申這個問題。我有12個元素的數組:如何將元素添加到方法中?
1.6, 2.1, 1.7, 3.9, 3.7, 3.9, 2.9, 4.3, 2.4, 3.7
我想這個數組中的最大值。問題是如何從我的主類調用方法到我的驅動程序類中創建的對象?
//MAIN CLASS
import java.util.Scanner;
public class Rainfall
{
private double total = 0;
private double average;
private double max;
private double smallest;
private double rain[];
Scanner scan = new Scanner(System.in);
public Rainfall(double...rainfall)
{
double[] rain = {1.6 , 2.1, 1.7, 3.9, 3.7, 3.9, 2.9, 4.3, 2.4, 3.7};
}
public double getTotal()
{
total = 0;
for(int i = 0; i < 12; i++)
{
total = total + rain[i];
}
System.out.println("The total rainfall for the year is: " + total);
return total;
}
public double getAverage()
{
average = total/12;
System.out.println("The average monthly rainfall is: " + average);
return average;
}
public double getMostRain()
{
double max = 0;
int maxind = 0;
for(int i = 0; i < 12; i++)
{
if (rain[i] > max)
{
max = rain[i];
maxind = i;
}
}
System.out.println("The largest amout of rainfall was: " + max +
"inches in month" + (maxind + 1));
return max;
}
public double getLeastRain()
{
double smallest = Double.MAX_VALUE;
int smallind = 0;
for(int n = 0; n < 12; n++)
{
if (rain[n] < smallest)
{
smallest = rain[n];
smallind = n;
}
}
System.out.println("The smallest amout of rainfall was" + smallest +
"inches in month " + (smallind + 1));
return smallest;
}
}
//DriverClass
public class RainfallDriver {
public static void main(String[] args) {
double[] list = {1.6 , 2.1, 1.7, 3.9, 3.7, 3.9, 2.9, 4.3, 2.4, 3.7};
//Counts the total and average from the elements in the array
double total = 0;
double average =0;
for (double element : list)
total += element;
average = total/12;
System.out.println("Total: " + total);
System.out.println("Smallest: " +rain.getLeastRain()); //How can I call the method?
System.out.println("Largest: " + rain.getMostRain()); //How can I call the method?
System.out.println("Average: " + average);
}
}
這不是一類,它的兩個方法。也沒有''main''。請使用所有相關信息更新您的問題。用語言標記你的問題也會有幫助,這是Java嗎? – aruisdante
@aruisdante我有一堆我想在我的Driver類中調用的方法。在哪裏以及如何創建一個包含12個元素的數組,以便我可以從主類中調用方法..對不起,我的代碼太雜亂了......我已經在這個相當長一段時間了這讓我瘋狂! – misheekoh
@misheekoh:Re:「對不起,我的代碼太混亂了」:你不需要道歉。只是把它清理乾淨,沒有人會在意它過去是混亂的。 – ruakh