2014-07-04 200 views
0

我是一名初学Java的学生。这是我正在做的一般想法。如何在Do-While循环中编写嵌套的if语句?

我有一个用户可以通过输入相应的数字来选择的东西列表。输入一个整数后,该项旁边的字符串将打印为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); 
+0

使用else if block。if(something){...} else if(something else){...}'您的代码缺少'else'我认为 –

回答

0
do 
{ 

只需添加“if”语句之间的“else”一词。在你的例子中,当s是“NO”时,你将它改为“YES”。因此,当你点击第二个“if”语句时,s是“YES”。

更好的是,代替测试两个值“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); 
+0

哇,那太简单了!非常感谢你!但现在出于某种原因,我必须输入一个数字,然后再次循环......你认为我的布尔值有什么问题吗? – user3806226

1

你似乎缺少一个else语句。

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

,或者如果你想缩短事情有点:

s = s.equalsIgnoreCase("NO") ? "YES" : "NO"; 
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 
{ 
    .... 
} 
+0

谢谢!现在的问题是,它可以将它从yes更改为no,但是如果不重新启动prog,我无法将其更改回yes ram – user3806226