简体   繁体   中英

How to add in a read object to an ArrayList and print out user requested info

For class, we have to read in a CSV file that has states, their abbreviations, and population and add the objects to an array list. then we have to print out the list in a tabular format. From there we have to ask the user what abbreviation they are looking for and print the abbreviation, state, and population out.

I have already tried adding the objects to an array list how my professor showed me and it broke the whole program. From what I have it set up as now is the closest thing that i've gotten to from the assignment description. We have never used array lists before so you'll have to forgive me if im missing something obvious. I have tried adding for loops in different places to see if it would work and it has not so far. Im lost on how to find specific items in the data and pull them out also.

import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;


class Reader {
    public static void main(String[] args) {
        String abbreviation = "";
        String nameOfState = "";
        int population = 0;

        Scanner inFile = null;

        // open file
        try {
            inFile = new Scanner(new File("States.txt"));
        } catch (FileNotFoundException e) {
            System.out.println("Error: File not found");
        }

        // read file
        System.out.printf("%-12s %5s %5s\n", "Abbreviation", "State Name",
                "Pop");
        System.out.printf("%-12s %5s %5s\n", "------------", "----------",
                "---");
        while (inFile.hasNext()) {
            String record = inFile.nextLine();        // read up to new line
            String[] tokens = record.split(",[ ]*");

            abbreviation = tokens[0];
            nameOfState = tokens[1];
            population = Integer.parseInt(tokens[2]);

            System.out.printf("%-12s %5s %12d\n", abbreviation, nameOfState,
                    population);

        }
        Scanner in = new Scanner(System.in);
        System.out.println("Which state would you like to find?");
        String question = in.nextLine();
        for (int i = 0; i < abbreviation.length(); i++) {

            if (question.equalsIgnoreCase(abbreviation)) {

            } else {
                System.out.println("Incorrect formating");
            }

        }
        inFile.close();

    }
}

--

public class States {
    private String abbreviation;
    private String nameOfState;
    private int population;

    public States(String abbreviation, String nameOfState, int population) {
        super();
        this.abbreviation = abbreviation;
        this.nameOfState = nameOfState;
        this.population = population;
    }

    public String getAbbreviation() {
        return abbreviation;
    }

    public String getNameOfState() {
        return nameOfState;
    }

    public int getPopulation() {
        return population;
    }
}

First let's cal the class State and not States it has no sense

Then you need to

  • declare a new array list List<State> stateList = new ArrayList<>();
  • for each line create a State instance, and add it to the list
List<State> stateList = new ArrayList<>();
while (inFile.hasNext()) {
    String record = inFile.nextLine();        // read up to new line
    String[] tokens = record.split(",[ ]*");

    String abbreviation = tokens[0];
    String nameOfState = tokens[1];
    int population = Integer.parseInt(tokens[2]);

    stateList.add(new State(abbreviation, nameOfState, population));
}

Then iterate over each State in the list, and if the abbrevation matches the user input : print it

Scanner in = new Scanner(System.in);
System.out.println("Which state would you like to find?");
String question = in.nextLine();
for (State state : stateList) {
    if (question.equalsIgnoreCase(state.getAbbreviation())) {
        System.out.println(state);
    }
}

And in State class

@Override
public String toString() {
    return String.format("%-12s %5s %12d", abbreviation, nameOfState, population);
}

Streamy version for fun

Using a constructor that takes the line directly

public State(String data) {
    String[] tokens = data.split(",\\s*");
    this.abbreviation = tokens[0];
    this.nameOfState = tokens[1];
    this.population = Integer.parseInt(tokens[2]);
}

You could

List<State> stateList = Files.lines(Path.of("States.txt"))
                             .map(State::new)
                             .collect(Collectors.toList());

stateList.stream()
        .filter(state -> state.getAbbreviation().equals(question))
        .forEach(System.out::println);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM