gpt4 book ai didi

java - 尝试使用带有 'menu' 的 For 循环

转载 作者:行者123 更新时间:2023-12-02 09:53:16 25 4
gpt4 key购买 nike

初学者,请尽可能解释!

类(class)问题要求我创建一个菜单(已完成)。

菜单上有多个选项给出不同的一次性结果(完成)。

现在它要我实现一个 forwhiledo...while 循环(无法理解)

我确实尝试了所有基本知识,包括在 for 循环内创建和填充数组(事后看来这是一个愚蠢的想法)。

public void displayMenu()
{
System.out.println("A. Option #A");
System.out.println("B. Option #B");
System.out.println("C. Option #C");
System.out.println("D. Option #D");
System.out.println("X. Exit!");
System.out.println();
System.out.println("Please enter your choice:");
}

public void start()
{
displayMenu();
Scanner console = new Scanner(System.in);
String input = console.nextLine().toUpperCase();
System.out.println();

switch (input)
{
case "A": System.out.println("Option #A was selected"); break;
case "B": System.out.println("Option #B was selected"); break;
case "C": System.out.println("Option #C was selected"); break;
case "D": System.out.println("Option #D was selected"); break;
case "X": System.out.println("You chose to Exit"); break;
default: System.out.println("Invalid selection made"); break;
}

}

public void startFor()
{
/*Each of these methods will modify the original start() method, each
*will add a loop of the specific type so that the menu is displayed
*repeatedly, until the last option is selected. When the last option
*is selected, exit the method (i.e. stop the loop).
*/
}

最佳答案

正如您在评论中要求提供一个带有 for 的示例。

练习的重点似乎是在菜单上进行迭代,直到满足退出条件("X".equals(input))。这意味着在 for 语句中的三个条件之间,这是您需要指定的唯一一个。这是因为(基本)for 语句的一般形式是

for ( [ForInit] ; [Expression] ; [ForUpdate] )

括号中的这些术语都不是强制性的,因此我们也可以去掉 [ForInit][ForUpdate] (但保留分号)。这具有不使用 [ForInit] 初始化任何内容的效果,并且在使用 [ForUpdate] 循环的每次迭代结束时不执行任何操作,让我们只检查退出由[Expression] 表达式给出的条件(当其计算结果为false 时,循环退出)。

请注意,console 是在循环外部声明的,因为在每次迭代时分配一个控制台会很浪费。还有input,因为您在for 语句的条件中需要它。

Scanner console = new Scanner(System.in);
String input = "";

for (;!"X".equals(input);) { // notice, the first and last part of the for loop are absent

displayMenu();

input = console.nextLine().toUpperCase();
System.out.println();

switch (input) {
case "A": System.out.println("Option #A was selected"); break;
case "B": System.out.println("Option #B was selected"); break;
case "C": System.out.println("Option #C was selected"); break;
case "D": System.out.println("Option #D was selected"); break;
case "X": System.out.println("You chose to Exit"); break;
default: System.out.println("Invalid selection made"); break;
}
}

您可能会注意到这有点尴尬,因为这不是您通常使用 for 循环的内容。

无论如何,此时,while 版本变得微不足道(while (!"X".equals(input))),在本例中,do...while 也是等价的, (do { ... } while (!"X".equals(input))) 因为相同的条件适用于当前循环的结束和下一个循环的开始,并且它们之间没有副作用。

顺便说一句,您可能会注意到 while (condition)for (; condition ;) 在功能上是等效的,并且您可能会想为什么应该使用一个而不是另一个。答案是可读性。当您执行 while (condition) 时,您想要执行的操作会更加清晰。

关于java - 尝试使用带有 'menu' 的 For 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56162376/

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