0

In check_mark() method if I put wrong mark for PHYSICS ( which is in 2nd position a[1] ) i.e 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] i.e MATHS...... Same as for ENGLISH it again starts from 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();
    }
 }

2 Answers 2

1

You should not call check_mark method if mark was incorrect. 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--;
       }
   }
}
Sign up to request clarification or add additional context in comments.

Comments

1

You can also do it with while() loop;

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.