Search code examples
javaif-statementmethodsswitch-statementgoto

When i try to use method it give error


i have a switch statement in which i try to check for string values, i want that after checking for name it should ask for marks. But when i try to make an if else statement in a method it gives error.

here is the code which runs fine :

import java.util.Scanner;

public class java {

    public static void main(String args[]) {
        Scanner obj = new Scanner(System.in);
        int num;
        final int pass = 33;
        String Student;
        System.out.println("Please enter your name");
        Student = obj.nextLine();
        switch (Student) {
            case "Ram":
                System.out.println("Students name is " + Student);
                break;
            case "Shyaam":
                System.out.println("Students name is " + Student);
                break;
            default:
                System.out.println("This name is not recognised");

        }

        System.out.println("Enter your marks");
        num = obj.nextInt();
        if (num < pass) {
            System.out.println(Student + " You have failed the subject");
        } else {
            System.out.println(Student + " You have passed the subject");
        }
    }
}

but in this even if name does not get verified it still ask for marks.

what should i do.

Please help.


Solution

  • A switch statement is not a while switch statement.

    To allow to take another input, include the switch in a while that goes on while the student String is not valid.
    Besides, you should respect conventions : the variable name should start with a lowercase.
    String student is correct. String Student is not.

     String student = null;
    
     while (student == null){
        student = obj.nextLine();
    
        switch(student){
          case "Ram":
            System.out.println("Students name is "+ Student);
            break;
          case "Shyaam":
            System.out.println("Students name is "+ Student);
            break;
          default:
              System.out.println("This name is not recognised");
              student = null;
        }
    }