简体   繁体   English

如何将数据文件中的数据加载到数组中并要求用户输入,然后根据用户输入查找和打印数据?

[英]How do I load data from a data file into an Array and ask for user input then find and print the data based off of user input?

I have a project where we have to take a file name zipcodes.txt and load into an array.我有一个项目,我们必须将文件名 zipcodes.txt 加载到数组中。 The files format is like 08001, Alloway, Salem county where each item is on a different line by itself.文件格式类似于 08001, Alloway, Salem 县,其中每个项目单独位于不同的行上。

The goal is to load the data into an array of zip codes.目标是将数据加载到邮政编码数组中。 Print the list of zip codes--including each zip codes, town, and state with the data for each zip on separate line.打印邮政编码列表——包括每个邮政编码、城镇和州,并在单独的行上打印每个邮政编码的数据。 A method that asks the user for zip code, then either displays the data for that zip code or says the zip code was not found in the list.一种向用户询问邮政编码的方法,然后显示该邮政编码的数据或说在列表中找不到该邮政编码。 This is what needs to be done, I am drawing a blank here.这是需要做的,我在这里画一个空白。 Any ideas?有任何想法吗?

Since there has to be a main class, a ziplist class where the array is stored, and a zipcode class where the variables are stored I have managed to load the file into an array and call it in the main method.由于必须有一个主类、一个存储数组的 ziplist 类和一个存储变量的 zipcode 类,因此我设法将文件加载到一个数组中并在 main 方法中调用它。 But I can't seem to figure how to implement user into my code and have like a Boolean condition to compare the input to the data in the file and then print the zip and data for the zip such as township and state.但是我似乎无法弄清楚如何将用户实现到我的代码中,并且像布尔条件一样将输入与文件中的数据进行比较,然后打印 zip 和 zip 的数据,例如城镇和州。

The file is like this文件是这样的

08001
Alloway
Salem County
08002
Cherry Hill
Camden County
08003

With the data on their own.用自己的数据。 like 08001 is on line 1, and Alloway is on line 2.比如 08001 在第 1 行,而 Alloway 在第 2 行。

public class ZipcodesProject {
    //Main method for the Class
    public static void main(String[] args) throws FileNotFoundException {
        boolean isPresent = false;
        Integer index=null;

        Scanner in= new Scanner(System.in);
        while(true){
            System.out.println("Please enter the zip code:");
            String input= in.nextLine();

            ZipList zipcodesObject = new ZipList();
            zipcodesObject.ZipsandProperties(); 
            Integer number = Integer.valueOf(input);

        }
    }
}
    package zipcodesproject;
    import java.io.FileNotFoundException;
    import java.io.File;
    import java.util.Scanner;

    public class ZipList {

        public void ZipsandProperties() throws FileNotFoundException{

        File zipcodes = new File("zipcodes.txt");

           Scanner inFile = new Scanner(zipcodes);
           String[]fileData=new String[4000];
           int count=0;
           while (inFile.hasNextLine()){
               fileData[++count] = inFile.nextLine();
               System.out.println(fileData[count]);
           }
        }
    }
    package zipcodesproject;

    public class ZipCodes {
        int zip;
        String township;
        String state;

        ZipCodes(int z, String tship, String ste) {
            zip = z;
            township = tship;
            state =ste;
        }
    }

Instead making String array named fileData, you may first parse the String that you obtain from file as zip,township and state,then you may create an array with type ZipCodes.您可以先将从文件中获取的字符串解析为 zip、township 和 state,而不是创建名为 fileData 的 String 数组,然后您可以创建一个类型为 ZipCodes 的数组。

public void ZipsandProperties() throws FileNotFoundException{

    File zipcodes = new File("zipcodes.txt");

       Scanner inFile = new Scanner(zipcodes);
       ZipCodes[] fileData= new ZipCodes[4000];
       int count=0;
       while (inFile.hasNextLine()){
           String line = inFile.nextLine();
           String [] temp = line.split(" ");//I assumed that your file content is like "<zip code> <township> <state>"
           ZipCodes zc = new ZipCodes(Integer.parseInt(temp[0]),temp[1],temp[2]));
           fileData[++count] = zc;
       }
    }

Then,you can use this array more flexible than String array.然后,您可以比 String 数组更灵活地使用此数组。 You can iterate it with given input.您可以使用给定的输入对其进行迭代。

i dont know if this is good enough for you, or at least it guides you into a solution you need:我不知道这对你来说是否足够好,或者至少它引导你找到你需要的解决方案:

ZipCodeProject.java:邮政编码项目.java:

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

public class ZipCodeProject {

    public static void main(String[] args) {

        String zipFileNamePath = "path/to/your/file/zipcodes.txt";
        try {
            List<ZipCode> zipCodes = loadZipFile(zipFileNamePath);
            int option = -1;
            Scanner optionScanner = new Scanner(System.in);
            while(option != 4) {

                printMenu();
                option = optionScanner.nextInt();
                switch (option) {
                    case 1:
                        for (ZipCode zipCode : zipCodes) {
                            System.out.println(zipCode.toString());
                        }
                        break;
                    case 2:
                        // logic to find a zip code
                        break;
                    case 3:
                        System.out.println("operation not supported");
                        break;
                    case 4:
                        System.out.println("Byeee");
                        break;
                    default:
                        System.out.println("error, select a number from the menu");
                }
            }

        } catch (FileNotFoundException exception) {
            System.out.println("File not found: " + zipFileNamePath);
        }
    }

    public static void printMenu() {
        System.out.println("Menu");
        System.out.println("1 - Print all zip codes.");
        System.out.println("2 - Find a zip code.");
        System.out.println("3 - Add new zip code.");
        System.out.println("4 - Quit.");
        System.out.println("Select the menu number");
    }

    public static List<ZipCode> loadZipFile(String zipFileName) throws FileNotFoundException {

        File zipFile = new File(zipFileName);
        Scanner inFile = new Scanner(zipFile).useDelimiter("\n");
        List<ZipCode> zipCodes = new ArrayList<>();
        while (inFile.hasNextLine()) {
            String[] zipCodeProperties = new String[3];
            int count = 0;
            while (count < 3) {
                zipCodeProperties[count] = inFile.next();
                count++;
            }
            ZipCode zipCode = new ZipCode(Integer.parseInt(zipCodeProperties[0]), zipCodeProperties[1], zipCodeProperties[2]);
            zipCodes.add(zipCode);
        }
        return zipCodes;
    }

}

ZipCode.java:邮政编码.java:

public class ZipCode {

    private int zip;
    private String town;
    private String state;

    public ZipCode(int zip, String town, String state) {
        this.zip = zip;
        this.town = town;
        this.state = state;
    }

    @Override
    public String toString() {
        return "ZipCode{" +
                "zip=" + zip +
                ", town='" + town + '\'' +
                ", state='" + state + '\'' +
                '}';
    }
}

zipcodes.txt:邮政编码.txt:

08001
Alloway
Salem County
08002
Cherry Hill
Camden County

Execution:执行:

Menu
1 - Print all zip codes.
2 - Find a zip code.
3 - Add new zip code.
4 - Quit.
Select the menu number
1
ZipCode{zip=8001, town='Alloway', state='Salem County'}
ZipCode{zip=8002, town='Cherry Hill', state='Camden County'}
Menu
1 - Print all zip codes.
2 - Find a zip code.
3 - Add new zip code.
4 - Quit.
Select the menu number
4
Byeee

I hope its helpful, any questions, just shoot :)我希望它有帮助,任何问题,就拍:)

ps: going over the response, i noticed zip code is an int, and in your description it starts with a 0, which a leading 0 in an int is removed. ps:查看响应,我注意到邮政编码是一个 int,在您的描述中它以 0 开头,其中删除了 int 中的前导 0。 If you need zip codes to be with leading 0s then you should take that variable as a String, if its just numeric, and leading 0s are not necessary to register, you can leave it as it is :D如果您需要邮政编码前导 0,那么您应该将该变量作为字符串,如果它只是数字,并且不需要注册前导 0,您可以保持原样:D

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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