当我使用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: ");
}
}
在用于检索未知其他变量名称的do / 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 :(得分:2)
扫描完成后,将missingVar设置为scan.next(),但不执行任何操作。循环继续。
之后
missingVar = scan.next();
添加行
getUnknownsAccel();
注意,另一个问题是你需要稍后处理的是missingVar是本地的 - 要在getUnknownsAccel()中访问它,你应该将声明更改为
public void getUnknownsAccel(String missingVar){
}
而是使用 getUnknownsAccel(missingVar);