为什么charAt和String.valueOf的比较在它们是相同的值时才返回true?

时间:2015-12-01 04:07:07

标签: java cookies

这是我的计划:

import java.util.Scanner;
public class Lottery
{
public static void main(String[] args)
{
    //declare and initialized variables and objects
    Scanner input = new Scanner(System.in);

    String lotteryNum = "";
    String userGuess = "";

    //Generate a 3-digit "lottery" number composed of random numbers
    int num1 = (int)(Math.random()*10);
    int num2 = (int)(Math.random()*10);
    int num3 = (int)(Math.random()*10);
    //Simulate a lottery by drawing one number at a time and 
    //concatenating it to the string
    String c1 = String.valueOf(num1);
    String c2 = String.valueOf(num2);
    String c3 = String.valueOf(num3);
    lotteryNum = (c1+c2+c3);
    //Identify the repeated steps and use a for loop structure
    //Input: Ask user to guess 3 digit number
    System.out.println("WINNER:"+lotteryNum+" Please enter your three numbers (e.g. 123): ");
    userGuess = input.next();
    System.out.println(c1.equals(userGuess.charAt(0)));
    System.out.println(userGuess.charAt(0) +"   " + userGuess.charAt(1) + "     " + userGuess.charAt(2) + "\n" + c1 + "\t"+c2+"\t"+c3);;
    if (c1.equals(userGuess.charAt(0)) && c2.equals(userGuess.charAt(1)))
        System.out.println("Winner: "+ lotteryNum+"\nCongratulations, the front pair matched.");
    else if (c2.equals(userGuess.charAt(1)) && c3.equals(userGuess.charAt(2)))
        System.out.println("Winner: "+ lotteryNum+"\nCongratulations, the end pair matched.");
    else if (c1.equals(userGuess.charAt(0)) && c2.equals(userGuess.charAt(1)) && c3.equals(userGuess.charAt(2)))
        System.out.println("Winner: "+ lotteryNum+"\nCongratulations, both pairs matched.");
    else 
                System.out.println("Winner: "+ lotteryNum+"\nSorry, no matches. You only had \n one chance out of 100 to win anyay.");

} //end main

} //结束类彩票

由于某种原因,具有逻辑的行如:System.out.println(c1.equals(userGuess.charAt(0))); 特别是返回false,即使用户输入相同的值,即String.valueOf(num1)与userGuess.charAt(0)的值相同,我甚至将它们都视为字符串,但它仍然返回false。这是为什么?非常感谢所有帮助!

2 个答案:

答案 0 :(得分:2)

因为String不是char

if (c1.equals(String.valueOf(userGuess.charAt(0))) 
        && c2.equals(String.valueOf(userGuess.charAt(1))))

更短的

if (c1.charAt(0) == userGuess.charAt(0) && c2.charAt(0) == userGuess.charAt(1))

答案 1 :(得分:1)

userGuess.charAt(0)返回char

c1 is String

可以按照建议使用String.valueOf

您也可以使用Character.toString(char);

System.out.println(c1.equals(Character.toString(userGuess.charAt(0))));

我们需要转换String to charchar to String,然后比较