dimanche 16 mai 2021

How do I output the correct print statement based on the values of certain variables?

I am new to Java so I am doing practice problems. This problem requires an election result to be outputted, but no matter what candidates the user inputs a vote for, it will always output the print statement claiming it is a tie. (Even if candidate A has more votes that candidate B or vice versa, it will always say it is a tie).

//VOTE COUNT 
    Scanner inputs = new Scanner(System.in);
    
    //getting total number of votes from user 
    System.out.println("Enter the total number of votes in the election.");
    int voteNum = inputs.nextInt();
    
    //defining the two different votes for the two candidates
    int voteA = 0;
    int voteB = 0;
    
    //collecting each vote one at a time from the user 
    for (int i = 0; i < voteNum; i++) {
        
        System.out.println("Do you want to vote for candidate A or B? Enter A or B (Must be a capital letter).");
        String vote = inputs.next();
        
        //adding to candidate A and B's total votes depending on the vote
        if (vote == "A") {
            
            voteA = voteA + 1;
        }
        
        else if (vote == "B") {
            
            voteB = voteB + 1;
        }
        
    }
    
     //displaying the final result of the election 
     if (voteA > voteB) {
         
         System.out.println("The election winner is candidate A!");
     }
     
     else if (voteB > voteA) {
         
         System.out.println("The election winner is candidate B!");
     }
     
     else {
         
         System.out.println("Candidate A and candidate B have tied!");
     }

Aucun commentaire:

Enregistrer un commentaire