如何在循环中的一个字符串中存储多个字符串变量输入(JAVA)

最后发布: 2019-03-05 21:04:53


问题

我是Java的初学者

这是我的代码

        while (true) {
        System.out.println("Choose the number");
        System.out.println("1");
        System.out.println("2");
        System.out.println("3");
        System.out.println("4 for Display summary and Exit");

        int cho = input.nextInt();

        System.out.println("Registration");

        System.out.println("Enter your full name (first and lastname)");
        String name = input.next();

        System.out.println("Enter your National ID");
        int id = input.nextInt();

        System.out.println("Enter your phone number");
        int phone = input.nextInt();

我对所有选择1,2,3,4作了if陈述

这是第4个if语句

            else if (cho == 4) {
            System.out.println("Summary");
        }

我想在此循环中,如果主菜单中的用户Choice 4打印了所有选择1,2,3的已注册用户(姓名,电话,ID)的摘要,即使该用户进行了多个注册,然后退出程序。

java string loops if-statement
回答

您应该使用诸如Person类的类在每个循环中存储每个人,例如

class Person{
    String name;
    int id, phone;
    // Constructor with the 3 attributes
    // toString() method implemented
}

并在使用时问问4打印所有清单

List<Person> peoples = new ArrayList<>()
while (true) {
    System.out.println("Choose the number\n1\n2\n3\n4 for Display summary and Exit");
    int cho = input.nextInt();

    System.out.println("Registration");

    System.out.println("Enter your full name (first and lastname)");
    String name = input.next();

    System.out.println("Enter your National ID");
    int id = input.nextInt();

    System.out.println("Enter your phone number");
    int phone = input.nextInt();

    Person p = new Person(name, id, phone);
    peoples.add(p)
    //...
    if( cho == 4){
        peoples.forEach(System.out::println);
        break;
    }
}