I just started learning Java in a class. The assignment was to make a Rock, Paper and Scissors game, here is my source code. I turned this in already but have not received a grade.
package rockpaperscissors;
import java.util.Random;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// Create scanner input
Scanner input = new Scanner (System.in);
// Introduce user to game
System.out.println("Welcome to the Rock, Paper and Scissors game");
// Ask the user for their move
System.out.println("\nPlease select a move\nEnter 0 for Scissors, 1 "
+ "for Rock and 2 for Paper");
int userMove = input.nextInt();
// Ensure that userMove is between 0 and 2
if (userMove > 2 || userMove < 0) {
System.out.println("Invalid entry the result of this game will not "
+ "be accurate! Please retry using either 0 for Scissors, 1"
+ " for Rock and 2 for Paper\n");
}
// Generate computerMove using java.util.Random
// Create instance first
Random MyRandom = new Random();
//Now generate number
int computerMove = MyRandom.nextInt(3);
System.out.print("The computer played " + computerMove + "\nRemember"
+ " 0 stands for Scissors, 1 is for Rock and 2 is for paper\n");
// Determine draw result
if (userMove == computerMove) {
System.out.println("\nYou played " + userMove + ", The computer "
+ "played " + computerMove + " The game is a draw!");
}
// Determine computer win
else if(userMove == 0 && computerMove == 1) {
System.out.println("\nYou played " + userMove + ", The computer "
+ "played " + computerMove + " The Computer Wins!");
}
else if(userMove == 2 && computerMove == 0) {
System.out.println("\nYou played " + userMove + ", The computer "
+ "played " + computerMove + " The Computer Wins!");
}
else if(userMove == 1 && computerMove == 2) {
System.out.println("\nYou played " + userMove + ", The computer "
+ "played " + computerMove + " The Computer Wins!");
}
/* Determine User win, as no other moves can result in computer win all
other combinations will result in user win
*/
else {
System.out.print("\nYou played " + userMove + ", The computer "
+ "played " + computerMove + " You Win!");
}
}
}
I am having trouble on getting the program to re-ask for a number if the number is above 2 or below 0, it will say "Invalid entry the result will not be valid..." but it will still preform the rest of the program with an invalid number.
How can I make the program stop and prompt the user for a valid number and then preform the program? Additionally, this is the third program I have ever made so any other advice would be appreciated.
Thanks
What you want is to not do all the other code if your conditions are met.
Right now you are giving an error message when your conditions are met - but not stopping execution of the rest of the function.
you can just stop.
So - without telling you the exact answer... how do you exit from a function?
Do that just after the error message gets displayed and you will be fine.
However - if you want to continue fetching the user input until you meet the conditions... that requires a loop around the part that fetches and checks.
what loops do you know?
do you know one that lets you loop until you've met some condition?
you've got your condition already... now you just need to adapt a loop to let you do the code that you want - repeatedly - until that condition is met.
in pseudo code (ie this is not real java - you must translate):
some_loop do
fetch user input
give error message if its not ok
until (user input is ok)
Related
I have created a monopoly game, and the problem right now is that once I press "y" to buy a property, it prints out the previous lines again, rather than going straight through the loop.
if (board1[pos_l].getType().equals ("prop")) {
if (board1[pos_l].getAvail() == (true) && numClicks!=0) {
println (board1[pos_l].getName() + " is available for $" + board1[pos_l].getPrice() + ". Press y to buy.");
println("player 2 roll the die (a) if player 1 doesn't buy it");
println("");
if (key == 'y' ){
board1 [pos_l].setAvail(false);
board1[pos_l].setOwner (name1);
p1money = p1money - board1[pos_l].getPrice();
println("you have bought it! you now have " +p1money + ". player 2 press 'a' to roll the die.");
numClicks=0;
}
}
I expect the output to be "you have bought it! you now have $___ .....". Instead, it's printing out "board1[pos_l].getName() + " is available for $" + board1[pos_l].getPrice() + Press y to buy. player 2 roll the die (a) if player 1 doesn't buy it" again after I press y.
You're not telling it not to print out the lines when the user presses Y. You need to move those lines to an else block:
if (board1[pos_l].getAvail() == (true) && numClicks!=0) {
if (key == 'y' ){
board1 [pos_l].setAvail(false);
board1[pos_l].setOwner (name1);
p1money = p1money - board1[pos_l].getPrice();
println("you have bought it! you now have " +p1money + ". player 2 press 'a' to roll the die.");
numClicks=0;
} else {
println (board1[pos_l].getName() + " is available for $" + board1[pos_l].getPrice() + ". Press y to buy.");
println("player 2 roll the die (a) if player 1 doesn't buy it");
println("");
}
}
I have this celebrity guessing game where the user has to guess a celebrity’s name, given only a portion of the letters in the name.
I give the player the “clue” (e.g.rge oney) and read in their guess. The program should have a loop that allows them to keep guessing. If they guess incorrectly 3 times, give them a hint If they guess incorrectly a fourth time (after the hint), they lose the game (and you should tell them who the celebrity was).
I'm having trouble with the loop. this is what I have so far.
System.out.println("Celebrity Guessing Game");
String celeb = "John Lennon";
System.out.print("Choose your difficulty (easy/medium/hard): ");
String difficulty = input.nextLine();
int maxtry = 3;
if (difficulty.equals("easy"))
{
System.out.println("Here is your clue: " + celeb.substring(1, 4) + " " + celeb.substring(5,10));
}
else if (difficulty.equals("medium"))
{
System.out.println(("Here is your clue: " + celeb.substring(0, 3) + " " + celeb.substring(4,9)));
}
else if (difficulty.equals("hard"))
{
System.out.println(("Here is your clue: " + celeb.substring(2, 4) + " " + celeb.substring(5,7)));
}
System.out.print("What is your guess? ");
String guess1 = input.nextLine();
System.out.println("guess1 = " + guess1 + " celeb = " + celeb );
while (!guess1.equals(celeb) && maxtry == 3 ) {
if (!guess1.equals(celeb) && maxtry == 3) {
maxtry--;
System.out.println("Try Again." + " Number of guesses left : " + maxtry);
}
if (guess1.equals(celeb) || guess1.equals("john lennon")) {
System.out.println("Good Guess, you are correct!");
}
This is my output:
Celebrity Guessing Game
Choose your difficulty (easy/medium/hard): easy
Here is your clue: ohn Lenno
What is your guess? john lennon
guess1 = john lennon celeb = John Lennon
Try Again. Number of guesses left : 2
Good Guess, you are correct!
^ Why is it going through both if statements??
The problem is in checking condition. It have following problems:
It should be maxtry > 0 instead of maxtry == 3
Instead of equals() use equalsIgnoreCase()
Following is corrected code snippet:
while (!guess1.equalsIgnoreCase(celeb) && maxtry > 0 ) {
if (!guess1.equalsIgnoreCase(celeb) && maxtry > 0) {
maxtry--;
System.out.println("Try Again." + " Number of guesses left : " + maxtry);
}
Note: You are not reading input from user for other tries.
This question already has answers here:
Why do we need break after case statements?
(17 answers)
Closed 7 years ago.
first time poster, and newbie coder. I apologize for the mess of this code, still needs cleaning. However, I am having major issues with my switch. If I select case 1, it runs through case 1, then after completion, automatically runs through case 2, then case 3. Likewise, if I select case 2, after completion of case 2, it runs through case 3. Finally, my default isn't working either. When selecting anything other than 1, 2, or 3, all sorts of errors appear. Any help would be greatly appreciated!
Had a hard time searching for this complex issue!
switch(input3)
{
case 1 :
{
JOptionPane.showMessageDialog(null,"You have selected the Rock, Paper, Scissors Game\nThe program is now loading...\nProgram loaded successfully! Please press OK.");
JOptionPane.showMessageDialog(null,"Rock, Paper, Scissors Game... 3 Rounds!");
while(round<3) {
String UserInput = JOptionPane.showInputDialog("Rock, Paper, Scissors Game: Type Rock, Paper, or Scissors");
Random Game = new Random();
int Computer = 1+Game.nextInt(3);
int Scissors, Rock, Paper;
Rock = 1;
Paper = 2;
Scissors= 3;
if(UserInput.equals("Rock")) {
Player = 1;
}
if(UserInput.equals("Paper")) {
Player = 2;
}
if(UserInput.equals("Scissors")) {
Player = 3;
}
int random = (int)(Math.random() * 3);
String computerInput; // Computer's choice
if (random == 0)
computerInput = "rock";
else if (random == 1)
computerInput = "paper";
else
computerInput = "scissor";
while (Player > 3 || Player < 1) {
losses++;
round++;
System.out.println("Not a valid input! Computer wins");
System.out.println("Player has won " + wins + " times and the computer has won " + losses + " times");
}
//Establish tie scenarios using if statements
if(UserInput== computerInput){
JOptionPane.showMessageDialog(null,"Player has won " + wins + " times and the computer has won " + losses + " times");
round++;
}
//Winning scenerios
if(Player == Scissors)
if(Computer == Paper){
JOptionPane.showMessageDialog(null,"Scissors v Paper! Player Wins!");
wins++;
round++;
JOptionPane.showMessageDialog(null,"Player has won " + wins + " times and the computer has won " + losses + " times");
}
//Computer wins
else if(Computer == Rock){
JOptionPane.showMessageDialog(null,"Scissors v Rock! Computer Wins!");
losses++;
round++;
JOptionPane.showMessageDialog(null,"Player has won " + wins + " times and the computer has won " + losses + " times");
}
//Player wins
if(Player == Rock)
if(Computer == Scissors ){
JOptionPane.showMessageDialog(null,"Rock v Scissors! Player Wins!");
wins++;
round++;
JOptionPane.showMessageDialog(null,"Player has won " + wins + " times and the computer has won " + losses + " times");
}
//Computer wins
else if (Computer == Paper){
JOptionPane.showMessageDialog(null,"Rock v Paper! Computer Wins!");
losses++;
round++;
JOptionPane.showMessageDialog(null,"Player has won " + wins + " times and the computer has won " + losses + " times");
}
//Player Wins
if(Player == Paper)
if(Computer == Rock){
JOptionPane.showMessageDialog(null,"Paper v Rock! Player Wins!");
wins++;
round++;
JOptionPane.showMessageDialog(null,"Player has won " + wins + " times and the computer has won " + losses + " times");
}
//Computer Wins
else if (Computer == Scissors){
JOptionPane.showMessageDialog(null,"Paper v Scissors! Computer Wins!");
losses++;
round++;
JOptionPane.showMessageDialog(null,"Player has won " + wins + " times and the computer has won " + losses + " times");
}
}
if(wins>losses){
JOptionPane.showMessageDialog(null,"The Player Wins!");
}if(losses>wins){
JOptionPane.showMessageDialog(null,"The Computer Wins!");
}
}
case 2 :
{
JOptionPane.showMessageDialog(null,"You have selected the game's rules.\nOpening the rules...\nLoaded successfully! Please press OK.");
JOptionPane.showMessageDialog(null,"Here are the rules for the game:\nIn total, there are 3 rounds for this game, including Ties.\nPaper vs Rock => Paper is the Winner. Add 1 to the winner.\nPaper vs Scissors => Scissors is the Winner. Add 1 to the winner.\nRock vs Scissors => Rock is the Winner. Add 1 to the winner.\nRock vs Rock => Tie. No score.\nScissors vs Scissors => Ties. No score.\nPaper vs Paper => Tie. No score.");
}
case 3 :
{
JOptionPane.showMessageDialog(null,"3");
}
default :
JOptionPane.showMessageDialog(null,"You entered an invalid operation. Please select 1, 2, or 3.");
String input2 = JOptionPane.showInputDialog("Would you like to return to the main menu? Please respond with Yes or No.");
if (input2.equalsIgnoreCase ("No"))
JOptionPane.showMessageDialog(null,"You have selected to exit the program. Closing the program... please press OK.");
{
i=1;
}
}
}
You need to use break at the end of every case. Syntax is like:
switch(variable){
case 1:
//Do your operations.
break;
case 2:
//Do your operations.
break;
.
.
.
}
Let me know if this helps.
I have been trying to make a game in java called pig where a player rolls 2 dice. the player earns point based off of what they roll for example if the player rolls 5 and 4 he now has 9 points but if the player rolls a 1 they gain no points and control switches over to the computer and if the player rolls snake eyes ( 1 and 1) the player loses all point and control switches over to the computer. i have the game working but i need to stop the computer after it gains 20 points in its turn. Whichever player hits 100 first wins.
Here is my code:
//this program runs 4.4
import java.util.Scanner;
public class run {
public static void main(String[] args)
{Scanner scan = new Scanner (System.in);
dice thing = new dice();
dice thing1 = new dice();
boolean control=true;
int x = 0,points=0,a,b,y=0,c,d,turn=0,save=0,no=0;
while(x<100 && y<100)
{
while (control == true && x<100)
{
a=thing.roll();
b=thing1.roll();
if (a == 1 && b==1)
{
control=false;
System.out.println("your first die rolled a " + thing.getroll() + " second die rolled a " + thing1.getroll()+"computer now has control");
x=0;
}
else if(a == 1 || b==1)
{
control = false;
System.out.println("your first die rolled a " + thing.getroll() + " second die rolled a " + thing1.getroll() + " now you have " + x +" points "+"computer now has control");
}
else
{
x +=(a+b);
System.out.println("your first die rolled a " + thing.getroll() + " your second die rolled a " + thing1.getroll() + " now you have " + x +" points" );
System.out.println(" would you like to end your turn put in 1 for yes 0 for no");
points = scan.nextInt();
if(points==1)
{
control= false;
}
if (x>=100)
{
System.out.println("you win");
}
}
}
while (control==false && y<100)
{
c=thing.roll();
d=thing1.roll();
if (c == 1 && d==1)
{
control=true;
System.out.println("The computers first die rolled a " + thing.getroll() + " The computers second die rolled a " + thing1.getroll()+"you now have control");
turn = y;
y=0;
}
else if(c == 1 || d==1)
{
control = true;
System.out.println("The computers first die rolled a " + thing.getroll() + " The computers second die rolled a " + thing1.getroll()+ " now the computer has " + y +" points "+"you now have control");
turn = y;
}
else
{
y +=(c+d);
System.out.println("The computers first die rolled a " + thing.getroll() + " The computers second die rolled a " + thing1.getroll() + " now the computer has " + y +" points" );
turn = y;
if (y>=100)
{
System.out.println("you lose");
}
}
}
}
}
}
Try adding:
if (turn >= 20){
control = true;
turn = 0;
}
after:
while (control==false && y<100)
{
I've written a code for a game that simulates the user and the computer rolling a die and the winner receives 1$ from the loser, with each starting with 2$. The code runs fine, but it doesn't end when either the user or computer reaches 0$ like i had anticipated. Any suggestions?
import java.util.Scanner;
public class ALE_04_RollDice {
public static void main (String[] args) {
Scanner input = new Scanner(System.in);
int userMoney = 2;
int compMoney = 2;
int userRoll = (int) (1 + Math.random() * 6);
int compRoll = (int) (1 + Math.random() * 6);
System.out.print("Press 'r' if you would like to roll ");
do {String roll = input.nextLine();
if (roll.equals("r")); {
if (userRoll > compRoll){
userMoney++;
compMoney--;
System.out.print("The computer rolled " + compRoll + " and you rolled " + userRoll + ". you won."
+ "\n" + "You have $" + userMoney + " & The computer has $" + compMoney);
}
else if (userRoll < compRoll) {
compMoney++;
userMoney--;
System.out.print("The computer rolled " + compRoll + " and you rolled " + userRoll +
". you lost" + "\n" + "You have $" + userMoney + " & The computer has $" + compMoney);
}
else {System.out.print("The computer rolled " + compRoll + "and you rolled " + userRoll +
". it's a tie" + "\n" + "You have $" + userMoney + " & the computer has $" + compMoney);}
}
}while (userMoney >= 0 || compMoney >=0);
}}
Your while statement is testing for <= 0, but initially both variables are > 0. The while loop will never fire.
First off you have a problem with your while condition money values = 2 for player and comp, so while will never fire..fix that and you could use a do while
do{
statement(s) //block of statements
}while (Boolean expression);
So inside your do{} you could have your statements and conditions..so it will do whatever is inside those braces until the condition inside the while() is met
for example
class DoWhileLoopExample {
public static void main(String args[]){
int i=10;
do{
System.out.println(i);
i--;
}while(i>1);
}
}
You are using the incorrect condition in the while statement.You are testing if any player has >=0 this will always test true and cause an infinite loop. Instead test if BOTH players have >0 and end the game if not.
Also you have a ';' after you if statement. That will cause the code after it to execute all the time.
Here is complete working code:
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int userMoney = 2;
int compMoney = 2;
int userRoll = (int) (1 + Math.random() * 6);
int compRoll = (int) (1 + Math.random() * 6);
System.out.print("Press 'r' if you would like to roll ");
do {String roll = input.nextLine();
if (roll.equals("r")) {
if (userRoll > compRoll){
userMoney++;
compMoney--;
System.out.print("The computer rolled " + compRoll + " and you rolled " + userRoll + ". you won."
+ "\n" + "You have $" + userMoney + " & The computer has $" + compMoney);
}
else if (userRoll < compRoll) {
compMoney++;
userMoney--;
System.out.print("The computer rolled " + compRoll + " and you rolled " + userRoll +
". you lost" + "\n" + "You have $" + userMoney + " & The computer has $" + compMoney);
}
else {System.out.print("The computer rolled " + compRoll + "and you rolled " + userRoll +
". it's a tie" + "\n" + "You have $" + userMoney + " & the computer has $" + compMoney);}
}
//prompt user to type 'r' to roll again
System.out.println("\n\nPress 'r' if you would like to roll ");
}while (userMoney > 0 && compMoney >0);
System.out.println("\n\nGAME OVER!!!");
}
}
//end main
You want to stop when less than or equal to but you have greater than or equal to.
while (userMoney >= 0 || compMoney >=0) {
Cause of problem:
Your while loop does not run at all, because the condition inside is initially evaluated as false.
while (userMoney <= 0 || compMoney <=0)
This reads: whilst the user has a money less than or equal to 0 OR whilst the computer has money less than or equal to 0 then run the while loop, this will never initially be true as they both the computer and user both start with $2, hence userMoney == 2 and compMoney == 2.
Solution:
Change the condition of the while loop to the following:
while(userMoney>0 || compMoney>0)
then add an if statement which says if the compMoney == 0 or if the userMoney == 0, then break out of the while loop.
if(userMoney == 0 || compMoney == 0){
break;
}