Search code examples
javaclassmethodscall

How do I call the following method in Java?


In my program I'm trying to call a method called readData which will read a file called carbon.data. What it will do is take all the values in that file and put it in an array. I'm just not sure how to call the ReadData method. Here's the code:

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;
    }
}

This code is part of a class called CO2Data. Here's the code for the class:

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;
    }

Solution

  • Try to call it in your main and print it out -

    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());
                    }
                }
            }