Drk*_*ibs 0 java if-statement while-loop nested-loops
这是我正在使用的代码。此处引用的其他类已经过测试并且可以正常工作,但它们不应影响此处语句的功能。
import java.util.Scanner;
public class TransferTest
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
double transferAmount;
Account acct1 = new Account(100, null);
Account acct2 = new Account(100, null);
System.out.print("Choose an option: "
+ "\n1 <Enter>: to transfer from account 1 to account 2"
+ "\n2 <Enter>: to transfer from account 2 to account 1"
+ "\n3 <Enter>: to quit");
int userOption = scan.nextInt();
scan.nextLine();
while(userOption != 3);
{
if (userOption == 1)
{
System.out.print("You chose transfer from account 1 to account 2"
+ "\nEnter an amount to transfer: ");
transferAmount = scan.nextInt();
acct1.transfer(acct2, transferAmount);
}
else if (userOption == 2)
{
System.out.print("You chose transfer from account 1 to account 2"
+ "\nEnter an amount to transfer: ");
transferAmount = scan.nextInt();
acct2.transfer(acct1, transferAmount);
}
else if (userOption == 3)
{
System.out.println(acct1.toString());
System.out.println(acct2.toString());
}
else
{
System.out.println("Invalid input");
}
System.out.print("Choose an option: "
+ "\n1 <Enter> to transfer from account 1 to account 2?"
+ "\n2 <Enter> to transfer from account 2 to account 1"
+ "\n3 <Enter> to quit");
userOption = scan.nextInt();
scan.nextLine();
}
System.out.println(acct1.toString());
System.out.println(acct2.toString());
scan.close();
}
}
Run Code Online (Sandbox Code Playgroud)
我想要做的是提示用户选择由数值表示的三个选项之一。然后跟随那个值的 if 分支,在 1 或 2 的情况下向用户询问一个数量。在用户选择选项 3 之前不退出 while 循环。发生的事情是当输入 3 或指定范围之外的值时the program works as expected, but when 1 or 2 are chosen as options nothing happens, not even the print statements are output. 非常感谢您对这项工作的任何帮助。
你的 while 循环后有一个分号。
while(userOption != 3);
Run Code Online (Sandbox Code Playgroud)
实际上等于:
while(userOption != 3) {
// do nothing
}
Run Code Online (Sandbox Code Playgroud)
所以在该行之后没有代码被执行。