java - 如何在 if 循环中询问特定条件的输入
问题描述
在 check_mark() 方法中,如果我为 PHYSICS 放置了错误的标记(位于第二个位置 a[1] ),即标记 > 100,它会进入 if 循环,它必须要求输入相同的 PHYSICS 标记,但是它又从a[0] 即 MATHS...... 与 ENGLISH 相同,它再次从 MATHS 开始。
请帮我解决这个问题,它必须要求输入错误输入的特定标记....
故障代码:
import java.util.Scanner;
class averageMark
{
static int no_of_students=2;
static int a[]=new int[3];
static int no_of_subjects=a.length;
static String b[]=new String[]{"MATHS","PHYSICS","ENGLISH"};
static int avg;
static int total_marks=0;
static Scanner sc=new Scanner(System.in);
void check_mark()
{
for (int j = 0; j < 3; j++)
{
System.out.print("Enter "+b[j]+" mark: ");
a[j]=sc.nextInt();
if(a[j]>100)
{
System.out.println("Please provide correct mark which is equal to or below 100");
check_mark();
}
}
}
public static void main( String[] args )
{
for (int i = 0; i < no_of_students; i++)
{
averageMark check=new averageMark();
check.check_mark();
for (int k = 0; k < no_of_subjects; k++)
{
total_marks+=a[k];
}
avg=total_marks/no_of_subjects;
System.out.println();
System.out.println("The average is: "+avg);
if(avg>=70)
{
System.out.println();
System.out.println("!!!Qualified!!!");
}
else
{
System.out.println();
System.out.println("!!!Not qualified!!!");
}
System.out.println();
}
sc.close();
}
}
解决方案
如果标记不正确,则不应调用 check_mark 方法。你应该减少索引
void check_mark() {
for (int j = 0; j < 3; j++) {
System.out.print("Enter "+b[j]+" mark: ");
a[j]=sc.nextInt();
if(a[j]>100) {
System.out.println("Please provide correct mark which is equal to or below 100");
j--;
}
}
}
推荐阅读
- flutter - 如何正确解析这个 json 对象?
- javascript - 我怎样才能更改 Html 输入类型周语言?
- shibboleth - shibboleth idp 与 OpenLDAP 集成/未捕获的运行时异常 java.lang.NullPointerException: null
- android - 未解决的参考:Android Studio 中的字体
- visual-studio-code - 什么是 Visual Studio Code 中的“Markdown:打开预览到侧面”快捷方式?
- python - 修改python中的元素嵌套列表
- vim - vimrc E127: 无法重新定义函数 CompileBuildrrr: 它正在使用中
- python - 基于填充的 GET 请求键的 Django 动态搜索视图
- php - 当我在数据库中使用 Alamofire 发送三个数组帖子时出现错误?
- python - 如何在 Kotlin 中正确反转链表?