mardi 8 décembre 2015

program that adds 1, 2, or 3, until it reaches 21

I am making a program called "count 21". How it's supposed to work is, "Two people play the game of Count 21 by taking turns entering a 1, 2, or 3, which is added to a running total. The player who adds the value that makes the total exceed 21 loses the game. Create a game of Count 21 in which a player competes against the computer, and program a strategy that always allows the computer to win. On any turn, if the player enters a value other than 1, 2, or 3, force the player to reenter the value." I am having trouble figuring out how I should do this, this is what I have so far:

import javax.swing.JOptionPane;
import java.util.Scanner;

public class Count21 {

public static void main(String[] args) {

    Scanner scan = new Scanner(System.in);

    int x; //running total
    int y; //input num
    String strInput = "";
    String message = "";
    String answer = "";

    do {
    strInput = JOptionPane.showInputDialog(null, "Welcome to Count 21. \n In this game you will play against "
            + "the computer and add the numbers 1, 2, or 3 together. \n Whoever pushes the "
            + "numbers over 21 loses. \n Do you want to add 1, 2, or 3? "
            + "(please enter the number you choose.");
    y = Integer.parseInt(strInput);
    x++; 
    if (y == 1) {JOptionPane.showMessageDialog(null, "You chose the number 1."
            + " 1 will be added to the running total of" + (x + 1) +" .");
    }
    else if (y == 2) {JOptionPane.showMessageDialog (null, "You chose the number 2."
           + "2 will be added to the running total of" + (x + 2) + " .");
    }
    else if (y == 3) {JOptionPane.showMessageDialog (null, "You chose the number 3."
            + "3 will be added to the running total of" + (x + 3) + " .");
    }
    else{ 
        JOptionPane.showMessageDialog(null, "You didn't type a valid number, please try again. \n");
    }
    }
    while (x > 21);
    }
}

After the program runs and the user types in the number they chose the program ends. This is all I have so far, but I am stuck on how to keep the number's from the user adding until it reaches 21. I also am unsure of how to make the computer win the game. I think I should be using a for loop? Any advice or comments are greatly appreciated. I apologize if my code or question is unclear.

Aucun commentaire:

Enregistrer un commentaire