Write a program to simulate a coin toss. First, ask the user to "call" or predict the toss. Next, let the user know you are tossing the coin. Then report whether the user was correct.
Example:
Please call the coin toss (h or t): h Tossing... The coin came up heads. You win!
This is about what I am supposed to do. This is the code I have so far:
package inClassCh4Sec8to9;
import java.util.Random;
import java.util.Scanner;
public class ClassCh4Sec8to9 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
while (true) {
System.out.print("Enter you guess (1 for heads, 0 for tails, 2 to quit):");
int call = input.nextInt();
int heads = 1;
int quit = 2;
int tails = 0;
if (call == quit) {
break;
} else if (call == heads) {
} else if (call == tails) {
} else {
System.out.println("invalid");
continue;
}
Random random = new Random();
int coinflip = random.nextInt(2);
if(call == coinflip){
System.out.println("Correct!");
}else{
System.out.println("Sorry, incorrect.");
}
}
}
}
My problems:
import java.util.Scanner;
public class A {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
while (true) {
System.out.print("Please call the coin toss (h or t): ");
String call = input.nextLine();
String heads = "h";
String tails = "t";
if(call==null || call.length() > 1){
break;
}
System.out.println("Tossing...");
int random=(int)(Math.random()*2);
if(random<1){ //assume that, if random variable is smaller than 1 then it is head. If bigger than 1 and smaller than 2, then tails.
if(heads.equals(call)){
System.out.println("The coin came up heads. You win!");
}
else{
System.out.println("Sorry, incorrect.");
}
}else{
if(tails.equals(call)){
System.out.println("The coin came up tails. You win!");
}
else{
System.out.println("Sorry, incorrect.");
}
}
}
}
}