我正在做一个抛硬币游戏程序。但是我在这部分 [ (if Guess==i) {.我该如何解决这个问题?
I am doing a coin toss game program. But i am having an error in this portion [ (if Guess==i) {. How do I solve this?
import java.util.Scanner;
public class CoinTossGame {
public static void main(String[] args) {
System.out.println("A coin is tossed!");
int Heads=0, Tails=1;
Scanner input = new Scanner (System.in);
System.out.println("Enter your guess."); //Starting message
System.out.println("Press 0 for Heads and 1 for Tails."); //prompts user to enter the input
String Guess = input.nextLine( ); //Stored input in variable
int i= (int) (Math.random () * 2); //Store random number
if (Guess==i) {
System.out.println("Nice guess.\nYou are really guenius!!");
}
else {
System.out.println("Opps! wrong guess.");
System.out.println("Try again.");
System.out.println("Thank you.");
}
}
}
您将整数与字符串进行比较。那显然不行。将 Guess
转换为 int
或将 i
转换为 String
。
您正在将 int
与 String
进行比较:if (Guess==i)
你需要的是 2 个整数:
int guess = Integer.parseInt(input.nextLine()); //or int guess = input.nextInt();
int i = (int) (Math.random () * 2); //Store random number
if (guess==i) {
System.out.println("Nice guess.\nYou are really guenius!!");
}
或 2 Strings
:
String guess = input.nextLine();
String i = ((int) (Math.random () * 2)) + "";
if (guess.equals(i)) { // for object use equals() and not ==
System.out.println("Nice guess.\nYou are really guenius!!");
}
import java.util.Scanner;
public class CoinTossGame {
public static void main(String[] args) {
System.out.println("A coin is tossed!");
int Heads=0, Tails=1;
Scanner input = new Scanner (System.in);
System.out.println("Enter your guess."); //Starting message
System.out.println("Press 0 for Heads and 1 for Tails."); //prompts user to enter the input
String Guess = input.nextLine( ); //Stored input in variable
int i= (int) (Math.random () * 2); //Store random number
if (Guess==i) {
System.out.println("Nice guess.\nYou are really guenius!!");
}
else {
System.out.println("Opps! wrong guess.");
System.out.println("Try again.");
System.out.println("Thank you.");
}
}
}
您将整数与字符串进行比较。那显然不行。将 Guess
转换为 int
或将 i
转换为 String
。
您正在将 int
与 String
进行比较:if (Guess==i)
你需要的是 2 个整数:
int guess = Integer.parseInt(input.nextLine()); //or int guess = input.nextInt();
int i = (int) (Math.random () * 2); //Store random number
if (guess==i) {
System.out.println("Nice guess.\nYou are really guenius!!");
}
或 2 Strings
:
String guess = input.nextLine();
String i = ((int) (Math.random () * 2)) + "";
if (guess.equals(i)) { // for object use equals() and not ==
System.out.println("Nice guess.\nYou are really guenius!!");
}