gpt4 book ai didi

java - 当 charAt 和 String.valueOf 的值相同时,为什么它们的比较不返回 true?

转载 作者:行者123 更新时间:2023-12-01 21:58:39 25 4
gpt4 key购买 nike

这是我的程序:

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
}//end class Lottery

出于某种原因,这些行的逻辑如下:

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

特别返回false,即使用户输入相同的值,即String.valueOf(num1)userGuess.charAt(0)相同的值),我什至将它们都视为字符串,但它仍然返回 false。这是为什么?

最佳答案

因为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))

关于java - 当 charAt 和 String.valueOf 的值相同时,为什么它们的比较不返回 true?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34012418/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com