Hello! I am learning Java recently. The task is as follows: a person must enter a name, login and password in the console, after which the program should check the login for involvement in a dynamic array and, if it is not there, add it, and if it is, output an error warning.
At startup, an input window opens where the above-mentioned "name", "login" and "password" are quietly entered. However, the program does not check the login for involvement in the array and does not display an error message, as well as it does not display the array fields themselves. I would be grateful for the help!

import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; public class User { public static void main(String[] args) throws IOException { BufferedReader bReader =new BufferedReader(new InputStreamReader(System.in)); String name = bReader.readLine(); String login = bReader.readLine(); String password = bReader.readLine(); UserADD(name,login,password); } public static ArrayList<String> UserADD(String name,String login,String password) { ArrayList <String> users = new ArrayList<String>(); for (int i = 0; i<users.size(); i++) { if (users.contains(login)) { System.out.println("Это имя пользователя уже занято"); } else users.add(name); users.add (login);users.add(password); { System.out.println(users); } } return users; } } 

Thank you all very much, but the problem remained. When the second user tries to enter the login of the first one, the program calmly accepts it, ignoring any restrictions and the warning does not appear on the screen. I tried all the options.

  • one
    Well, every time you create a list of users through ArrayList <String> users = new ArrayList<String>(); . accordingly, it doesn’t run through the loop, because the size is zero ........ plus brackets are not placed as much as else ....... but in general, as for me, it would be necessary to make a list User. and add exactly the user, with all his data. Well, it is IMHO. - Alexey Shimansky
  • Because the list of users must be rendered to the class and made static. Then the values ​​will be stored in the global variable and with each method call everything will work. Plus, it is better to use Set for storing non-repeating values. - I. Perevoz
  • Not an information headline, please reformulate! - t1nk

3 answers 3

First, a very strange piece of code

 else users.add(name); users.add (login);users.add(password); { System.out.println(users); } 

It looks like you started in brackets.

Secondly, the task is to check the login for employment. I see no reason to add a name and password to the list.

Thirdly, you do not need to enumerate the list. Enough conditions

 if(users.contains(login)) { System.out.println("Это имя пользователя уже занято"); } else { users.add(login); } 

Finally, you create an empty list every time you call the UserADD method and you do not save it anywhere. When the method completes, the users variable goes out of scope and the garbage collector deletes it.

    You add "fruit, water and smoke to the Fruit basket". Passwords and names need not be added to the collection that stores logins.

    The users collection must be created in the main method so that it is not initialized every time a new user is added. bring to the main method:

     ArrayList <String> users = new ArrayList<String>(); 

    Then next to it you need to create 2 more collections:

     ArrayList <String> names = new ArrayList<String>(); ArrayList <String> passwords = new ArrayList<String>(); 

    and modify the string:

     else users.add(name); users.add (login);users.add(password); 

    at

     else {names.add(name); users.add(login); passwords.add(password);} 

    In this case, everything will work and you will be able to work with users by their ID.

      Must be something like:

       public class Test { private static Set<String> users; //Предполагаю, что в списке значения хранятся в формате <Имя, Логин, Пароль> public static Set<String> addUser (String name, String login, String password){ //Если множенство не инициализировано, то самое время. if (users==null) users = new HashSet<>(); //Триггер на дубликат boolean b = false; //Проходим итератором, т.к. в будущем, если что можно будет без проблем удалить элемент (если, допустим, будет опция замены) Iterator<String> iterator = users.iterator(); while (iterator.hasNext()){ //Получаем логин (2-й элемент) разбивая строку на кусочки в массив. Разделитель запятая. if (iterator.next().split(",")[1].equals(login)){ b = true; } } //Если все ок, то добавляем if (!b) { users.add(name+","+login+","+password); }else {//Иначе говорим о проблеме и больше ничего не делаем. System.out.println("Такой логин("+login+") уже существует"); } return users; } }