我是新手。我知道我的代码很乱。我将努力添加评论等。
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
是否存在导致其跳过的逻辑错误?
答案 0 :(得分:0)
您帖子中未显示的任何其他内容可能会导致新的线路残留在缓冲区中。一个更健壮的选项是循环,而nextLine返回一个空字符串。
答案 1 :(得分:0)
如果您正在阅读更多数据,使用Scaner,如input.nextInt();
,那么它只会读取一个int。
一个解决方案是添加input.nextLine();
,它应该可以工作。
使用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获得输出。
希望这有帮助。