在我的程序中,我正在尝试调用一个名为readData的方法,该方法将读取一个名为carbon.data的文件。它将做的是获取该文件中的所有值并将其放入数组中。我只是不确定如何调用ReadData方法。这是代码:
import java.io.*;
import java.util.*;
public class Report{
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
String filename = scanner.next();
Scanner input = readFile(filename);
}
public static Scanner readFile(String filename){
File input = new File(filename);
Scanner sc = null;
try{
sc = new Scanner(input);
}
catch(FileNotFoundException e){
System.out.println("Filename not valid");
System.exit(-1);
}
return sc;
}
public static CO2Data[] readData(String filename){
File input = new File(filename);
Scanner sc = null;
try{
sc = new Scanner(input);
}
catch(FileNotFoundException e){
System.out.println("Filename not valid");
System.exit(-1);
}
String info = sc.nextLine();
int total = sc.nextInt();
CO2Data[] arr = new CO2Data[total];
for(int i=0; i<10;i++){
arr[i] = new CO2Data();
}
for(int i=0; i<10;i++){
arr[i].setCountry(sc.next());
arr[i].setTotalCO2(sc.nextDouble());
}
return arr;
}
}
此代码是名为CO2Data的类的一部分。这是该类的代码:
public class CO2Data {
private String country;
private double totalCO2;
public CO2Data() {
country = "";
totalCO2 = 0;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public double getTotalCO2() {
return totalCO2;
}
public void setTotalCO2(double totalCO2) {
this.totalCO2 = totalCO2;
}
答案 0 :(得分:0)
由于readData是静态的,你可以将其称为Report.readData(&#34; blah&#34;);
答案 1 :(得分:0)
尝试在主打电话中将其打印出来 -
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
String filename = scanner.next();
CO2Data[] aDataArray = null
aDataArray = readData(filename);
if(aDataArray != null) {
for(int i = 0; i < aDataArray.length; i++) {
System.out.println("Country:" + aDataArray[i].getCountry());
System.out.println("CO2 Level:" + aDataArray[i].getTotalCO2());
}
}
}
答案 2 :(得分:0)
如果从Report类中调用它,你可以写
CO2Data[] data = readData(filename);
如果你想从另一个类调用它,你必须在方法名前加上类名(因为它是一个静态方法)
CO2Data[] data = Report.readData(filename);