简体   繁体   中英

Conditional Operators(!=)(If-else Statement)

Desired Output:

Data Type: int
Variable Name: a
Initial Value: 0
Conditional Operator: !=
Conditional Value: 5
Increment/Decrement: ++
Interval: 1
for(int a=0;a!=5;a+=1)
{
}
for(int a=1;a!=5;a+=1)
{
}
for(int a=2;a!=5;a+=1)
{
}
for(int a=3;a!=5;a+=1)
{
}
for(int a=4;a!=5;a+=1)
{
}

If you change the interval to 2, it should output "Infinite Loop! Try Again" and if you change the interval to 1, it should output the desired output stated above.

My program's output:

Data Type: int
Variable Name: a
Initial Value: 0
Conditional Operator: !=
Conditional Value: 5
Increment/Decrement: ++
Interval: 1
Infinite Loop! Try Again!

My code:

else if(inc_dec.equals("++") && conditionalOperator.equals("!="))
 {
   for(float c=initialValue;c!=conditionalValue;c+=interval)
     {
       if(initialValue == conditionalValue)
         System.out.print("for("+dataType+" "
         +varName+"="+c+";"+varName+conditionalOperator+conditionalValue+";"
         +varName+"+="+interval+"){\n}\n");
       else break;
     }
       System.out.println("Infinite Loop! Try Again!");
  }

PS The code should only use if-only statements

I fixed it!

else if(inc_dec.equals("++") && conditionalOperator.equals("!="))
                    {
                     for(float c=initialValue;c!=conditionalValue;c+=interval)
                     {
                      if(conditionalValue%interval == 0)
                         System.out.print("for("+dataType+" "+varName+"="+c+";"+varName+conditionalOperator+conditionalValue+";"+varName+"+="+interval+"){\n}\n");
                      else break;
                     }
                    }

Initial value of a = 0 and if you increment variable a value by 2 then the condition a!=5 will never be true. Your a becomes 0,2,4,6,8...infinity (But it will never become 5). Hence you are going into infinite loop.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM