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

时间:2019-03-05 21:04:54

标签: java string loops if-statement

我是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");
        }

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

1 个答案:

答案 0 :(得分:1)

您应使用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;
    }
}