Home > Software engineering >  How to iterate the switch through a loop if user enter the last switch Case(default) and I want him
How to iterate the switch through a loop if user enter the last switch Case(default) and I want him

Time:11-05

package com.mhm;

import java.util.Scanner;

public class StudentGrade {
    public static void main(String[] args) {

        System.out.println("Enter your grade: ");
        Scanner in = new Scanner(System.in);
        String grade = in.nextLine();
         //a program that prompts the user to enter the grade for student and show up a massege for him 

1-if he gets A write Excellent 2-if he gets B write OutStanding 3- if he gets C write Good 4-if he gets D write Can Do Better 5- if he gets f write Failed ! if user entered another grade write invaild grade

            switch (grade) {

                case "A":
                    System.out.println("Excellent.");
                    break;
                case "B":
                    System.out.println("OutStanding.");
                    break;
                case "C":
                    System.out.println("Good");
                    break;
                case "D":
                    System.out.println("Can Do Better ");
                    break;
                case "F":
                    System.out.println("Failed !");
                    break;
                default:
                    System.out.println("invalid grade ");
            }





        }
    }

CodePudding user response:

Generally, there's a couple ways you can handle this, depending on how much you like recursion. But here's an iterative option that works by setting a flag regarding whether or not you should continue the loop.

public static void main(String[] args) {
    
    Scanner in = new Scanner(System.in);
    boolean flag = true; //We will set this variable to false in order to indicate that we should exit the loop.

    while (flag) {
        

        System.out.print("Enter your grade: ");
        String grade = in.nextLine();

        switch (grade) {
            //As DevilsHnd notes, you might also want to use 'switch (grade.toUpperCase()) {' so that your program is case-insensitive.

            case "A":
                System.out.println("Excellent!");
                flag = false; //This indicates we should exit the loop.
                break;

            case "B":
                System.out.println("Outstanding!");
                flag = false; //This also indicates we should exit the loop.
                break;

            /**
             *    More cases go here
             */

            default:
                System.out.println("Sorry, I didn't understand that. Could you try again?");
                //Note that we're not setting flag to false this time. This is because we are not exiting the loop.


        }

    }
    
    in.close(); //Don't forget to close your resources!

}
  • Related