简体   繁体   English

如何要求输入 if 循环内的特定条件

[英]How to ask input for the particular condition inside of if loop

In check_mark() method if I put wrong mark for PHYSICS ( which is in 2nd position a[1] ) ie mark > 100 it goes to the if loop and it has to ask input for the same PHYSICS mark but, it again starts from a[0] ie MATHS...... Same as for ENGLISH it again starts from MATHS.在 check_mark() 方法中,如果我为 PHYSICS 设置了错误的标记(位于第二个位置 a[1] ),即标记 > 100,它会进入 if 循环,它必须要求输入相同的 PHYSICS 标记,但是,它再次从a[0] 即 MATHS…… 与 ENGLISH 相同,它再次从 MATHS 开始。

Please help me to solve this that it has to ask input for that particular mark which is wrongly entered....请帮我解决这个问题,它必须要求输入错误输入的特定标记......

Fault code:故障代码:

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();
    }
 }

You should not call check_mark method if mark was incorrect.如果标记不正确,则不应调用 check_mark 方法。 You should to decrement index你应该减少索引

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--;
       }
   }
}

You can also do it with while() loop;你也可以用 while() 循环来做到这一点;

void check_mark()
    {
       for (int j = 0; j < 3; j++) 
       {
           System.out.print("Enter "+b[j]+" mark: ");
           a[j]=sc.nextInt();

           while(a[j]>100){
               System.out.println("Please provide correct mark which is equal to or below 100");
              a[j] = sc.nextInt(); 
           }
       }
   }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM