所以我试图制作一个基本的游戏,有人可以进入头部或尾部,然后将该值转换为数字,然后给出答案,好像它是对的。那么如何将头转换为1并将尾部转换为0
public static void main(String[]args){
int coin = (int)(Math.random() * 2+1);
Scanner input = new Scanner(System.in);
System.out.print("Do you think the coin will be heads or tail");
String guess = input.next();
if (guess != "heads" || guess !="tails")
System.out.println(" please enter a heads or tails");
System.out.print("Do you think the coin will be heads or tail");
if (guess == "heads")
int guess = 1;
else if(guess == "tails")
int guess = 0 ;
else
System.out.println(" please enter a heads or tails");
if (guess == coin)
System.out.println("Got it");
else if (coin == 0)
System.out.println("Sorry, it is a head");
else
System.out.println("Sorry, it is a tail");
}
答案 0 :(得分:0)
那么如何将磁头转换为1并将尾部转换为0?
int guessValue = 0;
if (guess.equals("heads")) {
guessValue = 1;
}
答案 1 :(得分:0)
你不会想要"转换"将值转换为数字。您应该使用单独的变量来保存整数值。我想你也希望这是"连续",在这种情况下,你想要一个while
循环来继续获取值:
while(true){
int coin = (int)(Math.random() * 2+1);
System.out.print("Do you think the coin will be heads or tail");
String guess = input.nextLine(); // nextLine should work fine
while(!guess.equals("heads") && !guess.equals("tails")){ // loop until you get a correct input
System.out.println(" please enter a heads or tails");
guess = input.nextLine();
}
int choice = 0;
if (guess.equals("tails")) // use .equals(yourString) to compare values of strings
choice = 1; // only change to 1 if it's tails, otherwise it's heads
if (choice == coin)
System.out.println("Got it!");
else if (coin == 0)
System.out.println("Sorry, it is a head");
else
System.out.println("Sorry, it is a tail");
}
您还可以检查输入是否要再次播放,然后使用break
声明,如果他们表示他们没有。