【问题标题】:How do I output the correct print statement based on the values of certain variables?如何根据某些变量的值输出正确的打印语句?
【发布时间】:2021-08-06 09:21:30
【问题描述】:

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

【问题讨论】:

标签: java if-statement variables input output


【解决方案1】:

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

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

相反,将它们更改为

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

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

干杯!

【讨论】:

    【解决方案2】:

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

    vote.equals("A")

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-02-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-01
      • 2021-05-03
      相关资源
      最近更新 更多