0

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!");
     }
Tia Rojas
  • 37
  • 3
  • I suggest adding `println()` statements for your variables to see what is happening. Read [this article](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/) for more debuging tips. – Code-Apprentice May 17 '21 at 04:56
  • Does this answer your question? [How do I compare strings in Java?](https://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java) – maloomeister May 17 '21 at 05:30

2 Answers2

0

Hi your using == operator for a string comparison instead you should use equals method of string class

vote.equals("A")

0

Strings cannot be compared in the same way two integers or floating point numbers would be compared. These two lines don't work as expected.

if (vote == "A") 
else if (vote == "B")

Instead, change them to

if (vote.equals("A"))
else if (vote.equals("B"))

String.equals(Object) is a built in function to check if a String is equal to the object passed. Another method that can used is String.compareTo(String) which you can read about

Cheers!

ram
  • 437
  • 2
  • 12