如何在Do-While循环中编写嵌套的if语句?

时间:2014-07-04 17:53:33

标签: java if-statement boolean do-while

我是初学者Java学生。这是我正在做的一般想法。

我有一个用户可以通过输入相应的号码来挑选的东西列表。输入一个整数后,项目旁边的字符串将打印为YES。如果他们决定不再需要它,他们必须再次输入相同的数字,然后字符串应该更改为NO。我的嵌套循环技术允许这种更改,但在读取下一个if语句后立即将其更改回来。我一直在研究这个问题很长一段时间。任何人都可以在正确的方向上推动我找出这个问题吗?

     do
    {
        int num=input.nextInt();  

        if (num == 7)
        {               
            if(s.equals("NO"))  //corresponding string
            {
               s = "YES";
            }
            if(s.equals("YES"))  //same corresponding string
            {
               s = "NO";
            }
        }

    //similar if statements for different conditions 
    //similar if statements for different conditions 


    }while(myBoolean()==true);

3 个答案:

答案 0 :(得分:1)

你似乎错过了一个其他陈述。

if(s.equals("NO"))  //corresponding string
{
   s = "YES";
} else if(s.equals("YES"))  //same corresponding string
{
   s = "NO";
}

或者如果你想稍微缩短一点:

s = s.equalsIgnoreCase("NO") ? "YES" : "NO";

答案 1 :(得分:0)

你应该做的是使用像这样的else if语句

if (num == 7)
{               
    if(s.equals("NO"))
    {
       s = "YES";
    }
    else if(s.equals("YES"))
    {
       s = "NO";
    }
}

如果第一个if语句为true,则会跳过else if语句。如果if语句为false,则会读取else if语句。你也可以有多个else if语句,如此

if(boolean)
{
   ....
}
else if(another boolean)
{
   ....
}
else if(some other boolean)
{
   ....
}

如果if语句和所有else if语句都是false,您可以添加else语句,该语句将被读取

if(boolean)
{
   ....
}
else if(another boolean)
{
   ....
}
else
{
   ....
}

答案 2 :(得分:0)

 do
{

只需添加"否则"在你的"如果"之间声明。在您的示例中,当s为" NO"时,您将其更改为" YES"。因此s是"是"当你点击第二个"如果"言。

更好的是,而不是测试两个值" YES和" NO",只测试其中一个并在测试失败时采取相反的情况。

例如为:      做     {         int num = input.nextInt();

    if (num == 7)
    {               
        if(s.equals("NO"))  //corresponding string
        {
           s = "YES";
        }
        else  // <--- This is the only change I made.
        {
           s = "NO";
        }
    }

//similar if statements for different conditions 
//similar if statements for different conditions 


}while(myBoolean()==true);
相关问题