如何根据某些变量的值输出正确的打印语句?

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

我是 Java 的新手,所以我正在做练习题。这个问题需要输出一个选举结果,但是无论用户输入的是什么候选人的选票,它总是会输出打印语句声称它是平局。 (即使候选人 A 的票数比候选人 B 多,反之亦然,它总是会说这是平局)。

//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!");
     }

您好,您使用 == 运算符进行字符串比较,您应该使用字符串的 equals 方法 class

vote.equals("A")

不能像比较两个整数或浮点数那样比较字符串。这两行没有按预期工作。

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

改为

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

String.equals(Object) 是一个内置函数,用于检查字符串是否等于传递的对象。另一种可以使用的方法是String.compareTo(String),您可以阅读

干杯!