首页 > 解决方案 > 尝试使用带有“菜单”的 For 循环

问题描述

初学者在这里,请尽可能解释!

一个课程问题要求我创建一个菜单(完成)。

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

现在它要我实现一个for,whiledo...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).
   */
}

标签: javafor-loopbluej

解决方案


for正如您在评论中要求的示例。

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

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

如果括号中的这些术语都不是强制性的,那么我们也可以去掉[ForInit]and [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...whiledo { ... } while (!"X".equals(input))

顺便说一句,您可能会注意到while (condition)并且for (; condition ;)在功能上是等效的,并且您可能会徘徊为什么应该使用一个而不是另一个。答案是可读性。当你做的时候,你想做什么就更清楚了while (condition)


推荐阅读