调试这个简单的高尔夫游戏Java代码有什么问题?
我迷路了。在我的Java1类中,我应该调试并修复这个简单的代码。这是一场简单的高尔夫比赛。我知道这个问题基本上是要求你们也做我的家庭作业,但我想帮助你们在未来的调试任务中找到正确的方向
高尔夫球赛。java
import java.util.Scanner;
/*
* Debugging Exercise - Chapter 4
*
* Debug the error(s) and submit to the Dropbox on Angel
* Please do not submit if it is not debugged
*
*/
///////////////////////////////////////////////////////////////////////////////
// READ ME FIRST:
// This program compiles, but, there is logic error in the while statement.
// Debug the logic error and run the program to calculate your golf score.
// Try inputting several numbers to get the total score.
// The program should keep looping until the user selects -1 to terminate.
///////////////////////////////////////////////////////////////////////////////
public class GolfGame {
Scanner input = new Scanner(System.in);
public void getTotalScore() {
int score = 0, total = 0;
while ( score == -1 )
{
System.out.print("Please enter a score [-1 to quit]: ");
score = input.nextInt();
System.out.println();
total += score;
}
if (total != -1)
System.out.println("Your total score is " + total);
}
}
高尔夫球赛。java
/*
* This is the MAIN class; RUN this class to show
* that the GolfGame.java program functions correctly.
*
* NOTE: You must first debug the GolfGame.java file.
* There is no need to debug this file.
*/
public class GolfGameTest {
public static void main(String[] args)
{
System.out.println("Golf Game Calculator");
GolfGame golfGame = new GolfGame();
golfGame.getTotalScore();
}
}
# 1 楼答案
while循环将永远不会被输入
向正确的方向推进。。。查看循环控制。如果你在进入循环时遇到困难,那么下一个更痛苦的缺陷就是“无限循环”
在编写循环代码时,实践是在多次迭代中,从思想上或书面上跟踪循环控制变量,确保:
上述订购的原因基于未能这样做导致缺陷的次数百分比
# 2 楼答案
如果我能回到我开始编程的时候,只教会自己一件事,那就是使用调试器的基础知识
它将真正帮助您了解netbeans的调试特性。为了更好地解决调试问题,这可能是最重要的一件事。我建议从以下几点开始:
这似乎是了解NetBeans中调试的一个良好开端:
http://www.cs.uga.edu/~shoulami/sp2009/cs1301/tutorial/NetBeansDebuggerTutorial/NetBeansDebuggerTutorial.htm
在您的示例中,您可以一步一步地查看代码,发现它从未进入while循环。您还可以查看score变量的值(应该是0),并看到“while(score=-1)”中的条件不是真的