0

我是新手。我知道我的代码很乱。我将努力添加评论等。

    try // get customer's address
    {
    System.out.println("\nPlease type in your shipping address.");
    System.out.println ("This way you can receive what you have ordered.");
    System.out.println ("In this format: Street, City, State, Zipcode\n");
    customerAddress = input.nextLine();
    }
    catch (Exception e)
            {
                System.out.println("You need to enter in an address.");
            }

    try // get customer's telephone number
    {
        System.out.println("Please enter in your telephone number:\n");
        phoneNumber = input.nextLine();
    }
    catch (Exception e)
    {
        System.out.println("You need to enter in a phone number.");
    }

我能够从 phoneNumber 获取输入,但程序似乎直接跳过了 customerAddress 输入。

以下是我在命令提示符中得到的内容。请注意,我可以在电话号码下输入数据,但没有机会将其放入地址部分。

请输入您的收货地址。
这样您就可以收到您订购的商品。
采用这种格式:街道、城市、州、邮政编码

请输入您的电话号码:

123457890

是否有任何可能导致它跳过的逻辑错误?

4

2 回答 2

0

您的帖子中未显示的任何其他内容都可能导致在缓冲区中保留一条杂散的新行。一个更健壮的选项是在 nextLine 返回一个空字符串时循环。

于 2013-08-08T02:30:08.970 回答
0

如果您正在读取更多数据,那么使用 Scanerinput.nextInt();将只读取一个 int。一种解决方案是添加input.nextLine();,它应该可以工作。

解决方案2:

采用BufferedReader;

        BufferedReader bufferRead = new BufferedReader(new InputStreamReader(System.in));

        try{
            System.out.println("\nPlease type in your shipping address.");
            System.out.println ("This way you can receive what you have ordered.");
            System.out.println ("In this format: Street, City, State, Zipcode\n");

            customerAddress = bufferRead.readLine();
        }catch (Exception e){
            System.out.println("You need to enter in an address.");
        }

        try {
             System.out.println("Please enter in your telephone number:\n");
             phoneNumber =  bufferRead.readLine();
        }catch (Exception e){
             System.out.println("You need to enter in a phone number.");
        }  


        System.out.println(customerAddress + " " + phoneNumber);

查看是否使用 BufferedReader 获得输出。

希望这可以帮助。

于 2013-08-08T02:33:30.103 回答