gpt4 book ai didi

java - 如何在for循环中设置限制?

转载 作者:行者123 更新时间:2023-12-02 02:54:16 25 4
gpt4 key购买 nike

我必须创建一个程序来计算每个学生的平均分。我设法做到了,但是如何将分数限制在 0 到 100 之间呢?我搜索了其他问题和许多节目来放置 while 语句。问题是我不知道在哪里添加 while。所以这是代码:

import java.util.Scanner;

public class AverageScore {
public static void main(String[] args) {

int x; // Number of students
int y; // Number of tests per student
int Score = 0; //Score of each test for each student
double Average = 0; //Average score
double Total = 0; //Total score

Scanner keyboard = new Scanner(System.in);

System.out.println("Please enter the number of students: ");
x = keyboard.nextInt();

System.out.println("Please enter the amount of test scores per student: ");
y = keyboard.nextInt();

for (int z = 0; z < x; z++)
{
System.out.println("Student " + (z + 1));
System.out.println("------------------------");

for (int g=0; g < y; g++)
{
System.out.print("Please enter score " + (g + 1) + ": ");

Total += new Scanner(System.in).nextInt();
Total += Score;
Average = (Total/y);
}

System.out.println("The average score for student " + (z + 1) + " is " + Average);
System.out.println(" ");

Total= 0;
}

keyboard.close();
}
}

如果还有其他方法请注明。提前致谢。

最佳答案

import java.util.Scanner;

public class AverageScore {
public static void main(String[] args) {

int x; // Number of students
int y; // Number of tests per student
int Score = 0; //Score of each test for each student
double Average = 0; //Average score
double Total = 0; //Total score
double Input = 0; **//Add this in your variable**
boolean Valid = false; **//Add this in your variable**

Scanner keyboard = new Scanner(System.in);

System.out.println("Please enter the number of students: ");
x = keyboard.nextInt();

System.out.println("Please enter the amount of test scores per student: ");
y = keyboard.nextInt();

for (int z = 0; z < x; z++)
{
System.out.println("Student " + (z + 1));
System.out.println("------------------------");

for (int g=0; g < y; g++)
{
System.out.print("Please enter score " + (g + 1) + ": ");
Input = new Scanner(System.in).nextInt();

//validation of your input from 0 to 100
if(Input>=0&&Input<=100)
{
Valid = true;
}

//enter while loop if not valid
while(!Valid)
{
System.out.println("");
System.out.print("Please enter a valid score " + (g + 1) + ": ");
Input = new Scanner(System.in).nextInt();
if(Input>=0&&Input<=100)
{
Valid = true;
}
}

Valid = false; //reset validation;

Total += Input;
Average = (Total/y);
}

System.out.println("The average score for student " + (z + 1) + " is " + Average);
System.out.println(" ");

Total= 0;
}

keyboard.close();
}
}

关于java - 如何在for循环中设置限制?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43358470/

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