I'm have just begun learning java and have been asked to create a program which:
Assigns 2 Arrays: Suit, Rank
Uses the Math.random class to determine the cards drawn. (I realize that this isn't a very realistic approach to how cards are drawn.)
I ran into troubles when I tried to add the option for the user to choose to draw a new hand.
For some reason the compiler will run, but when I go to ask for a new hand I get the message: "static error: undefined name 'yes' "
My Code before fix
import java.util.Scanner; public class exercise5{ public static void main(String[] args){ Scanner input = new Scanner(System.in); String again; do{ System.out.println("How many cards would you like?"); int counter = input.nextInt(); String[] suit = {"Diamonds", "Clubs", "Hearts", "Spades"}; String[] rank = {"Ace", "King", "Queen", "Jack", "10", "9", "8", "7", "6", "5", "4", "3", "2", "1"}; while (counter > 0){ double rand1 = Math.random() * 4; int ran1 = (int)rand1; double rand2 = Math.random() * 14; int ran2 = (int)rand2; if (rand1 >= 3.9 || rand2 >= 13.9) System.out.println("You got a joker!!!"); else System.out.println(rank[ran2]+ " of " + suit[ran1]); counter --; } System.out.println("Would you like a new hand? "); again = input.nextLine(); }while (again.startsWith("y") || again.startsWith("Y")); } }
I have found that assigning a new Scanner just before my do-while condition will fix my program. I am looking for a reason as to why. I'm not sure I understand what is happening. If anyone could help me out, it would be greatly appreciated.
My Code After Fix
import java.util.Scanner; public class exercise5{ public static void main(String[] args){ Scanner input = new Scanner(System.in); String again; do{ System.out.println("How many cards would you like?"); int counter = input.nextInt(); String[] suit = {"Diamonds", "Clubs", "Hearts", "Spades"}; String[] rank = {"Ace", "King", "Queen", "Jack", "10", "9", "8", "7", "6", "5", "4", "3", "2", "1"}; while (counter > 0){ double rand1 = Math.random() * 4; int ran1 = (int)rand1; double rand2 = Math.random() * 14; int ran2 = (int)rand2; if (rand1 >= 3.9 || rand2 >= 13.9) System.out.println("You got a joker!!!"); else System.out.println(rank[ran2]+ " of " + suit[ran1]); counter --; } Scanner in = new Scanner(System.in); System.out.println("Would you like a new hand? "); again = in.nextLine(); }while (again.startsWith("y") || again.startsWith("Y")); } }