如何生成数据列表然后查询列表?

发布于 2025-02-11 13:31:16 字数 4672 浏览 1 评论 0原文

我是Java的新手,我正在尝试构建一个Java命令行,该程序生成了随机数据集(如GetData()),并在生成的数据集中查询。但是我不知道如何将生成的数据从getData()函数传递到主要函数,以便我可以在生成的数据中找到最古老的人。

public class Data {

    public String first;
    public String last;
    public int age;
    public int id;
    public String country;

    public Data(String first, String last, int age, int id, String country) {
        this.first = first;
        this.last = last;
        this.age = age;
        this.id = id;
        this.country = country;

    }

    public String toString() {
        return "{" +
                " 'firstName': " + first + "," +
                " 'lastName': " + last + "," +
                " 'age': " + age + "," +
                " 'id': " + id + "," +
                " 'country': " + country +
                " }";
    }

    public static ArrayList<Data> getData(int numRows) {
        ArrayList<Data> generator = new ArrayList<>();

        String[] names = {"James", "Matt", "Olivia", "Liam", "Charlotte", "Amelia", "Evelyn", "Taeyeon", "Sooyoung", "Tiffany", "Yoona", "Hayley"};
        String[] lastName = {"Novak", "Forbis", "Corner", "Broadbet", "Kim", "Young", "Hwang", "Choi", "McDonalds", "Kentucky", "Holmes", "Shinichi"};
        String[] country = {"New Zealand", "Vietnam", "Korea", "French", "Japan", "Switzerland", "Italy", "Spain", "Thailand", "Singapore", "Malaysia", "USA"};
        String data = "";
        Random ran = new Random();

        int namesLength = numRows; // passing length to names_len
        int lastNameLength = lastName.length; // passing length to lastname_len
        int countryLength = country.length; // passing length to lastname_len

        for (int i = 0; i < numRows; i++) { // for loop to iterate upto names.length
            int x = ran.nextInt(namesLength); // generating random integer
            int y = ran.nextInt(lastNameLength); // generating random integer
            int z = ran.nextInt(countryLength);
            int a = ran.nextInt(40);
            int exampleId = ran.nextInt(1000);

            // below for loop is to remove that element form names array
            for (int j = x; j < (namesLength - 1); j++) {
                names[j] = names[j + 1]; // this moves elements to one step back
            }
            // below for loop is to remove that element form Lastnames array
            for (int j = y; j < (lastNameLength - 1); j++) {
                lastName[j] = lastName[j + 1]; // this moves elements to one step back
            }

            for (int j = z; j < (countryLength - 1); j++) {
                country[j] = country[j + 1]; // this moves elements to one step back
            }

            namesLength = namesLength - 1; // reducing len of names_len by 1
            lastNameLength = lastNameLength - 1; // reducing len of lastname_len by 1
            countryLength = countryLength - 1; // reducing len of lastname_len by 1

            // Output data in NDJSON format
            data = "{" +
                    " 'firstName': " + names[x] + "," +
                    " 'lastName': " + lastName[y] + "," +
                    " 'age': " + a + "," +
                    " 'id': " + exampleId + "," +
                    " 'country': " + country[z] +
                    " }";
            System.out.println(data);
// How can I add data to the generator list, the generator.add(data) does not work

        }
        // return a list of data
        return generator; 

    }

    public static void main(String[] args) {
        // Generate random data
        int rows = 0;
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter number of rows (maximum 12) you want to generate: ");
        rows = sc.nextInt();
        while (rows >= 13 || rows <= 0) {
            System.out.println("Rows must be in range of 1 and 12");
            System.out.print("Please reenter the number of rows: ");
            rows = sc.nextInt();
        }

        System.out.println("Data is now generated");

        ArrayList<Data> generatedData = getData(rows);


        String[] base_options = {
                "1 - Find the oldest person",
                "2 - Group by country and return count",
                "3 - Choose a country and group by age range",
                "4 - Find the youngest person",
        };
        System.out.println(base_options);


        // Task 2
        // TODO: PASTE GENERATED DATA INTO THIS

        // Find oldest
        Data oldest = generatedData.stream().max((a,b) -> a.age - b.age).get();
        System.out.println(String.format("The oldest person is %s %s", oldest.first, oldest.last));

I am new to Java and I am trying to build a Java command-line program, which generates random dataset (as in getData()) and query into the generated dataset. But I don't know how to pass the generated data from getData() function to the main function so that I can find the oldest person in my generated data.

public class Data {

    public String first;
    public String last;
    public int age;
    public int id;
    public String country;

    public Data(String first, String last, int age, int id, String country) {
        this.first = first;
        this.last = last;
        this.age = age;
        this.id = id;
        this.country = country;

    }

    public String toString() {
        return "{" +
                " 'firstName': " + first + "," +
                " 'lastName': " + last + "," +
                " 'age': " + age + "," +
                " 'id': " + id + "," +
                " 'country': " + country +
                " }";
    }

    public static ArrayList<Data> getData(int numRows) {
        ArrayList<Data> generator = new ArrayList<>();

        String[] names = {"James", "Matt", "Olivia", "Liam", "Charlotte", "Amelia", "Evelyn", "Taeyeon", "Sooyoung", "Tiffany", "Yoona", "Hayley"};
        String[] lastName = {"Novak", "Forbis", "Corner", "Broadbet", "Kim", "Young", "Hwang", "Choi", "McDonalds", "Kentucky", "Holmes", "Shinichi"};
        String[] country = {"New Zealand", "Vietnam", "Korea", "French", "Japan", "Switzerland", "Italy", "Spain", "Thailand", "Singapore", "Malaysia", "USA"};
        String data = "";
        Random ran = new Random();

        int namesLength = numRows; // passing length to names_len
        int lastNameLength = lastName.length; // passing length to lastname_len
        int countryLength = country.length; // passing length to lastname_len

        for (int i = 0; i < numRows; i++) { // for loop to iterate upto names.length
            int x = ran.nextInt(namesLength); // generating random integer
            int y = ran.nextInt(lastNameLength); // generating random integer
            int z = ran.nextInt(countryLength);
            int a = ran.nextInt(40);
            int exampleId = ran.nextInt(1000);

            // below for loop is to remove that element form names array
            for (int j = x; j < (namesLength - 1); j++) {
                names[j] = names[j + 1]; // this moves elements to one step back
            }
            // below for loop is to remove that element form Lastnames array
            for (int j = y; j < (lastNameLength - 1); j++) {
                lastName[j] = lastName[j + 1]; // this moves elements to one step back
            }

            for (int j = z; j < (countryLength - 1); j++) {
                country[j] = country[j + 1]; // this moves elements to one step back
            }

            namesLength = namesLength - 1; // reducing len of names_len by 1
            lastNameLength = lastNameLength - 1; // reducing len of lastname_len by 1
            countryLength = countryLength - 1; // reducing len of lastname_len by 1

            // Output data in NDJSON format
            data = "{" +
                    " 'firstName': " + names[x] + "," +
                    " 'lastName': " + lastName[y] + "," +
                    " 'age': " + a + "," +
                    " 'id': " + exampleId + "," +
                    " 'country': " + country[z] +
                    " }";
            System.out.println(data);
// How can I add data to the generator list, the generator.add(data) does not work

        }
        // return a list of data
        return generator; 

    }

    public static void main(String[] args) {
        // Generate random data
        int rows = 0;
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter number of rows (maximum 12) you want to generate: ");
        rows = sc.nextInt();
        while (rows >= 13 || rows <= 0) {
            System.out.println("Rows must be in range of 1 and 12");
            System.out.print("Please reenter the number of rows: ");
            rows = sc.nextInt();
        }

        System.out.println("Data is now generated");

        ArrayList<Data> generatedData = getData(rows);


        String[] base_options = {
                "1 - Find the oldest person",
                "2 - Group by country and return count",
                "3 - Choose a country and group by age range",
                "4 - Find the youngest person",
        };
        System.out.println(base_options);


        // Task 2
        // TODO: PASTE GENERATED DATA INTO THIS

        // Find oldest
        Data oldest = generatedData.stream().max((a,b) -> a.age - b.age).get();
        System.out.println(String.format("The oldest person is %s %s", oldest.first, oldest.last));

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

咋地 2025-02-18 13:31:16

generator.add(新数据(名称[x],lastName [y],a,exampleId,country [z]));对我有用

generator.add(new Data(names[x], lastName[y], a, exampleId, country[z])); works for me just fine

破晓 2025-02-18 13:31:16

您可以将字符串中生成的数据解析为data,并以这样的方式获取最大valud:

public static void main(String[] args) {
    // Generate random data
    int rows = 0;
    Scanner sc = new Scanner(System.in);
    System.out.print("Enter number of rows (maximum 12) you want to generate: ");
    rows = sc.nextInt();
    while (rows >= 13 || rows <= 0) {
        System.out.println("Rows must be in range of 1 and 12");
        System.out.print("Please reenter the number of rows: ");
        rows = sc.nextInt();
    }

    System.out.println("Data is now generated");

    ArrayList<String> generatedData = getData(rows);
    // Find oldest
    Data oldest = generatedData
        .stream()
        .map(it -> extractData(it))
        .max(Comparator.comparingInt(a -> a.age))
        .get();
    System.out.println(String.format("The oldest person is %s %s", oldest.first, oldest.last));
}

private static Data extractData(String str) {
    return new Data(
        extractProperty(str, "firstName"),
        extractProperty(str, "lastName"),
        Integer.parseInt(extractProperty(str, "age")),
        Integer.parseInt(extractProperty(str, "id")),
        extractProperty(str, "country")
    );
}

private static String extractProperty(String str, String keyName) {
    String key = "'" + keyName + "': ";
    int startIndex = str.indexOf(key) + key.length();
    if (startIndex < 0) {
        return "";
    }
    StringBuilder value = new StringBuilder();
    for (int i = startIndex ; i < str.length() ; ++i) {
        char ch = str.charAt(i);
        if (ch == ',') {
            break;
        }
        value.append(ch);
    }
    return value.toString();
}

You can parse your generated data in string to Data and get the max valud like this:

public static void main(String[] args) {
    // Generate random data
    int rows = 0;
    Scanner sc = new Scanner(System.in);
    System.out.print("Enter number of rows (maximum 12) you want to generate: ");
    rows = sc.nextInt();
    while (rows >= 13 || rows <= 0) {
        System.out.println("Rows must be in range of 1 and 12");
        System.out.print("Please reenter the number of rows: ");
        rows = sc.nextInt();
    }

    System.out.println("Data is now generated");

    ArrayList<String> generatedData = getData(rows);
    // Find oldest
    Data oldest = generatedData
        .stream()
        .map(it -> extractData(it))
        .max(Comparator.comparingInt(a -> a.age))
        .get();
    System.out.println(String.format("The oldest person is %s %s", oldest.first, oldest.last));
}

private static Data extractData(String str) {
    return new Data(
        extractProperty(str, "firstName"),
        extractProperty(str, "lastName"),
        Integer.parseInt(extractProperty(str, "age")),
        Integer.parseInt(extractProperty(str, "id")),
        extractProperty(str, "country")
    );
}

private static String extractProperty(String str, String keyName) {
    String key = "'" + keyName + "': ";
    int startIndex = str.indexOf(key) + key.length();
    if (startIndex < 0) {
        return "";
    }
    StringBuilder value = new StringBuilder();
    for (int i = startIndex ; i < str.length() ; ++i) {
        char ch = str.charAt(i);
        if (ch == ',') {
            break;
        }
        value.append(ch);
    }
    return value.toString();
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文