提问人:Jamie Morrissey 提问时间:11/9/2023 更新时间:11/10/2023 访问量:33
在for语句中的if语句中,java程序计算成绩然后分配字母编号。扫描仪类请为循环提供帮助
An if statement inside a for statement, java program to calculate the grades then assign letter numbers. Scanner class please need assistance for loop
问:
有人可以帮我处理 for 循环中的 if 语句,Java 新手,当插入“999”时,会破坏循环。谢谢。另外,签署程序的退出或只是用中断语句退出循环会好吗?
package java_1.java;
import java.util.Scanner;
public class HelloWorld {
public static void main(String[] args) {
int marks[] = new int[10];
int i;
float total=0,avg;
Scanner scanner = new Scanner(System.in);
int b = 999;
for(i=0; i<10; i++) {
System.out.print("Enter Marks of Subject"+(i+1)+":");
marks[i] = scanner.nextInt();
total = total + marks[i];
if(marks[i]==b)
{
break;
}
}
scanner.close();
int sum = 0;
float average = 0.0f;
// Calculating the average in for loop
for (i=0; i<marks.length;i++) {
sum += marks[i];
}
average = (float) sum / marks.length;
// Printing the calculating averated value
System.out.print("The average of he given array: " + average);
//Calculating the average
avg = total/10;
System.out.printf("%n");
System.out.print("Average student grade out of the scores is: ");
// Define variables for for loop
if(avg>=80)
{
System.out.print("A");
}
else if(avg>=60 && avg<80)
{
System.out.print("B");
}
else if(avg>=40 && avg<60)
{
System.out.print("C");
}
else
{
System.out.print("D");
}
}
}
答:
-2赞
alpaca
11/9/2023
#1
System.exit(),如果你的目的是关闭程序 中断以关闭循环
-2赞
Reilas
11/9/2023
#2
"...签署程序的退出或只是用中断语句退出循环会好吗?..."
利用布尔值来确定循环是否提前退出。
...
int b = 999;
boolean exited = false;
for(i=0; i<10; i++) {
...
if(marks[i]==b)
{
exited = true;
break;
}
}
if (!exited) {
...
}
上一个:如何在函数中保留对象
评论