jeudi 15 septembre 2016

JAVA -if else displays multiple outputs

I have this bit of code to return to the beginning of the program if an answer is not expected.

else                                                     // returns to start for unsatisfactory
        {   
               System.out.println();
               System.out.println();
               System.out.println("Check your spelling and try again");
               main (args);

        }      

however when I i enter a different word then go through again and enter an expected word the program outputs two different results


Current Salary: $100.00

Amount of your raise: $4.00

Your new salary: $104.00


Current Salary: $100.00

Amount of your raise: $0.00

Your new salary: $100.00


I tried using an else if statement to possibly eliminate that as a cause but it caused the same thing.


import java.util.Scanner;
import java.text.NumberFormat;

 public class Salary {
     public static void main (String[] args) {
         double currentSalary; // employee's current salary
         double raise = 0.0;         // amount of the raise
         double newSalary;     // new salary for the employee
         String rating;         // performance rating

         Scanner scan = new Scanner(System.in);
         System.out.print ("Enter the current salary: ");
         currentSalary = scan.nextDouble();

        System.out.print ("Enter the performance rating (Excellent, Good, or Poor): ");

        rating = scan.next();

        // Computes raise with if-else
        if ((rating.equals("Excellent")) || (rating.equals("excellent"))) {
            // calculates raise for excellent
            raise = .06 * currentSalary;
        }
        else if ((rating.equals("Good")) || (rating.equals("good"))) {
            // calculates raise for good
            raise = .04 * currentSalary;
        }
        else if ((rating.equals("Poor")) || (rating.equals("poor"))) {
            // calculates raise for poor
            raise = .015 * currentSalary;
        }   
        else {
            // returns to start for unsatisfactory
            System.out.println();
            System.out.println();
            System.out.println("Check your spelling and try again");
            main (args);
        }      

        newSalary = currentSalary + raise;

        // Print the results

        NumberFormat money = NumberFormat.getCurrencyInstance();
        System.out.println();
        System.out.println("Current Salary:       " + money.format(currentSalary));
        System.out.println("Amount of your raise: " + money.format(raise));
        System.out.println("Your new salary:     " + money.format(newSalary));
        System.out.println();
    }
}

Aucun commentaire:

Enregistrer un commentaire