陷入循环?
Getting stuck in a loop?
我正在为一个项目制作一个银行机器代码,但每当您登录时都会出错。执行此操作的代码部分是这样的:
if(pincheck == pin){
loggedin = true;
pincheck = 0;
do{
System.out.println("Welcome, " + name);
System.out.println("");
System.out.println("Your account balance is $" + balance);
System.out.println("");
System.out.println("Press 1 to deposit funds");
System.out.println("Press 2 to withdraw funds");
System.out.println("Press 3 to log out");
System.out.println("");
options = in.nextInt();
switch (options) {
case 1: System.out.println("How much would you like to deposit?"); // deposit
deposit = in.nextFloat();
balance = balance + deposit;
deposit = 0;
System.out.println("You have deposited funds into your account."); // withdraw
System.out.println("");
break;
case 2: System.out.println("How much would you like to withdraw?");
withdraw = in.nextFloat();
balance = balance - withdraw;
withdraw = 0;
System.out.println("You have removed funds from your account.");
System.out.println("");
break;
case 3: System.out.println("Logging out..."); // log out
System.out.println("");
loggedin = false;
break;
default:System.out.println("Please enter a valid number"); // Invalid number
break;
}
}while(loggedin = true);
发生的事情是登录,你需要输入一个数字,作为 pincheck,如果它等于现有的 pin,它会让你登录。我可以登录但是当我按 3 登录时out,它打印 logging out,然后打印 welcome,然后整个事情又开始了。谁能指出我卡在哪里?
=
是一个赋值运算符,因此您只是简单地赋值(即设置 loggedin=true
),它将始终为 true
(因为您设置为 true
).
因此,您没有检查循环中的实际条件,因此您需要更正 while
条件,如下所示,它使用 ==
运算符(用于计算条件表达式):
while(loggedin == true); //use == for condition evaluation
我正在为一个项目制作一个银行机器代码,但每当您登录时都会出错。执行此操作的代码部分是这样的:
if(pincheck == pin){
loggedin = true;
pincheck = 0;
do{
System.out.println("Welcome, " + name);
System.out.println("");
System.out.println("Your account balance is $" + balance);
System.out.println("");
System.out.println("Press 1 to deposit funds");
System.out.println("Press 2 to withdraw funds");
System.out.println("Press 3 to log out");
System.out.println("");
options = in.nextInt();
switch (options) {
case 1: System.out.println("How much would you like to deposit?"); // deposit
deposit = in.nextFloat();
balance = balance + deposit;
deposit = 0;
System.out.println("You have deposited funds into your account."); // withdraw
System.out.println("");
break;
case 2: System.out.println("How much would you like to withdraw?");
withdraw = in.nextFloat();
balance = balance - withdraw;
withdraw = 0;
System.out.println("You have removed funds from your account.");
System.out.println("");
break;
case 3: System.out.println("Logging out..."); // log out
System.out.println("");
loggedin = false;
break;
default:System.out.println("Please enter a valid number"); // Invalid number
break;
}
}while(loggedin = true);
发生的事情是登录,你需要输入一个数字,作为 pincheck,如果它等于现有的 pin,它会让你登录。我可以登录但是当我按 3 登录时out,它打印 logging out,然后打印 welcome,然后整个事情又开始了。谁能指出我卡在哪里?
=
是一个赋值运算符,因此您只是简单地赋值(即设置 loggedin=true
),它将始终为 true
(因为您设置为 true
).
因此,您没有检查循环中的实际条件,因此您需要更正 while
条件,如下所示,它使用 ==
运算符(用于计算条件表达式):
while(loggedin == true); //use == for condition evaluation