简体   繁体   English

我的Java程序意外终止

[英]My Java program Terminate unexpectedly

i've created one program like twitter. 我已经创建了一个像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! 如果执行了案例1,扫描仪在几秒钟的时间内获得输入,它将意外终止而不会显示任何错误,它没有调用登录功能! How do solve this, i am beginner. 我是初学者,如何解决这个问题。

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. nextInt()方法仅读取一个int,而不读取其余的行。 You need to add a readLine() after each call to nextInt(). 您需要在每次调用nextInt()之后添加一个readLine()。
  • As pointed out by pL4Gu33, your second break needs to be moved inside case 2 正如pL4Gu33指出的那样,您的第二个休息时间需要移至案例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;
    }

}

Your second break; 你的第二次休息; is terminate your loop. 是终止您的循环。 Set it over the bracket, because its only for case 2. 将其放在支架上,因为仅适用于情况2。

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

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