Issue
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!");
}
Solution
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!
Answered By - ram Answer Checked By - Candace Johnson (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.