Rio Ablas
Rio Ablas

Reputation: 51

Do While loop not coordinating with a Scanner the 2nd time

I have a project that I need help with. I'm a beginner in programming, and I don't understand this. I'm hoping to get an answer.

Scanner reg_input = new Scanner(System.in);
    int ctr = 0,item = 1;
    char reg_mn = 'y', choice;
    String[] user = new String[item];
    String[] pass = new String[item];
    reg_mn = 'y';
    do {
        System.out.println("[REGISTER]");
        System.out.println("==========");
        System.out.print("Username: ");
        user[ctr] = reg_input.next(); //Line 11
        System.out.print("Password: ");
        pass[ctr] = reg_input.next();
        System.out.println("==========");

        System.out.println("Do you wish to Continue? [Y/N]");
        choice = reg_input.next().charAt(0);

            if (choice == 'y' || choice =='y') {
                item = item + 1;
            } 
            else if (choice == 'n' || choice == 'N') {
                reg_mn = 'n';
                item = item + 1;
                return;

            }

        ctr++;
    } while (reg_mn == 'y' || reg_mn == 'Y');

the 1st loop is fine. The problem here is when I type "y" to try and get the 2nd loop, I get an error from the scanner at Line 11

Upvotes: 0

Views: 45

Answers (1)

Rohit Suthar
Rohit Suthar

Reputation: 987

Because you have declared a string with the size of an item whose value is 1 initially. So if you increment the item by 1 but the string array size would not be incremented because it is declared with size 1.

String[] user = new String[item];
String[] pass = new String[item];

Change like this

String[] user = new String[30];
String[] pass = new String[30];

You have to declare with some maximum size.

I suggest you use any java Collections for this like HashMap. Because here you are declaring the string array with maximum size so it allocated that size however if you are storing only 2 users remaining size would be waste. For this use Collections.

Upvotes: 1

Related Questions