【发布时间】:2014-12-14 06:38:43
【问题描述】:
首先:我在下面的代码中不断陷入无限循环。代码的构建是为了让您输入 1 到 10 之间的 8 个数字。它证明这些数字在 1 到 10 之间。然后第二个证明是这 8 个数字加起来等于 60。如果其他情况,我在结尾有问题陈述。如果数字的总数为 60,它可以正常工作并打印出来,但如果它在 if 语句处停止,它会无限打印 “你输入了错误的总数” 打印输出以及总点数不断增加。我是否遗漏了一些简单的东西,比如括号之类的东西?
其次:如果总数不是60,如何循环回到最初输入的值并重新开始整个过程?
public static void lebronJames() {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
//Declare an array to hold 8 intgers values
int lebronJamesAttributes[] = new int[8];
int attribute = 0;
System.out.println("Please allocate your attribute points for Lebron James in the following order. Your point allocations per attribute should be between 1 and 10. You have a total of 60 points to allocate");
System.out.println("-----------------");
System.out.println("Close Range" + "\n" + "Mid Range" + "\n" + "Three Point" + "\n" + "Free Throw" + "\n" + "Offensive Rebound" + "\n" + "Defensive Rebound" + "\n" + "Assist" + "\n" + "Steal" + "\n");
while (attribute <= 7) {
int attributeValue = input.nextInt();
if (attributeValue >= 1 && attributeValue <= 10 ) {
lebronJamesAttributes[attribute] = attributeValue;
attribute++;
}
else {
System.out.println("The attribute value you have selected is out of range. Select again.");
}
}
int jamesTotalQuarter = 0;
while (jamesTotalQuarter != 60){
for (int jamesTotalQ1 : lebronJamesAttributes){
jamesTotalQuarter += jamesTotalQ1;
}
if (jamesTotalQuarter != 60) {
System.out.println("You have entered the wrong total number of attribute points. Please enter a total of 60 attribute points between the 8 characteristics.");
System.out.println("You have allocated a total of " + jamesTotalQuarter + " points.");
}
else {
System.out.println("Close Range" + lebronJamesAttributes[0] + "\n" + "Mid Range" + lebronJamesAttributes[1] + "\n" + "Three Point" + lebronJamesAttributes[2] + "\n" + "Free Throw" + lebronJamesAttributes[3] + "\n" + "Offensive Rebound" + lebronJamesAttributes[4] + "\n" + "Defensive Rebound" + lebronJamesAttributes[5] + "\n" + "Assist" + lebronJamesAttributes[6] + "\n" + "Steal" + lebronJamesAttributes[7] + "\n");
System.out.println("You have allocated a total of " + jamesTotalQuarter + " points.");}
}
}
}
【问题讨论】:
-
您的 for 循环根据
lebronJamesAttributes数组中的元素添加jamesTotalQuarter。这样您就可以跳过60,从而导致无限循环。例如,如果我在jamesTotalQuarter = 55并且lebronJamesAttributes中的下一项是10。你得到65。而且由于您添加数字,它永远不会是60。 -
你需要创建一些递归函数来实现你的输出
-
Spencer Wieczorek 我应该改写成某种不等式,比如 jamesTotalQuarter > 60 || jamesTotalQuarter
标签: java loops infinite-loop