gpt4 book ai didi

java - 应用 do while 循环

转载 作者:行者123 更新时间:2023-11-30 07:24:50 32 4
gpt4 key购买 nike

我的代码目前无法在程序的开头启动,即“请输入...”。我希望代码能够在每次执行选择 1 或 2 时返回到起始语句。 while 语句不满足这一点,因为我无法在声明“choice”之前使用 while 语句。我知道我应该使用 do while 循环,但每次我尝试实现它时 - 它都会给我一个带有大括号的错误。

以下是我的代码片段:

    System.out.println("Please type in 1 for a customer to view their portfolio, 2 to trade stocks or 3 to exit the application");
int choice = Integer.parseInt(input.nextLine());
{
while (!"3".equals(choice));
{
if (choice == 1) {
System.out.println(mycustomers[menuchoice].toString());
return;
}
if (choice == 2) {
String StockSelect = "Please select a stock";
for (int i = 0; i < mystocks.length; i++) {
// [i] is the element we are accessing
StockSelect += " " + i + " " + (mystocks[i].getSymbol());
}

System.out.println(StockSelect);

int stockchoice = Integer.parseInt(input.nextLine());

System.out.println("Select 1 to buy or 2 to sell?");
int choice2 = Integer.parseInt(input.nextLine());

if (choice2 == 1) {
System.out.println("How many stocks would you like to buy ");
int volumebought = Integer.parseInt(input.nextLine());
for (int i = 0; i < numofstocks; i++) {
mycustomers[menuchoice].setBalance(
mycustomers[menuchoice].getBalance() - (volumebought * mystocks[i].getprice()));
mycustomers[menuchoice].setPortfolio();
}
System.out.println(mycustomers[menuchoice].toString());
return;
}
if (choice2 == 2) {
System.out.println("How much stocks would you like to sell ");
int volumesold = Integer.parseInt(input.nextLine());
for (int i = 0; i < numofstocks; i++) {
mycustomers[menuchoice].setBalance(
mycustomers[menuchoice].getBalance() + (volumesold * mystocks[i].getprice()));
mycustomers[menuchoice].setPortfolio();
}
System.out.println(mycustomers[menuchoice].toString());
return;
}

}
if (choice == 3) // how to exit application
{
System.out.println("Thank you for using the application");
System.out.println("The current state of all customers are:");
for (int i = 0; i < mycustomers.length; i++) {
System.out.println(mycustomers[i].toString());
}
System.out.println("The current state of all stocks are:");
for (int i = 0; i < mystocks.length; i++) {
System.out.println(mystocks[i].toString());
}
System.exit(0);
}

}

}}}

如何实现 do-while 循环,以便每次执行代码后都返回到初始语句 - 只要输入不是 3?

最佳答案

在 while 循环内请求输入,如下所示:

choice = Integer.parseInt(input.nextLine());

关于java - 应用 do while 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36960884/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com