其他条件似乎无法执行

时间:2016-02-08 03:14:40

标签: java if-statement

我正在创建一个简单的数学练习程序,但是我遇到了一个严重的问题,我的其他条件。当应该触发else块运行的条件时,if语句运行,即如果程序提示用户回答问题7 + 6,如果他们输入5,它仍然会说就像他们输入了正确的答案一样。在过去的几个小时里,我已经梳理了这个if if系列的每次迭代(这只是5中的一个),但我无法确定阻止else段运行的情况。

correctrange / correctrange2是随机生成的int值(目前它们总是分别为7和6) d1& d2与双精度值相同 人是一个错误参数 当input1 = q时,程序应该结束 编辑:这是一个更新版本,但错误仍然存​​在

  //Addition    
    boolean addition = false;
while(input1 == 'A'|| input1 == 'a')
{
    System.out.println("What is the solution to the problem " + correctRange 
            + " + " +  correctRange2 );
    double input2 = userinput.nextDouble();
    if(input2 <= (d1 + d2) + human || 
       input2 >= (d1 + d2) - human)
    {System.out.println("That is correct!");
     System.out.println("What would you like to practice next?");
     addition = true;
    }
    while (!addition) 
    {System.out.println("The correct solution is " +
                correctRange + correctRange2);
        input1 = 'q';
        }
    input1 = userinput.next().charAt(0);
}

2 个答案:

答案 0 :(得分:0)

每次拨打userinput.nextDouble()时,它都会读取一个新的双倍。如果你召唤它两次,那么期待一个新的双倍。

if(userinput.nextDouble() <= (d1 + d2) + human || 
   userinput.nextDouble() >= (d1 + d2) - human)

如果第一个条件为假,则读取一个或两个。

很可能你打算做

double input = userinput.nextDouble();
if(input <= (d1 + d2) + human || 
   input >= (d1 + d2) - human)

或者你可以写

if(Math.abs(input - (d1 + d2)) <= human)

注意:=是作业,==是比较

while (addition = false) 

总是false你想要的可能是什么

while (addition == false) 

或更好

while (!addition) 

答案 1 :(得分:0)

问题在于你的条件:

NSString *dateStr = @"2016-01-18T13:28:06.357";
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.SSS"];
NSDate *date = [formatter dateFromString:dateStr];

让我们取你的样本值:d1 = 6,d2 = 7,人类= 0。

  • 用户输入5:if (input2 <= (d1 + d2) + human || input2 >= (d1 + d2) - human) ?是的,确定
  • 用户输入13:5 <= (6+7)+0?是的,仍然是真的
  • 用户输入20:13 <= (6+7)+0?不,但是:
  • 用户输入20:20 <= (6+7)+0?是的!

我认为你的情况应该是:

20 >= (6+7)-0
相关问题