我的程序应要求用户输入一些值,并根据选择的菜单选项(在我的情况下为3),应正确打印出这些值。我曾经System.out.println("Your name: " + name);
打印出用户插入的姓名,但不幸的是它无法打印出姓名。该行只是留空。为什么这样?我该如何解决。
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int userChoose;
String name = null;
int accNum = 0;
double initiateAmount = 0;
double newAmm = 0;
double depOrWith = 0;
System.out.println("WELCOME TO OUR BANK!\n\n"
+ "...................\n"
+ "...................\n\n"
+ "Choose your optiin:\n"
+ "1. Create new account\n"
+ "2. Deposit/withdraw\n"
+ "3. View details\n"
+ "4. Deleting an account\n"//not used yet
+ "5. View all the accounts\n"//not used yet
+ "6. Quit\n\n");
System.out.println("*************\n"
+ "************");
while (true) {
userChoose = sc.nextInt();
if (userChoose == 1) {
System.out.println("Enter your full name:");
name = sc.nextLine();
sc.nextLine();
System.out.println("Choose an account number:");
accNum = sc.nextInt();
System.out.println("Enter an initiating amount:");
initiateAmount = sc.nextDouble();
System.out.println("\n-----------\n"
+ "------------");
} else if (userChoose == 2) {
System.out.println("Enter negative value to withdraw and positive to deposit");
depOrWith = sc.nextInt();
if (depOrWith < 0) {
initiateAmount = initiateAmount + depOrWith;
} else {
initiateAmount = initiateAmount + depOrWith;
}
System.out.println("\n-----------\n"
+ "------------");
} else if (userChoose == 3) {
System.out.println("Your name: " + name);
System.out.println("Your account number: " + accNum);
System.out.println("Your current balance: " + initiateAmount);
System.out.println("\n-----------\n"
+ "------------");
} else if (userChoose == 6) {
System.exit(0);
}
}
}
选择选项并按Enter后,Scanner
不会读取换行符。之后,当name = sc.nextLine();
调用时,它将仅读取所选选项之后的新行,name
并将被分配一个空字符串。要解决此问题,只需nextLine
在读取所选选项后添加一个呼叫,并nextLine
在读取名称时删除重复项即可:
while (true) {
userChoose = sc.nextInt();
sc.nextLine();
if (userChoose == 1) {
System.out.println("Enter your full name:");
name = sc.nextLine();
System.out.println("Choose an account number:");
...
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句