简体   繁体   English

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

[英]how to store more than string variable input in one string from loop (JAVA)

I am semi-beginner in java 我是Java的初学者

This is my code 这是我的代码

        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();

I made if statement for all the choices 1,2,3,4 我对所有选择1,2,3,4作了if陈述

And this is number 4 if statement 这是第4个if语句

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

I want in this loop if user Choice 4 in the main menu prints a summary of all registered users (name, phone, id) that choices 1,2,3, even if the user made more than one register, and then exits the program. 我想在此循环中,如果主菜单中的用户Choice 4打印了所有选择1,2,3的已注册用户(姓名,电话,ID)的摘要,即使该用户进行了多个注册,然后退出程序。

You should use a class like Person to store each person at each round of loop, like 您应该使用诸如Person类的类在每个循环中存储每个人,例如

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

And when use ask for 4 print all the list 并在使用时问问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;
    }
}

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

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