Elanthirian
Elanthirian

Reputation: 11

My Java program Terminate unexpectedly

i've created one program like twitter. here is part of my program.

public static void main(String[] args) {
    while (true) {Scanner a = new Scanner(System.in);
        System.out.println("1.Login\t2.Sign Up\t0.Close");
        int choice = 0;
        choice = a.nextInt();
        User user = new User();
        Tweets tweets = new Tweets(uSname);
        Account accounts = new Account();
        switch (choice) {
        case 1:
                Scanner b = new Scanner(System.in);
                System.out.println("Enter UserName:");
                uSname = b.nextLine();

                Scanner c = new Scanner(System.in);
                System.out.println("Enter Your Password:");
                Cpassword = c.nextLine();


            accounts.login(uSname, Cpassword);
            Tweets t = new Tweets(uSname);
            accounts.follow();
            //t.display();

            break;
        case 2:
            try {
                signup();
            } catch (Exception e) {
                System.out.println(e);
            }

        }
        break;
    }
}

if case 1 is executed Scanner getting input in a fracture of seconds it will terminated unexpectedly without showing any error, it didn't call login function! How do solve this, i am beginner.

Upvotes: 0

Views: 373

Answers (2)

JamesB
JamesB

Reputation: 7894

I think your problem is a combination of the following:

  • Using multiple Scanner instances
  • The nextInt() method only reads an int and not the rest of the line. You need to add a readLine() after each call to nextInt().
  • As pointed out by pL4Gu33, your second break needs to be moved inside case 2

Try this code instead.

while (true) {
    Scanner scanner = new Scanner(System.in);
    System.out.println("1.Login\t2.Sign Up\t0.Close");
    int choice = 0;
    choice = scanner.nextInt();
    scanner.nextLine();
    User user = new User();
    Tweets tweets = new Tweets(uSname);
    Account accounts = new Account();
    switch (choice) {
    case 1:
        System.out.println("Enter UserName:");
        uSname = scanner.nextLine();
        System.out.println("Enter Your Password:");
        Cpassword = scanner.nextLine();
        accounts.login(uSname, Cpassword);
        Tweets t = new Tweets(uSname);
        accounts.follow();
        //t.display();
        break;
    case 2:
        try {
            signup();
        } catch (Exception e) {
            System.out.println(e);
        }
        break;
    }

}

Upvotes: 3

pL4Gu33
pL4Gu33

Reputation: 2085

Your second break; is terminate your loop. Set it over the bracket, because its only for case 2.

Upvotes: 1

Related Questions