If I increment a variable within a switch case how do I get it to increment outside as well?

Viewed 18

There are multiple issues with my code, I know. I am definitely a beginner. One issue is that my object keeps being written over. I tried incrementing within the switch case as you can see. That doesn't seem to work. I am not sure how else to do it. Also, when my program sees that a user tries to reuse an employee id it gives an error, but doesn't break out of the switch case. Any help on how to break out once the error is printed would be a big help! Thank you!

   import java.util.*;

   public class HR{
      public static void main (String arg [ ]) throws Exception {

  Employee[] employees = new Employee[10];
  
  int size = 0;
  int index = 0;
  int option = 1;
  int enumb = 0;
  int delEnumb = 0;
  double salary;
  double moreThanSalary;
  String name;

  while (option != 0) {
   
     try {
        // Printing statements displaying menu on console
        System.out.println("\n**********MENU**********");
        System.out.println("1: Add Employee");
        System.out.println("2: Delete Employee");
        System.out.println("3: Display Employee(s) Earning Salary higher that you specify");
        System.out.println("4: Print all employees info");
        System.out.println("0: Exit program");
        Scanner input = new Scanner(System.in);
     
        System.out.print("\nEnter your selection : ");
        option = input.nextInt();
        
        switch (option) {
           case 1: 
                             
              Scanner scanint = new Scanner(System.in);
              Scanner scanstr = new Scanner(System.in);
              System.out.println("\nYou have selected to add a new employee");
              System.out.println("\nEnter ID: ");
              enumb = scanint.nextInt(); 
              for (index = 0; index < employees.length; index++){
                 if (employees[index] != null){
                    if (employees[index].getEnumb() == enumb) {
                       System.out.println("\nEmployee ID already exists");
                    }
                 }
              }
             
              System.out.println("Enter salary: ");
              salary = scanint.nextDouble();
              System.out.println("Enter name: ");
              name = scanstr.nextLine();
              employees[size]= new Employee(enumb, salary, name);
              size++; // this doesn't seem to be incrementing so it is just writing over
                      // the same object again and again.  
              
              break;
              
           case 2:
              System.out.println("\nYou have selected to remove an employee");
              Scanner scanId = new Scanner(System.in);
              System.out.println("Enter Employee number: ");
              delEnumb = scanId.nextInt();
              if (delEnumb >= 10001 && delEnumb <= 99999){
                 for (index = 0; index < employees.length; index++){
                    if (employees[index] != null){
                       if (employees[index].getEnumb() == delEnumb) {
                          employees[index] = null;
                          System.out.println("Employee entry has been deleted");
                       }
                    }
                 }
              }
              break;
        
           case 3:
              System.out.println("\nYou have selected to search through and find employees "
                                +"\nwhose salary is more than an amount you provide.");
              System.out.println("Enter Salary amount: ");
              Scanner userInput = new Scanner(System.in);
              moreThanSalary = input.nextDouble();
              for (index = 0; index < employees.length; index++) {
                 if (employees[index] != null){
                    if (employees[index].getSalary() > moreThanSalary ) {
                       System.out.println(employees[index]);
                    }
                 }
              }// closes for loop
           
              break;
        
           case 4: 
              System.out.println("============================");
              for (index=0; index < employees.length; index++){
                 if (employees[index] != null){
                    System.out.println(employees[index]);
                    System.out.println("============================");
                 }
              }
              break;
           case 0:
              System.out.print("\nYou have selected to exit the program. Thank you!");
           
              break;
              
           // If none of the above cases execute (less than 0 or more than 4)
           default: 
           
              System.out.println("\nSorry, you have entered a number other than 1, 2, 3, 4 or zero. \nTry Again.\n");
              
              break;
        
        } // closes switch
     
     } // closes try
     
     catch (InputMismatchException ime) {
        System.out.print("\n\t\t\t\t  ***Error*** \nThat entry was not an integer! Try again :)\n");
        continue;
     } // closes catch  
     catch (EmployeeException ee) {
        System.out.print(ee.getMessage());
     } // closes catch    
  } // closes while   

} // closes main

} // closes class '''

1 Answers

I found solutions to my issues. In case this helps others in future here is what I came up with. I am sure there are faster ways but this is what I used within the limits of my CS class:

  import java.util.*;
  import java.text.*;

  public class HR{
       public static void main (String arg [ ]) throws Exception {

  final int SIZE = 100; // Constant used so changing array size is easier 
  int realSize = 0;
  int index = 0;
  int option = 1; 
  int enumb = 0; // variable used in switch case 1
  int delEnumb = 0; // variable used in switch-case 2
  double salary; // variable used in switch case 1
  double moreThanSalary; // variable used in switch-case 3
  String name; // variable used in switch case 1
  boolean isEqual = false; // variable used in switch case 1 & 2
  boolean isEmpty = true; // variable used in switch-case 4
  boolean isNotMore = true; // variable used in switch-case 3

  Employee[] employees = new Employee[SIZE]; // creates empty array 'employees' and sets size to 100

  while (option != 0) {
     
     try {
        // Printing statements displaying menu on console
        System.out.println("\n**********MENU**********");
        System.out.println("1: Add Employee");
        System.out.println("2: Delete Employee");
        System.out.println("3: Display Employee(s) Earning Salary higher that you specify");
        System.out.println("4: Print all employees info");
        System.out.println("0: Exit program");
        Scanner input = new Scanner(System.in);
     
        System.out.print("\nEnter your selection : "); // Gets user input
        option = input.nextInt(); // Stores user input
        
        switch (option) {
           case 1: // add a new employee
                             
              Scanner scanint = new Scanner(System.in);
              Scanner scanstr = new Scanner(System.in); 
              System.out.println("\nYou have selected to add a new employee");
              System.out.println("\nEnter ID: "); // Gets uer input
              enumb = scanint.nextInt(); // Stores user input
              // Checks through current contents of array to see if enumb already exists
              for (index = 0; index < employees.length; index++){
                 // Skips empty (null) elements of array 
                 // && runs if the user entry matches a previous employee id then error message prints
                 if (employees[index] != null && employees[index].getEnumb() == enumb){ // == because it's primitive datatype
                    // 
                    System.out.println("\nEmployee ID already exists");
                    isEqual = true;
                 } // closes if statement
              } // closes for loop 
              // Will only run if the for loop above didn't find a matching employee ID number
              if (isEqual == false) {
                 System.out.println("Enter salary: "); 
                 salary = scanint.nextDouble(); // stores user input
                 System.out.println("Enter name: "); // Gets user input
                 name = scanstr.nextLine(); // stores user input
                 employees[realSize]= new Employee(enumb, salary, name); // creates object in employees array
              }
              break; // returns the user to the menu
              
           case 2:
              isEqual = false;
              System.out.println("\nYou have selected to remove an employee");
              Scanner scanId = new Scanner(System.in);
              System.out.println("\nEnter Employee number: ");
              delEnumb = scanId.nextInt(); // stores user input
              // Checks if the number the user has enteres is within the Employee ID range
              if (delEnumb >= 10001 && delEnumb <= 99999){
                 // Loops through employees array to check all NON null entries to find one that matches 
                 // and deletes it
                 for (index = 0; index < employees.length; index++){
                    if (employees[index] != null && employees[index].getEnumb() == delEnumb){ // == because primitive
                       employees[index] = null; // 'deletes' it by setting array element to null
                       System.out.println("\nEmployee entry has been deleted");
                       isEqual = true;
                    } // Closes if statement
                 } // Closes for loop
                 // Prints in case the ID number the user enters doesn't yet exist in the array
                 // Returns them to the menu
                 if (isEqual != true) {
                    System.out.println("\nThere is no current employee with that number.");
                 }// closes if statement
              }// Closes if statement
              else {
                 // Prints if the user has entered a number outside of the range then returns them to the menu
                 System.out.println("Your selection is outside of the range 10001 to 99999. "
                                   +"You will now be returned to the menu.");
              }// Closes else statement
              break; // returns the user to the menu
        
           case 3: // runs is the user selects the salary search option
              System.out.println("\nYou have selected to search through and find employees "
                                +"\nwhose salary is more than an amount you provide.");
              System.out.println("\nEnter Salary amount: ");
              Scanner userInput = new Scanner(System.in);
              moreThanSalary = input.nextDouble(); // Stores user input of double size
              // Used to help format the dollar amount the user entered to it looks nice
              DecimalFormat myFormatter = new DecimalFormat("$###,##0.00"); // used to format the $ amount nicely
              String output = myFormatter.format(moreThanSalary);
              // Print to let user know that the following text are employees that earn over the amount they requested
              System.out.println("\nNext you will see the employees that make over " + output + ":"); 
              // Loops through the array to search through salaries
              System.out.println("============================");                  
              for (index = 0; index < employees.length; index++) {
                 // Only searches NON null elements and prints out entries where the employee 
                 // earns over the specified amount the user inputed
                 if (employees[index] != null && employees[index].getSalary() > moreThanSalary){
                    System.out.println(employees[index]);
                    System.out.println("============================");
                    isNotMore = false;
                 }// closes if statement
              }// closes for loop
              // Will print if the amount that the user entered is more than any current employee salaries
              if (isNotMore != false) {
                 System.out.println("\nNo employees earn over " + output + ", time for a raise!");
              }// closes if statement
              break; // returns the user to the menu
        
           case 4: // Will run if the user chooses to print out all employee info
              for (index=0; index < employees.length; index++){
                 // Skips entries that are empty (null) 
                 if (employees[index] != null){
                    System.out.println(employees[index]);
                    isEmpty = false;
                 } // closes if statement
              } // closes for loop
              if (isEmpty != false) {
                 System.out.println("\nThere are no employees currently in the system. ");
              }
              break; // returns the user to the menu
              
           case 0: // Will run if the user chooses to exit the program
              System.out.print("\nYou have selected to exit the program. Thank you!");
              break;
              
           // Will run if none of the above cases execute (user enters a # less than 0 or more than 4)
           default: 
              System.out.println("\nSorry, you have entered a number other than 1, 2, 3, 4 or zero. \nTry Again.\n");
              break; // returns the user to the menu
        } // closes switch
     } // closes try
     
     // prints error message if user enters something other than an integer
     catch (InputMismatchException ime) {
        System.out.print("\n\t\t\t\t  ***Error*** \nThat entry was not an integer! Try again :)\n");
        continue;
     } // closes catch  
     // prints if the user enters something that triggers my custom exception
     catch (EmployeeException ee) {
        System.out.print(ee.getMessage());
     } // closes catch    
     realSize++; // here so that future entries are put in the next element
  } // closes while   
 } // closes main
} // closes class
Related