首页 > 解决方案 > 如何在 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();
    }
 }

标签: javaarraysloopsfor-loopif-statement

解决方案


如果标记不正确,则不应调用 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--;
       }
   }
}

推荐阅读