【问题标题】:Repeat the "if" statement if it has to go to the "else" statement如果必须转到“else”语句,则重复“if”语句
【发布时间】:2015-02-03 01:28:51
【问题描述】:

int type = 0, num = 0, square, cube;

    Scanner input = new Scanner(System.in);

    System.out.println("Press 1 to Square a Number\nPress 2 to Cube a Number ");
    type = input.nextInt();

    if (type == 1)
    {
            do
        {
            System.out.println("Type a number to square ");
            num = input.nextInt();
            square = num * num;
            System.out.println(square);
        }
        while (num != 0);   
    }

    else if (type == 2)
    {
        do
        {
            System.out.println("Type a number to cube ");
            num = input.nextInt();
            cube = num * num * num;
            System.out.println(cube);
        }
        while (num != 0);   
    }

    else 
        System.out.println("Please type either 1 or 2");

        ----> here I want it to go back to the top and ask again.
        ----> how do it do this part?

请阅读上面我输入这些箭头的地方。这就是我需要帮助的部分。

(别介意。这东西一直在提示我在里面放更多正常的词 所以这就是我正在做的)

}

【问题讨论】:

  • 你想要一个while 循环
  • 如果它想让你继续写更多正常的词,那可能是有原因的。他们不只是为了踢球而设置了最低字数限制,所以不要为了规避而虚张声势。
  • 哇。谢谢马特,你很有帮助...... Aditya 是对的

标签: java loops if-statement while-loop


【解决方案1】:

将整个代码块放在一个while循环中 和 while((type!=1 && type!=2)) { ... }

这样就可以了

【讨论】:

  • 谢谢伙计。我将所有内容放在我将扫描仪放入“Do While”循环的行之后,其中的“while”部分是你所说的并且它起作用了。
【解决方案2】:
while ((type!=1) && (type!=2))
{
  if......

【讨论】:

    猜你喜欢
    • 2019-04-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-10
    • 1970-01-01
    • 2018-01-11
    • 2017-10-28
    • 2017-02-05
    相关资源
    最近更新 更多