2013-07-13 135 views
-1

中的逻辑错误,当我使用problem1对象调用方法“getUnknownsAccel”时,出于某种原因未执行方法中的'if'语句来检索变量的值:我需要弄清楚我的代码

PhysicsProblem problem1 = new PhysicsProblem(accel, vI, vF, t, deltaX); 

    System.out.println("Which variable are you solving for? "); 
    String solveFor = scan.next(); 


    // after receiving solveFor input, assesses data accordingly 

    if (solveFor.equalsIgnoreCase("acceleration")) 
    { 
     System.out.println("Solving for Acceleration!"); 
     System.out.println("Are there any other unknowns? (enter 'none' or the name " + 
       "of the variable)"); 
     missingVar = scan.next(); 
     problem1.setMissingVar(missingVar); 
     do 
     { 
      problem1.getUnknownsAccel(); 
      System.out.println("Are there any other unknowns? (enter 'none' or the name " + 
        "of the variable)"); 
      missingVar = scan.next();    //// change all these in the program to scan.next, not scan.nextLine 
     } 
     while (!missingVar.equalsIgnoreCase("none") || !missingVar.equalsIgnoreCase("acceleration")); 

     if (missingVar.equals("none")) 
     { 
      // Write code for finding solutions 
      System.out.println("Assuming you have given correct values, the solution is: "); 
     } 
    } 

了之后做/ while循环用于检索未知其他变量的名字,我叫从这个类文件getUnknownsAccel方法:

public void getUnknownsAccel() 
{ 
    //----------- 
    // checks for another unknown value that is not accel 
    //----------- 
    if (missingVar.equalsIgnoreCase("time")) 
    { 
     System.out.println("Please enter the value for time: "); 
     t = scan.nextDouble(); 
     while (t <= 0 || !scan.hasNextDouble()) 
     { 
      System.out.println("That is not an acceptable value!"); 
      t = scan.nextDouble(); 
     } 
    }  

} 

假设这个问题的缘故,用户将在提示时输入“时间”作为未知数。任何想法为什么我的代码没有执行扫描功能来检索时间变量值?相反,该程序只是重复system.out函数“是否有任何其他未知...”

+0

输入'getUnknownsAccel()'时,'missingVar'的确切值是多少?如果你没有方便的调试器,那么你应该解决这个问题,但同时,只需要在if()之前重新打印出来。 –

+0

假定该人在提示时输入“时间”。当我调用getUnknownsAccel()时,我假设missingVar将等于“time”。我错了吗? – TommyD

+3

嗨。要求人们发现代码中的错误并不是特别有效。您应该使用调试器(或者添加打印语句)来分析问题,追踪程序的进度,并将其与预期发生的情况进行比较。只要两者发生分歧,那么你就发现了你的问题。 (然后,如果有必要,你应该构造一个[最小测试用例](http://sscce.org)。) –

回答

2

扫描后,您将missingVar设置为scan.next(),但您什么都不做。循环继续。

missingVar = scan.next(); 

添加一行

getUnknownsAccel(); 

注,另外一个问题是,你需要在后面的处理是missingVar是本地的 - 来访问它getUnknownsAccel(),你应该将声明更改为

public void getUnknownsAccel(String missingVar){ 
} 

而改为使用 getUnknow nsAccel(missingVar);

+0

我们不知道'missingVar'是一个局部变量。实际上,它在我看来是类的一个实例变量,并且它的声明不包含在问题中。 –

相关问题