How do you make the player play for a random number of match and then end the game with all the score?
I'm trying to do a loop that let a player play a number of matches and ask at the end if still want to play or not.
public class RockPaperScissors {
public static void main(String[] args) {
Random rand = new Random();
Scanner sc = new Scanner(System.in);
Scanner playername = new Scanner(System.in);
String name;
int playerChoose;
int aiChoose;
String match = "";
int matchCount = 1;
int matchLimit = 10;
boolean endMatch = true;
int Rock = 1, Paper = 2, Scissor = 3;
//Player choose how many round.
int max = 10;
int min = 1;
int randomNum = rand.nextInt((max - min) + 1) + 1;
// Computer random choose Rock, Paper or Scissor.
int maxme = 3;
int minme = 1;
aiChoose = rand.nextInt((maxme - minme) + 1) + 1;
System.out.println("Hi, what is your name?");
name = playername.next();
System.out.println("Hi, " + name);
System.out.println("Let's play Rock, Paper and Scissor!!");
System.out.println("How many round do you want to play?");
// loop match I'm doing something wrong
while (!match.equals(randomNum)) {
System.out.println(randomNum + " match");
if (randomNum == 0)
{
System.out.println("Chooses between Rock - 1, Paper - 2 and Scissor - 3? ");
}
playerChoose = sc.nextInt();
//Check Player choise for Rock Paper and Scissor
if (playerChoose < 1 || playerChoose > 3) {
System.out.println("Wrong Choise");
System.exit(0);
}
System.out.println(aiChoose);
if (playerChoose == aiChoose) {
System.out.println("We tie");
} else if ((playerChoose == Rock && aiChoose == Scissor) || (playerChoose == Scissor && aiChoose == Paper) || (playerChoose == Paper && aiChoose == Rock));
{
System.out.println("You win");
}
}
}
If you want to do a specific amount of round you can do it with a for loop:
for(int i = 0; i < numberOfMatches; i++){
}
If you want to let the user decide if he wants to play you could do something like this:
while(true){
//all the things before
System.out.println("Do you still want to play? ")
if(sc.next.equals("No")){
break;
}
}
Related
I try to figure out which line I miss the "{". it tells me in the 3rd line I expected to put "{" symbol and I did but still gives me an error.
this is my code:
package lab22;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner Sc = new Scanner(System.in);
int choice = 0;
int coffee = 0;
int tea = 0;
int coke = 0;
int orange = 0;
int pnum = 1;
System.out.println("Baverage:\n1. Coffee\n2. Tea\n3. Coke\n4. Orange Juice");
do{
System.out.println("Please input the favourite beverage of person #"+ String.valueOf(pnum)+": Choose 1, 2, 3, or 4 from the above menu or -1 to exit");
choice = Sc.nextInt();
if (choice == 1){
coffee += 1;
} else if (choice == 2){
tea += 1;
} else if (choice == 3){
coke += 1;
} else if (choice == 4){
orange += 1;
} else if (choice != -1){
System.out.println("Please enter valid input!");
continue;
}
pnum += 1;
} while(choice != -1);
System.out.println(" Beverage Number of Votes");
System.out.println(" *************************");
System.out.println("Coffee: "+ String.valueOf(coffee));
System.out.println("Tea: "+ String.valueOf(tea));
System.out.println("Coke: "+ String.valueOf(coke));
System.out.println("Orange Jiuce: "+ String.valueOf(coffee));
}
}
can someone help what did i miss?
Before starting your code you need to first understand basic naming conventions in Java.
As far as error concern you need to remove that .java from class name to get rid of the error.
Additionally:
a) Class name should start with Capital Letter (CamelCase).
b) Variable name should start with Small Letter (CamelCase).
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int choice = 0;
int coffee = 0;
int tea = 0;
int coke = 0;
int orange = 0;
int pnum = 1;
System.out.println("Baverage:\n1. Coffee\n2. Tea\n3. Coke\n4. Orange Juice");
do {
System.out.println("Please input the favourite beverage of person #" + String.valueOf(pnum)
+ ": Choose 1, 2, 3, or 4 from the above menu or -1 to exit");
choice = sc.nextInt();
if (choice == 1) {
coffee += 1;
} else if (choice == 2) {
tea += 1;
} else if (choice == 3) {
coke += 1;
} else if (choice == 4) {
orange += 1;
} else if (choice != -1) {
System.out.println("Please enter valid input!");
continue;
}
pnum += 1;
} while (choice != -1);
System.out.println(" Beverage Number of Votes");
System.out.println(" *************************");
System.out.println("Coffee: " + String.valueOf(coffee));
System.out.println("Tea: " + String.valueOf(tea));
System.out.println("Coke: " + String.valueOf(coke));
System.out.println("Orange Jiuce: " + String.valueOf(coffee));
}
}
As I have changed the class name, probably you would need to rename your file also containing the class as Main.java.
This is my nim game (goal is dont be the last person to pick up marbles), can someone please guide me. In playing the game, I have just one question
How can I keep track of whose turn it is, I guess if I can keep track of that I can monitor my remainingMarbles. This is the crux of my code. Please help
public class Nim{
public static void main(String[] args)
{
System.out.println("************** Welcome to the game of Nim *******************");
System.out.println("The object of this game is to make me take the last marble off the table");
System.out.println("You must take at least 1 and you can take up to 3 marbles on your turn");
System.out.println("You can go first");
Scanner scan = new Scanner(System.in);
final int MARBLES = 13;
int remainingMarbles;
String input;
do {
//boolean whoseTurn = true;
remainingMarbles = MARBLES;
System.out.println("There are " + MARBLES + " marbles on the table");
while (remainingMarbles > 0){
remainingMarbles -= getUserSelection();
System.out.println("There are " + (remainingMarbles -= getComputerSelection()) + " marble(s) on the table.");
}
if (1 <= remainingMarbles && remainingMarbles <= 2 && remainingMarbles < 0) {
System.out.println("Congratulations! you won!");
System.out.println("Want to play again? y/n");
input = scan.nextLine();
input = input.toLowerCase();
} else
System.out.println("Hard luck you lose!");
System.out.println("Want to play again? y/n");
input = scan.nextLine();
input = input.toLowerCase();
}while (input.charAt(0) == 'y');
}
private static int getUserSelection()
{
Scanner scan = new Scanner(System.in);
do {
System.out.println("Enter 1, 2 or 3");
int userSelection = scan.nextInt();
if (isValidMove(userSelection)){
return userSelection;
}
else {
System.out.println("Not a valid entry");
}
}while (true);
}
private static boolean isValidMove(int input)
{
return 1 <= input && input <= 3;
}
private static int getComputerSelection ()
{
Random generator = new Random();
int computerSelection = 1 + generator.nextInt(3);
System.out.println("The computer chooses " + computerSelection);
return computerSelection;
}
}
First, make a boolean before the loop.
boolean whoseTurn = true;
When the variable is true it's the first player's turn, otherwise the second player's turn.
Now inside the while loop we change the variable at the end of every repetition:
whoseTurn = !whoseTurn;
(Which is a faster way of this)
if(whoseTurn) whoseTurn = false;
else whoseTurn = true;
To conclude, you should do something like that:
...
boolean whoseTurn = true;
while(remainingMarbles > 0){
remainingMarbles -= getUserSelection();
System.out.println("There are " + (remainingMarbles -= getComputerSelection()) + " marble(s) on the table.");
whoseTurn = !whoseTurn;
}
...
This question already has answers here:
How do I generate random integers within a specific range in Java?
(72 answers)
Closed 3 years ago.
I am creating a random number generator multiplayer game (LAN).
I need help on how to create a code to make each player receive their own random number, and whenever one player guesses a code, the next turn would be a new player. Similar to where the output would show the following,
Fred, Please Guess the random number (integers only!!): 5
TOO LOW
Tom, Please Guess the random number (integers only!!): 95
TOO HIGH
John, Please Guess the random number (integers only!!): 50
TOO LOW
Then when a player guesses correctly, their turn is skipped and the game will end when all players have guessed their numbers, showing the number to guesses each person had, as well as the numbers they guessed previously.
This is what I have so far:
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner keyboard = new Scanner(System.in);
Random myRand = new Random();
ArrayList<Integer> guessedNumbers = new ArrayList();
int x = 0;
int players = 0;
System.out.println("how many players are there?:");
players = checkint(players);
int arraySize = guessedNumbers.size();
int[] numPlayers = new int [players];
boolean play = true;
boolean validGuess = true;
String [] pNames = new String[players];
for (int i = 0; i<players; i++) {
System.out.println("New player, what is your name?:");
pNames[i] = keyboard.nextLine();
}
while(play) {
int randNum = myRand.nextInt(100) + 1;
int numOfGuesses = 0;
do {
System.out.println("Enter what you think the number is between 0 and 100!:");
x= checkint(x);
guessedNumbers.add(x);
if (x < 0) {
System.out.println("we don't accept negative numbers");
if (x > 100) {
System.out.println("that number is above the random number generator range");
}
}
numOfGuesses++;
if (x == randNum) {
System.out.println("that's correct!");
System.out.println("It took you " + numOfGuesses + " tries!");
System.out.print("these are all the numbers you guessed:");
for(int count=0; count<guessedNumbers.size(); count++){
System.out.print(guessedNumbers.get(count) + ",");}
System.out.println("");
boolean playError = true;
//if ("Yes".equals(answer)) {
do {
System.out.println("Would you like to play again: Yes or No");
String answer = keyboard.nextLine();
if (answer.compareToIgnoreCase("yes") == 0) {
play = true;
playError = false;
} else if (answer.compareToIgnoreCase("no") == 0) {
play =false;
playError = false;
System.out.println("Thank you for playing");
} else {
//you messed up
System.out.println("You answer was invalid");
playError = true;
}
} while (playError == true);
}
else if
(x>randNum)
System.out.println("Lower than that!");
else if
(x<randNum)
System.out.println("Higher than that!");
} while (x != randNum);
}}
}
static int checkint(int a) {
int enteredNumber = 0;
Scanner myScanner = new Scanner(System.in);
boolean numberError = false;
String enteredString = "";
do {
try {
enteredString = myScanner.next(); //Read into a string
enteredNumber = Integer.parseInt(enteredString.trim()); //then cast as a integer
numberError = false; //if we haven't bailed out, then the number must be valid.
} catch(Exception e) {
System.out.println("Your entry: \"" + enteredString + "\" is invalid...Please try again");
numberError = true; //Uh-Oh...We have a problem.
}
} while (numberError == true ); //Keep asking the user until the correct number is entered.
return enteredNumber;
}
}
You are doing simple things in a complex way, however, my code can still be replaced by a compressed version but you can understand this better. Following code is doing exactly what you want it to do. I've:
Created Player class, so each player will keep record of guessedNumbers, Number of Guesses and it's name.
You don't have to make tons of variables like pName[], play, validGuesses etc...
I have changed some of the If-Conditions and removed the outer while-loop
Added new round concept, so whenever a player guessed the number, the number got changed.
and much more ....
UPDATED Code: Now each Player has a different random number to guess.
import java.util.*;
public class GuessNumber
{
public static void main(String[] args)
{
// TODO Auto-generated method stub
Scanner keyboard = new Scanner(System.in);
Random myRand = new Random();
ArrayList<Player> players = new ArrayList<Player>();
int x = 0;
System.out.println("how many players are there?:");
int noPlayer = checkint();
boolean validGuess = true , playError = true;
for (int i = 0; i<noPlayer; i++)
{
System.out.println("New player, what is your name?:");
players.add(new Player (keyboard.nextLine()));
}
for (int i = 0; i<noPlayer; i++)
{
players.get(i).number = myRand.nextInt(100) + 1;
}
int i =0; // for chossing different player each time
do
{
System.out.printf(players.get(i).name + " enter what you think the number is between 0 and 100!: ");
x= checkint();
players.get(i).guessedNumbers.add(x);
players.get(i).numOfGuesses++;
if (x == players.get(i).number)
{
System.out.println("That's correct!");
System.out.println("It took you " + players.get(i).numOfGuesses + " tries!");
System.out.print("These are all the numbers you guessed: ");
System.out.println(players.get(i).guessedNumbers);
do
{
System.out.println("Would you like to play again: Yes or No");
String answer = keyboard.nextLine();
if (answer.compareToIgnoreCase("yes") == 0)
{
playError = false;
players.get(i).number = myRand.nextInt(100) + 1; // creates a new random number for second round of the game
System.out.println("\n\n************ " +players.get(i).name + " WON ********");
System.out.println("\n************* SECOND ROUND STARTS **********");
}
else if (answer.compareToIgnoreCase("no") == 0)
{
playError = false;
System.out.println("Thank you for playing");
System.out.println("\n\n************ " +players.get(i).name + " WON ********");
System.out.println("\n************* SECOND ROUND STARTS **********");
players.remove(i);
}
else
{
System.out.println("You answer was invalid");
playError = true;
}
} while (playError);
}
else if (x>players.get(i).number)
System.out.println("Lower than that!");
else if (x<players.get(i).number)
System.out.println("Higher than that!");
if(i == noPlayer-1 || !(playError))
i = 0;
else
i++;
}while (players.size() > 0);
System.out.println("\n\n******************** Every Body Guessed Their Numbers ******************");
}
static int checkint()
{
int enteredNumber = 0;
Scanner myScanner = new Scanner(System.in);
boolean numberError = false;
do
{
try
{
enteredNumber = Integer.parseInt(myScanner.next().trim());
if (enteredNumber < 0 || enteredNumber > 100)
{
System.out.println("Either you entered a negative number or number is above the random number generator range");
numberError = true;
}
else
numberError = false; //if we haven't bailed out, then the number must be valid.
} catch(Exception e)
{
System.out.println("Your entry is invalid...Please try again");
numberError = true; //Uh-Oh...We have a problem.
}
} while (numberError); //Keep asking the user until the correct number is entered.
return enteredNumber;
}
}
// now each player would have its own record.
class Player
{
int numOfGuesses= 0;
ArrayList<Integer> guessedNumbers = new ArrayList<Integer>();
String name = "";
int number = 0;
public Player(String nam)
{
name = nam;
}
}
NOTE: I've added some new lines to output on the screen , once a players wins and want to play again or not. I recommend you to compare your code with mine, so that you'll get a better understanding of your approach vs mine. Do let me know if you find something difficult to understand.
Just use the Random class:
Random ran = new Random();
// Assumes max and min are non-negative.
int randomInt = min + ran.nextInt(max - min + 1);
I referenced here.
How do I generate random integers within a specific range in Java?
Our task was to create a guessing game, where the computer would generate a number and the user was prompted to guess. We were to create a method to play only one game, and then create a while loop in the main to make the game playable again. In the end, we need to show statistics. I'm having trouble with showing the "best game." That is a game where the amount of guesses is the least.
Here is the code:
import java.util.Random;
import java.util.Scanner;
public class GuessingGame {
public static final int MAX = 100;
// This is the main. Here we can see a do/while loop
// and a few variables that were created to compliment it.
public static void main(String[] args) {
Random rand = new Random();
Scanner console = new Scanner(System.in);
intro();
String s = "";
int totalGames = 0;
int totalGuess = 0;
do {
totalGuess = game(console);
System.out.print("Do you want to play again? ");
s = console.next();
totalGames++;
} while (s.equals("y") || s.equals("Y") || s.equals("Yes") ||
s.equals("yes") || s.equals("Yes"));
totalGuess = totalGuess;
statistics(totalGames, totalGuess);
}
// This method prints out the intro.
public static void intro() {
System.out.println("This program allows you to play a guessing
game.");
System.out.println("I will think of a number between 1 and");
System.out.println(MAX + " and will allow you to guess until");
System.out.println("you get it. For each guess, I will tell you");
System.out.println("whether the right answer is higher or lower");
System.out.println("than your guess.\n ");
}
// This method plays the game only once. It's later used in the main.
// Returns the
// number of guesses for one game.
public static int game(Scanner console) {
Random rand = new Random();
int random = rand.nextInt(MAX) + 1;
System.out.println("I'm thinking of a number between 1 and " + MAX + "
... (it's " + random + " )");
System.out.print("Your guess? > ");
int guess = console.nextInt();
int count = 0;
do {
if ((random - guess) > 0) {
System.out.println("It's higher.");
System.out.print("Your guess? > ");
guess = console.nextInt();
count++;
}
else if ((random - guess) < 0) {
System.out.println("It's lower.");
System.out.print("Your guess? > ");
guess = console.nextInt();
count++;
}
else if (random == guess) {
count++;
}
} while (random != guess);
if (count == 1) {
System.out.println("You got it right on the first guess!!");
}
else {
System.out.println("You got it right in " + count + " guesses.");
}
return count;
}
// This method prints out the statistics.
public static void statistics(int x, int y) {
System.out.println("total games = " + x);
System.out.println("total guesses = " + (y));
System.out.println("guesses/game = ");
System.out.println("best game = ");
}
}
Have a look when totalGuess is assigned:
public static void main(String[] args) {
Random rand = new Random();
Scanner console = new Scanner(System.in);
intro();
String s = "";
int totalGames = 0;
int totalGuess = 0;
// ^ Initialized to zero
do {
totalGuess = game(console);
// ^ Assigned (not added) to the return value from game.
// Did you mean: totalGuess += game(console); ?
System.out.print("Do you want to play again? ");
s = console.next();
totalGames++;
} while (s.equals("y") || s.equals("Y") || s.equals("Yes") ||
s.equals("yes") || s.equals("Yes"));
totalGuess = totalGuess;
// ^ Assigned to itself. No action.
statistics(totalGames, totalGuess);
}
For my assignment I'm supposed make the program rock paper scissors which I figured that out my main problem is I can't get the program to play again right or get the program to calculate the game scores correctly pleas help I'm going crazy trying to figure this out?!
//Tayler Dorsey
import java.util.Random;
import java.util.Scanner;
public class PRS {
static Scanner keyboard = new Scanner(System. in );
public static void instructions() {
System.out.println("This is the popular game of paper, rock, scissors. Enter your\nchoice by typing the word \"paper\", the word \"rock\" or the word\n\"scissors\". The computer will also make a choice from the three\noptions. After you have entered your choice, the winner of the\ngame will be determined according to the following rules:");
System.out.println("Paper wraps rock (paper wins)\nRock breaks scissors (rock wins)\nScissors cuts paper (scissors wins)");
System.out.println("If both you and the computer enter the same choice, then the game is tied.");
}
public static int playGame() {
int ties = 0, wins = 0, losts = 0;
String userchoice, computerchoice;
System.out.println("Enter your choice: ");
userchoice = keyboard.next();
computerchoice = computerChoose();
System.out.println("You entered: " + userchoice);
System.out.println("Computer choose: " + computerchoice);
if ((userchoice.equals("paper") && computerchoice.equals("paper")) || (userchoice.equals("rock") && computerchoice.equals("rock")) || (userchoice.equals("scissors") && computerchoice.equals("scissors"))) {
System.out.println("IT'S A TIE!");
ties++;
return 3;
} else if ((userchoice.equals("paper") && computerchoice.equals("rock")) || (userchoice.equals("rock") && computerchoice.equals("scissors")) || (userchoice.equals("scissors") && computerchoice.equals("paper"))) {
System.out.println("YOU WIN!");
wins++;
return 1;
} else {
System.out.println("YOU LOSE!");
losts++;
return 2;
}
}
public static String computerChoose() {
Random generator = new Random();
String[] answer = new String[3];
answer[0] = "paper";
answer[1] = "rock";
answer[2] = "scissors";
return answer[generator.nextInt(3)];
}
public static void main(String[] args) {
String play;
Scanner keyboard = new Scanner(System. in );
System.out.println("The Game of Paper, Rock, Scissors");
System.out.println("Do you need instructions (y or n)?");
String help = keyboard.nextLine();
if (help.equals("y")) instructions();
int result = playGame();
System.out.println("Play again (y or n)?");
play = keyboard.nextLine();
if (play.equals("y"));
else {
int count = 0, wins = 0, losts = 0, ties = 0;
System.out.println("Games played: " + count);
System.out.println("Wins for you: " + wins);
System.out.println("Wins for me: " + losts);
System.out.println("Tied games: " + ties);
}
do {} while (play == "y"); {
playGame();
int count = 0;
count++;
}
}
}
There are two issues here:
The code isn't inside the do-while loop, it's after it.
String equality should be checked with equals not with ==.
So:
int count = 0;
do { // Note the code inside the do-while block
playGame();
count++;
} while (play.equals("y")); // Note the use of equals
Do the following:
do {
play = keyboard.nextLine();
if (play.equals("y")){
}
else {
int count = 0, wins = 0, losts = 0, ties = 0;
System.out.println("Games played: " + count);
System.out.println("Wins for you: " + wins);
System.out.println("Wins for me: " + losts);
System.out.println("Tied games: " + ties);
}
} while (play.equals("y"));
In order to calculate the games scores make those variable global.
public class PRS {
static Scanner keyboard = new Scanner(System. in );
int ties = 0, wins = 0, losts = 0;