A way to reset program on cmd? - java

I wrote a simlpe dice game and would like to know a way to reset the program after typing something like "Reset". I use cmd to run my programs. There is no graphics included in any of my programs whatsoever.
import java.util.Scanner;
import java.util.Random;
public class Dice
{
public static void main(String[] args)
{
String personPlay; //User's play
String computerPlay = ""; //Computer's play
int computerInt; //Randomly generated number used to determine computer's play
String response;
Scanner scan = new Scanner(System.in);
Random generator = new Random();
System.out.println("Let's play some dice!");
//Generate computer's play
computerInt = generator.nextInt(6)+1;
//Translate computer's randomly generated play to
//string using if statements
if (computerInt == 1)
computerPlay = "1";
else if (computerInt == 2)
computerPlay = "2";
else if (computerInt == 3)
computerPlay = "3";
else if (computerInt == 4)
computerPlay = "4";
else if (computerInt == 5)
computerPlay = "5";
else if (computerInt == 6)
computerPlay = "6";
//Get player's play from input
System.out.println("Choose a number between 1 and 6.");
personPlay = scan.next();
//Print computer's play
System.out.println("The dice rolled " + computerPlay);
//See if you won.
if (personPlay.equals(computerPlay))
System.out.println("You won!");
else System.out.println("You lost!");
}
}

You should use an infinite loop and get input from user, check if user entered "RESET", if so roll the dice again or do whatever you're doing now.
If he entered a phrase like "EXIT" infinite loop ends or your program ends.

Usually I don't like giving full answers, but there are some improvements I wanted to show and just listing them would be a lot of work as well.
import java.util.Scanner;
import java.util.Random;
public class Dice
{
private static void play(Scanner scan, Random generator)
{
int computersPlay, usersPlay;
System.out.println("Let's play some dice!");
computersPlay = generator.nextInt(6) + 1;
System.out.print("Give a number:");
usersPlay = scan.nextInt();
System.out.printf("The dice rolled %d\n", computerPlay);
if (computersPlay == usersPlay) {
System.out.println("You win !");
}
else {
System.out.println("You lose!");
}
}
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
Random generator = new Random();
do {
play(scan, generator);
System.out.println("If you want to continue type:'Reset'");
} while(scan.next().equals("Reset");
}
}
Changes moving the play to a different method to keep oversight, using the Scanners nextInt method to obtain a number directly and compare that instead, and the do {} while(); statement to let it repeat an arbitrary amount of times (given that you type reset)

By "reset" I assume you meant "repeat"? Use a while loop.
Also, no real need to store String values other than capture what the user entered.
public class DiceGuess {
// Global variables for this class
static Random generator = new Random();
static Scanner scan = new Scanner(System.in);
public static void main(String[] args) {
System.out.println("Let's play some dice!");
// Initialize some variables
int computerInt;
String response;
while (true) { // Play forever
computerInt = generator.nextInt(6) + 1;
System.out.println("Choose a number between 1 and 6. ('quit' to stop playing)");
response = scan.nextLine();
if (response.equalsIgnoreCase("quit")) break; // Stop the game
try {
System.out.println("The dice rolled " + computerInt);
if (Integer.parseInt(response) == computerInt) {
System.out.println("You won!");
} else {
System.out.println("You lost!");
}
} catch (NumberFormatException e) {
System.err.println("That wasn't a number!");
}
}
}
}

Related

How to let the user attempt many times?

import java.util.Scanner;
import java.util.Random;
/*
* 1) the user can attempt many times and you need to display the number of successful attempt
* 2) the range of random number 1..49
* 3) output >> You successfully guess the number in 16 attempts
* 4) output >> Do you want to play again?
* */
public class GuessingGame {
public static void main(String[] args) {
Scanner uInput = new Scanner(System.in);
Random randNum = new Random();
int guessNumber, number, count=0;
String in;
char again;
System.out.println("Welcome to Guessing Game");
do {
number = randNum.nextInt(50); // random number in the range of 1..50
for(int i=0; i<5; i++)
{
System.out.println("Enter a number to guess: ");
guessNumber = uInput.nextInt(); // get guess number from user
if(guessNumber > number)
{
System.out.println("Too big");
}else if(guessNumber < number)
{
System.out.println("Too small");
}else
{
System.out.println("Success");
count+=1;
return;
}
}
System.out.println("You successfully guess the number in "+count);
System.out.println("Do you want to play again? ");
in = uInput.nextLine();
again = in.charAt(0); //again will hold the first character from in var
}while(again =='Y'|| again =='y');
System.out.println("Guessing game terminate, thank you");
}
}
public static void main(String[] args) {
System.out.println("Welcome to Guessing Game");
guessNumber();
System.out.println("Guessing game terminate, thank you");
}
private static void guessNumber() {
Scanner uInput = new Scanner(System.in);
Random randNum = new Random();
int guessNumber, number, count = 0;
String in;
char again;
boolean isCorrect = false;
number = randNum.nextInt(50); // random number in the range of 1..50
while (!isCorrect) {
System.out.println("Enter a number to guess: ");
guessNumber = uInput.nextInt(); // get guess number from user
count += 1;
if (guessNumber > number) {
System.out.println("Too big");
} else if (guessNumber < number) {
System.out.println("Too small");
} else {
System.out.println("Success");
isCorrect = true;
}
}
System.out.println("You successfully guess the number in " + count + " attempts");
System.out.println("Do you want to play again? yes/no");
in = uInput.next();
again = in.charAt(0); //again will hold the first character from in var
if (again == 'Y' || again == 'y') {
guessNumber();
}
}
All you have to do is to replace your do while loop with a while loop. But the point is that you must set an initial value 'Y' to your again char to start the while loop. the condition of the loop will be just the same. The code will be like : char again = 'Y';
while (again == 'Y' || again == 'y') {
System.out.println("Welcome to Guessing Game");
number = randNum.nextInt(50);
for (int i = 0; i < 5; i++) {
System.out.println("Enter a number to guess: ");
guessNumber = uInput.nextInt();
if (guessNumber > number) {
System.out.println("Too big");
} else if (guessNumber < number) {
System.out.println("Too small");
} else {
System.out.println("Success");
count += 1;
break;
}
}
System.out.println("You have successfully guessed the number for " + count + " times");
System.out.println("Do you want to play again? ");
in = uInput.next();
again = in.charAt(0); //again will hold the first character from in var
}
System.out.println("Guessing game terminate, thank you");
I must note that your count variable, contains the number of games which user has guessed the number successfully, and not the number of attempts during a single game. If you want to handle this too, create attempts variable inside the while loop and increase it whenever the user attempts.
Also I changed the line in = uInput.nextLine(); to in = uInput.next(); because I believe your scanner input will be skipped.

Rock, paper, scissors game Invalid entry loop

I am trying to figure out where to put the loop that when the user enters any value other than "rock", "paper" or "scissors" the program stays in the loop and displays "Invalid entry" while requesting the user to enter again.
Any help is much appreciated.
As it stands now, the program will display "Invalid entry" but then continues without asking the user to try again.
import java.util.Scanner; // Import the Scanner class
import java.util.Random; // Import the random class for game
/**
*/
public class Challenge17
{
// Method to determine the random choice of computer
public static String getComputerChoice(Random random)
{
int number;
number = random.nextInt(3) + 1;
String computerChoice;
switch (number)
{
case 1:
computerChoice = "rock";
break;
case 2:
computerChoice = "paper";
break;
case 3:
computerChoice = "scissors";
break;
default:
computerChoice = "";
}
return computerChoice;
}
// Method to display the menu for choices
public static void displayChoice( )
{
System.out.println("Game Options\n----------\n"
+ "1: rock\n2: paper\n3: scissors");
}
// Method to request and hold user choice for game
public static String getUserInput(Scanner keyboard)
{
String userInput;
System.out.println("Enter your choice: ");
userInput = keyboard.nextLine();
return userInput;
}
// Method to determine winner
public static String determineWinner(String computerChoice, String userInput)
{
String winner = "Tie Game!"; // Default display Tie game
String message = ""; // To determine the message for winner
String displayMessage; // To display the message for winner
// Custom messages below
String rockMessage = "Rock smashes scissors";
String scissorsMessage = "Scissors cuts paper";
String paperMessage = "Paper wraps rock";
boolean loop = false;
if(computerChoice.equals("rock") && userInput.equalsIgnoreCase("scissors"))
{
winner = " Computer wins!";
message = rockMessage;
loop = true;
}
else if (userInput.equalsIgnoreCase("rock") && computerChoice.equals("scissors"))
{
winner = "You win!";
message = rockMessage;
loop = true;
}
if(computerChoice.equals("scissors") && userInput.equalsIgnoreCase("paper"))
{
winner = " Computer wins!";
message = scissorsMessage;
loop = true;
}
else if (userInput.equalsIgnoreCase("scissors") && computerChoice.equals("paper"))
{
winner = "You win!";
message = scissorsMessage;
loop = true;
}
if(computerChoice.equals("paper") && userInput.equalsIgnoreCase("rock"))
{
winner = " Computer wins!";
message = paperMessage;
loop = true;
}
else if (userInput.equalsIgnoreCase("rock") && computerChoice.equals("scissors"))
{
winner = "You win!";
message = paperMessage;
loop = true;
}
else
{
System.out.println("Invalid entry.");
loop = false;
}
displayMessage = winner + " " + message;
return displayMessage;
}
// Main method to initiate and execute game
public static void main(String[] args)
{
Random random = new Random(); // To call the random class
Scanner keyboard = new Scanner(System.in); // To call the scanner class
String computerChoice; // Hold computer input
String userInput; // Hold user input
String input; // Hold input for repeat
char repeat; // Character for repeat
do
{
displayChoice(); // Call method to display the choices
computerChoice = getComputerChoice(random); // Hold the PC random choice
userInput = getUserInput(keyboard); // To get the user input
System.out.println("You chose: " + userInput + " computer chose: \n"
+ computerChoice);
System.out.println(determineWinner(computerChoice, userInput));
// Does the user want to play again
System.out.println("Would you like to play again?");
System.out.print("Enter Y for yes, or N for no: ");
input = keyboard.nextLine();
repeat = input.charAt(0);
}
while (repeat == 'Y' || repeat == 'y');
}
}
From my understanding i'm pretty sure you want this kind of a loop
public static String getUserInput(Scanner keyboard)
{
String userInput;
System.out.println("Enter your choice: ");
userInput = keyboard.nextLine();
while(!userInput.equals("rock")&&!userInput.equals("paper")&&!userInput.equals("scissors"))
{
System.out.println("Invalid Entry, Please re-enter your choice:");
userInput = keyboard.nextLine();
} //It wont go out of the loop unless it's one of the 3 choices
return userInput;
}
You could create a Boolean method.
private Boolean checkUserInput(String input) {
if(!input.equalsIgnoreCase("rock") && !input.equalsIgnoreCase("paper") && !input.equalsIgnoreCase("scissors")) return false;
return true;
Then you do the check before you determine the winner like if true then run the determineWinner(computerChoice, userInput) code else it doesn't.
That way, you can edit the code and add functionalities in the future if need be.

How to break else statement and exit the program

package oddsorevens;``
import java.util.Scanner;
import java.util.Random;
public class OddsOrEvens
{
public static void main(String[] args)
{
Scanner name= new Scanner (System.in); // getting input from user
System.out.print("Hi! What's your name: ");
String user = name.nextLine(); // getting user name
System.out.println("Hello: "+user);
System.out.println("Let's play OddsOrEvens");
System.out.println("Choose Odd or Even");
String s ="oddOrEven";
Scanner str = new Scanner(System.in); // getting new string from user
String s1 = str.next(); //storing odd or even here
o:
if (s1.equals("even")||(s1.startsWith("e")))
{
System.out.println("You choose even");
System.out.println("Computer choose odd");
}
else if (s1.equals("odd")||(s1.startsWith("o")))
{
System.out.println("You choose odd");
System.out.println("Computer choose even");
}
else
{
System.out.println("Entered wrong keyword");
}
System.out.print("How many fingers you want to put out: ");
Scanner num = new Scanner(System.in);
int n=num.nextInt();
Random rand = new Random();
int computer = rand.nextInt(6);
System.out.println("Computer choose "+ computer +" fingers");
int sum;
sum=n+computer;
System.out.println(sum);
if(sum%2==0)
{
System.out.println(sum+" is even");
}
else
{
System.out.println(sum+" is odd");
}
int u = s1.length();
if(u/2==0)
{
System.out.println("You won :)");
}
else
{``
System.out.println("You lose :(");
}
}
}
This is my first pgm in java. here if the user enter wrong keyword pgm should be break and based on the user input the output of the pgm will be win or lose. help please.
Whenever you want your application to stop, you have to explicitly tell that you want to exit. To do so you have write just piece of line of code and that is System.exit(0)
Here sample code to understand it better:
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
if (s.next().equals("o")) {
System.out.println("game is still on");
} else {
System.out.println("game end!");
System.exit(0);
}
}

Java rock paper scissor printing the statements oddly

So here i am trying to create a program that takes an input as an int and then plays a game of Rock paper scissors. It seems to want to reprint statements that it shouldn't be and is skipping printing statements as well. I would love some assistance if possible. I have tried setting up print statements everywhere but it has just been more confusing.
import java.util.Scanner;
public class RPSS{
//Main method
public static void main(String[ ] argc)
{
System.out.println("Lets play rock paper scissors");
Scanner tnt = new Scanner(System.in);
String computerHand; // string variable for computer choice
String userHand; // string variable for user choice
//
String answer = "";
while (!a
nswer.equals("No") && (!answer.equals("no"))){
userHand = userHand();
computerHand = computerHand();
System.out.println("The User picks " + userHand + " " );
System.out.print("The Computer picks " + computerHand );
String winner = getWinner(computerHand, userHand);
System.out.println(winner);
System.out.println("play again?");
answer = tnt.next();
}
//Condition for the do-while loop
}
public static String userHand(){ //method for users choice in the game
//prints message to user giving them choices
System.out.println(" ");
System.out.println("1. Rock ");
System.out.println("2. Paper ");
System.out.println("3. Scissors ");
int userChoice; // user choice variable in this method
Scanner tnt = new Scanner(System.in); // creates instance of scanner class
userChoice = tnt.nextInt(); //reads user input
return getChoice(userChoice); //returns user choice to userChoice
}
public static String computerHand() //method for computer generated choice
{
int computernum = 1 + (int)(Math.random() * (( 2) +1));
return getChoice(computernum);
}
public static String getChoice(int num) //method recieving both computer hand and user hand
{
// if statements to place the correct choice
String choice = "";
if (num == 1){
choice = "Rock";
}
else if(num == 2){
choice = "Paper";
}
else if(num == 3){
choice = "Scissors";
}
return choice;
}
// Method determing the winner
public static String getWinner(String computerChoice, String userChoice)
{
computerChoice = computerHand(); //places computerChoice variable in computerhand
userChoice = userHand(); //does same for user choice
String winner="";
if (userChoice.equals("Rock") && computerChoice.equals("Paper")){
System.out.println("The computer wins");
return winner;
}
else if (userChoice.equals("Paper") && computerChoice.equals("Scissors")){
System.out.println(" The computer wins");
return winner;
}
else if (userChoice.equals("Scissors") && computerChoice.equals("Rock")){
System.out.println(" The computer wins ");
return winner;
}
else if (userChoice.equals("Rock") && computerChoice.equals("Paper")){
System.out.println(" The computer wins ");
return winner;
}
else if(userChoice.equals(computerChoice))
{
System.out.println(" There is no winner");
return " ";
}
else{
return winner;
}
}
}
The first problem is that userhand() and computerHand() are being called twice per "round", once at the beginning of the while loop inside the main method and once at the beginning of the getWinner() method. Elimination of the calls at the beginning of the getWinner() method should solve the repeats.
The 2nd Problem is that instead of modifying the value of winner inside the getWinner() method before returning it, you are you are simply outputting the message via println(). an example of fixing this would be converting this:
if (userChoice.equals("Rock") && computerChoice.equals("Paper"){
System.out.println("The computer wins");
return winner;
}
to this:
if (userChoice.equals("Rock") && computerChoice.equals("Paper")){
winner = "The computer wins";
return winner;
}
another minor issue is the fact that
userChoice.equals("Rock") && computerChoice.equals("Paper")
is checked twice, id just remove the entire if else block based around the
2nd check of it
Lastly i would treat the final else clause as the player wins one and set winner to something like " The player wins "

How to reduce code in main method by making new methods for my code?

Hi I am using Eclipse to program a game.
Basically, the user chooses 1. Even or 2. Odd
A randomly generated dice rolls. If the user lands on the choice he made (even number or odd number) he stays otherwise, he moves 5 steps back.
The user is vsing the computer. So if user is Even, computer is Odd, and vice versa
My problem is I don't know how to call this kind of method. Please look at my code and give me advice. If it can be better let me know also.
package Testing;
import java.util.Scanner;
import java.util.Random;
public class hundredsteps {
public static int playerChoice(){
System.out.println("Please choose an option below");
System.out.println("1. Even");
System.out.println("2. Odd");
Scanner input = new Scanner(System.in);
int choice = input.nextInt();
return choice;
// player set EVEN by default
}
public static int playerRoll(){
System.out.println("Press enter to roll");
Scanner input = new Scanner(System.in);
String roll = input.nextLine();
Random generator = new Random();
int dice1 = generator.nextInt(6)+1;
int dice2 = generator.nextInt(6)+1;
int sumOfDice = dice1 + dice2;
return sumOfDice;
}
public static int cpuRoll(){
Random generator = new Random();
int dice1 = generator.nextInt(6)+1;
int dice2 = generator.nextInt(6)+1;
int sumOfDice = dice1 + dice2;
return sumOfDice;
}
public static String gameWinner(int player, int cpu){
String winner = " ";
if (player == 100 && cpu == 100){
winner = " TIE ";
System.out.println("TIE GAME!!");
}else if (player == 100){
System.out.println();
winner = " player ";
System.out.println("Congratulations! You've won!");
}else if (cpu == 100){
winner = " cpu ";
System.out.println("Sorry, you lost. The computer won this round");
}
return winner;
}
public static void main(String[] args) {
int playerPosition = 0, cpuPosition = 0;
int playerRoll = 0, cpuRoll = 0;
do{
System.out.println();
playerRoll = playerRoll();
System.out.println();
System.out.println("You rolled " +playerRoll);
playerPosition = playerPosition + playerRoll;
if (playerPosition % 2 == 0){
System.out.println("You are now on step number " +playerPosition);
} else if (playerPosition % 2 != 0){
System.out.println("You landed on an odd number! You must move 5 steps back");
playerPosition = playerPosition - 5;
System.out.println("You are now on step number " +playerPosition);
}
cpuRoll = cpuRoll();
System.out.println("The computer rolled "+cpuRoll);
cpuPosition = cpuPosition + cpuRoll;
if (cpuPosition % 2 != 0){
System.out.println("The computer is now on step number " +cpuPosition);
} else if(cpuPosition % 2 == 0){
System.out.println("The computer landed on an even number! The computer moved 5 steps back");
cpuPosition = cpuPosition - 5;
System.out.println("The computer is now on step number " +cpuPosition);
System.out.println();
}
if (playerPosition > 100){
System.out.println("You rolled too high!");
System.out.println("You moved 20 steps back");
playerPosition = playerPosition - 20;
} if (cpuPosition > 100){
System.out.println("The computer rolled too high");
System.out.println("The computer moves 20 steps back");
cpuPosition = cpuPosition - 20;
}
} while (playerPosition <= 99 && cpuPosition <= 99);
gameWinner(playerPosition, cpuPosition);
}
}
Do you mean all the methods you call in main() keep throwing compile errors if they aren't static, so you "can't" call them?
If thats what you mean, you need to make some code to run/test your code. You need some objects. Java is object oriented (OO), so always think about "things" rather than "procedures/sequences of commands."
For example, make a test class, that will "contain" your "game object"
public class GameTest {
public static void main(String[] args) {
DiceGame game = new DiceGame();
}
}
Put your game in a separate class ( a whole new file):
public class DiceGame {
//all your primitive/object references
//add a constructor
public DiceGame() {
//initialize primitives/objects
play();
}
public void play() {
//game logic goes here
//the stuff you have in main() right now
//this isn't a static method, so call any other methods you want
}
//put your other methods here
}
Then run the file GameTest, not DiceGame. This is just one of several patterns you can use to get your code running.
If this is not what you mean, can you clarify your question?
You must be making this too hard for yourself. If you want all of the code from you main() in another method then make it so.
public static void main(String[] args) {
newMethod();
}
public static void newMethod() {
// All the stuff from your old main goes in here
}
I can only imagine that you don't understand static methods and why the methods you call from your main() must be static.
Alternatively, do exactly what #nexus_2006 said and put your game in it's own class and then in your main() create an instance of that class and start the game from there.
public static void main(String[] args) {
DiceGame game = new DiceGame();
game.play();
}
The main() above can even go inside DiceGame.java. Either way works fine.

Categories