只是想知道你是否可以帮助解决这个问题。代码和输出在下面提供。
do {
System.out.println("would you kindly enter your age?");
while (!sc.hasNext("[0-9]+")) {
System.out.println("Please only use numbers.");
sc.nextLine();
}
age = sc.nextByte();
if (age >= 18) {
System.out.println(""+age);}
else if (age <= 17) {
System.out.println("You must be 18 or older to rent a car if you input an incorrect age please try again otherwise close this page.");
}
} while (age <= 17);
System.out.println("Would you kindly enter the first line of your address?");
address1 = sc.nextLine();
System.out.println("Would you kindly enter the second line of your address?");
address2 = sc.nextLine();
System.out.println("Would you kindly enter the third line of your address");
address3 = sc.nextLine();
sc.close();
输出:
请您输入您的姓名吗? 米
你愿意进入你的年龄吗? 122个
请问您输入地址的第一行吗? 请问您输入地址的第二行?
1
您能否进入地址的第三行? 1
答案 0 :(得分:1)
这是因为Scanner.nextInt方法没有捕获输入的最后一个换行符(在数字之后,例如'5 \ n'),并且在调用Scanner.nextLine()时,换行符被加载到String中。
答案 1 :(得分:0)
在每个地址下将nextline更改为next next似乎解决了这个问题,不知道为什么会有效。
也感谢你帮助汤姆。
答案 2 :(得分:0)
尝试这样的事情:
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Continue? [Y/N]:");
while (sc.hasNext() && (sc.nextLine().equalsIgnoreCase("y"))) {
System.out.print("Would you kindly enter your age?");
int age = sc.nextInt();
sc.nextLine(); // To consume the left over newline;
String address1, address2, address3;
if (age >= 18) {
System.out.println("Since you are " + age + " you are old enough to rent a car");
System.out.println("Would you kindly enter the first line of your address?");
address1 = sc.nextLine();
System.out.println("Would you kindly enter the second line of your address?");
address2 = sc.nextLine();
System.out.println("Would you kindly enter the third line of your address");
address3 = sc.nextLine();
} else if (age <= 17) {
System.out.println("You must be 18 or older to rent a car if you input an incorrect age please try again otherwise close this page.");
}
System.out.print("Continue? [Y/N]:");
}
}
}