gpt4 book ai didi

java - 使用 do-while 循环创建 for 循环时遇到问题

转载 作者:行者123 更新时间:2023-12-01 13:34:57 24 4
gpt4 key购买 nike

刚开始使用 Java,本周我的作业是编写一个程序,询问用户想要输入多少测试分数,用户填写该分数,然后程序要求他们输入测试分数,直到计数器达到我觉得我首当其冲,但只需要更多帮助,这有点陷入死循环,我陷入了困境。我已经移动了 for 循环,它要么将我的显示文本放入永无休止的循环中,要么程序在要求输入分数后停止(这就是现在的位置)。感谢任何帮助:

import java.util.Scanner;
public class TestScoreApp
{
public static void main(String[] args)
{
// display operational messages
System.out.println("Please enter test scores that range from 0 to 100.");
System.out.println(); // print a blank line

// initialize variables and create a Scanner object
int scoreTotal = 0;
int scoreCount = 0;
int testScore = 0;
int count = 0;
Scanner sc = new Scanner(System.in);
String choice = "y";
while (!choice.equalsIgnoreCase("n"))

while (testScore <= 100)
{

// get the input from the user
System.out.print("Enter the number of scores to be entered: ");
for (scoreCount = 0; count <=100; scoreCount++)
scoreCount = sc.nextInt();

// get the input from the user
System.out.print("Enter score: ");
testScore = sc.nextInt();

// accumulate score count and score total
if (testScore <= 100)

{
scoreCount = scoreCount + 1;
scoreTotal = scoreTotal + testScore;
}
else if (testScore != 999)
System.out.println("Invalid entry, not counted");

// display the score count, score total, and average score
double averageScore = scoreTotal / scoreCount;
String message = "\n" +
"Score count: " + scoreCount + "\n"
+ "Score total: " + scoreTotal + "\n"
+ "Average score: " + averageScore + "\n";

System.out.println(message);
System.out.println("Enter more test scores? ('y' to continue, 'n' to close): ");
choice = sc.next();
System.out.println();



}
}
}

最佳答案

尝试这样的事情:

// put this above main() - this way you can use it without ever defining a `Scanner` object again
static Scanner in = new Scanner(System.in);

public static void main(String[] args) {

// store number of scores to enter
int numScores = 0;

// input number of scores to enter
System.out.print("How many scores would you like to enter? ");
numScores = in.nextInt();

// store sum of scores
int scoreTotal = 0;

// input scores
for(int i = 0; i < numScores; i++)
scoreTotal += in.nextInt();

// print count, sum, and average of scores
System.out.printf("\nScore count: %d", numScores);
System.out.printf("\nScore total: %d", scoreTotal);
System.out.printf(\n Average score: %d", scoreTotal/numScores);
}

我认为这应该可以运行,但它可能有一两个错误。我不再有 Java,但如果它产生错误,我将能够提供帮助。只需将其放入您的类(class)中,看看它是如何工作的。您根本不需要修改它。

关于java - 使用 do-while 循环创建 for 循环时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21357721/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com