创建主要方法时遇到问题

时间:2014-08-06 22:09:13

标签: java

我无法创建可以正确演示此类的主方法。构造函数的参数必须采用MMYYYY形式。构造函数应读取2013年6月的两个文件的内容(highs062013.txt和lows062013.txt),并将值存储在两个整数数组中。这些文件包含相同数量的数据。还有获得最高和最低温度的方法,以及高平均值和低平均值。

import java.io.*;
public class Weather
{
public Weather(int date) throws FileNotFoundException, IOException
{
    String dateLow = ("lows" + date + ".txt");
    String dateHigh = ("highs" + date + ".txt");
    File low = new File(dateLow);
    File high = new File(dateHigh);
    FileReader frLow=new FileReader(dateLow);
    FileReader frHigh = new FileReader(dateHigh);
    char[] cLow = new char[(int)dateLow.length()];
    char[] cHigh = new char[(int)dateHigh.length()];
    frLow.read(cLow);
    frHigh.read(cHigh);
}
public char lowest(char[] cLow)
{
    char small = cLow[0];
    for (int i = 0; i < cLow.length; i++)
    {
        if (cLow[i] < small)
        {
            small = cLow[i];
        }
    }
    System.out.println(small + " is the lowest temp.");
    return small;
}
public char highest(char[] cHigh)
{
    char high = cHigh[0];
    for (int i = 0; i < cHigh.length; i++)
    {
        if (cHigh[i] > high)
        {
            high = cHigh[i];
        }
    }
    System.out.println(high + " is the highest temp.");
    return high;
}
public int averageLow(char[] cLow)
{
    int sum = 0;
    int averageLow;
    for(int i=0; i < cLow.length; i++)
    {
        sum = sum + cLow[i];
    }
    averageLow = sum/cLow.length;
    return averageLow;
    System.out.println(averageLow + " is the average low temp.");
}
public int averageHigh(char[] cHigh)
{
    int sum = 0;
    int averageHigh;
    for(int i=0; i < cHigh.length; i++)
    {
        sum = sum + cHigh[i];
    }
    averageHigh = sum/cHigh.length;
    System.out.println(averageHigh + " is the average high temp.");
    return averageHigh;
}
}

我需要创建一个可以演示我的代码的驱动程序方法,这就是我遇到的问题。

2 个答案:

答案 0 :(得分:1)

您需要创建一个与正确签名对应的main方法并实例化您的类。所以像这样:

public static void main(String[] args) {
   Weather weather = new Weather(<the date you want goes here);
}

答案 1 :(得分:0)

回答评论中的问题,您可以做两件事:

1.在构造函数的末尾调用方法。调用方法时,它们中包含的程序语句将执行。

public Weather(int date) throws FileNotFoundException, IOException
{
    // code here
    lowest(/*char array variable goes here*/);
    highest(/*char array variable goes here*/);
    // etc.
}

public static void main(String[] args)
{
    new Weather(/*int value goes here*/);
}

2.将变量设为全局变量,以便类中的所有方法都可以访问它们。

public class Weather
{
    private char[] cLow;
    private char[] cHigh;

    public Weather(int date) throws FileNotFoundException, IOException
    {
        // code here
        cLow = new char[(int)dateLow.length()];
        cHigh = new char[(int)dateHigh.length()];
        // code here
    }

    public static void main(String[] args)
    {
        Weather weather = new Weather(/*int value goes here*/);
        weather.lowest(/*char array variable goes here*/);
        weather.highest(/*char array variable goes here*/);
        // etc.
    }
}