What loop should I use to end rock paper scissor program? - java

I need to make my rock paper scissor program to run as a loop untill user puts in a finishing input avslutt. What loop type should I use and where should I put it?
//Stein saks papir
import java.util.Scanner;
import java.util.Random;
public class oppgave3{
public static void main (String[]args){
//setter muligheten for
Random rand = new Random();
Scanner tastatur = new Scanner(System.in);
int spillerValg = 0;
int poengS=0;
int poengD=0;
int uavgjort=0;
//forklarer bruker fremgangsmåte
System.out.println("Skriv stein, saks, papir eller avslutt:");
String spiller = tastatur.nextLine();
//omgjør brukerinput til tallverdier for å lettere sammenligne
if(spiller.equals("stein")){
spillerValg = 0;
}
if (spiller.equals("saks")) {
spillerValg = 1;
}
if (spiller.equals("papir")) {
spillerValg = 2;
}
if(spiller.equals("avslutt")){
spillerValg = 3;
}
int dataValg = rand.nextInt(3);
if(spillerValg <= 3){
if (spillerValg == dataValg){
System.out.println("Begge valgte samme!");
System.out.println("Uavgjort");
uavgjort++;
}
else if (dataValg == 0 && spillerValg == 1){
System.out.println("Spillervalg: Saks");
System.out.println("Datavalg: Stein");
System.out.println("Data vant!");
poengD++;
}
else if(dataValg == 0 && spillerValg == 2){
System.out.println("Spillervalg: Papir");
System.out.println("Datavalg: Stein");
System.out.println("Du vant!");
poengS++;
}
else if(dataValg == 1 && spillerValg == 0){
System.out.println("Spillervalg: Stein");
System.out.println("Datavalg: Saks");
System.out.println("Du vant!"); //0=stein 1= saks 2=papir
poengS++;
}
else if(dataValg == 1 && spillerValg == 2){
System.out.println("Spillervalg: Papir");
System.out.println("Datavalg: Saks");
System.out.println("Data vant!");
poengD++;
}
else if(dataValg == 2 && spillerValg == 0){
System.out.println("Spillervalg: Stein");
System.out.println("Datavalg: Papir");
System.out.println("Data vant!");
poengD++;
}
else if(dataValg == 2 && spillerValg == 1){
System.out.println("Spillervalg: Saks");
System.out.println("Datavalg: Papir");
System.out.println("Du vant!");
poengS++;
}
}
if (spillerValg == 3);
System.out.println("Spill avsluttet");
System.out.println("Uavgjort "+uavgjort+" ganger");
System.out.println("Du vant "+poengS+ " ganger");
System.out.println("Data vant "+poengD+" ganger");
tastatur.close();
}
}

First, you need to decide what loop to use.
A for loop does not sound like the right choice, since you don't know how many iterations you want to do when you start. So it should either be a while or a do-while.
You use a do-while when you always want to loop at least once. A common situation is that you do not have a value for the condition until you have performed the operation once. In your case, that is sort of the case (you don't know if the user entered avslutt until you asked), but you could use both a while and a do-while.
As this looks a little bit like homework, I will give you a rough outline in pseudo code.
First, as a do-while:
do
x = user input
if x <> "avslutt"
play the game
loop while x <> "avslutt"
Second, as a while:
x = user input
while x <> "avslutt"
play the game
x = user input
Bathshebas suggestion to put the actual game in a function, and call it inside the loop is a good one. Whenever you have long code inside a loop, you should consider that.

Related

Returning two values to main method without arrays

Create a program named rockPaperScissors.java
The program should validate user input.
Game should ask the user to play again and continue if yes and stop if no.
Once the user stops playing, program should print the total number of wins for the computer and
for the user.
I am trying to learn programming from a book, so I am not good at this. I need to return the values of Cwin and Uwin to the main method, but I know how to return one value to it. I also have a problem with looping the question. I cannot use arrays and could only use the basic while loops (without the (true) and break).
import java.util.*;
public class rockPaperScissors
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("Play again? Type yes or no.");
String YoN= input.next();
if (YoN.equalsIgnoreCase("yes"))
{
game();
}
else
{
System.out.println("Computer wins: " + Cwin + "/nUser wins: " + Uwin);
}
}
public static void game()
{
System.out.println("Choose rock, paper, or scissors. Type 1 for rock, 2 for paper, and 3 for scissors.");
Scanner console = new Scanner(System.in);
Random r = new Random();
int choice = console.nextInt();
int Uwin = 0;//user win count
int Cwin = 0;//computer win count
int result = -1;
if (choice > 1 || choice < 3)
{
System.out.println("Invalid entry. Please type 1, 2, or 3.");
}
int comp = r.nextInt(3) + 1;
if (comp == 1)
{
System.out.println("Computer chose rock.");
}
if (comp == 2)
{
System.out.println("Computer chose paper.");
}
if (comp == 3)
{
System.out.println("Computer chose scissors.");
}
if (choice == 1 && result == 2)
{
Cwin++;
}
if (choice == 2 && result == 3)
{
Cwin++;
}
if (choice == 3 && result == 1)
{
Cwin++;
}
if (choice == 2 && result == 1)
{
Uwin++;
}
if (choice == 3 && result == 2)
{
Uwin++;
}
if (choice == 1 && result == 3)
{
Uwin++;
}
}
}
If you want to return multiple values from a method you may use an array that stores the values in its elements. Check here.
However for this program there is no need for returning 2 values(and you also said "I cannot use arrays"). Instead you can have 2 global variables that record the number of times the player wins and the number of times the computer wins respectively. Lets call them playerWinCount and computerWinCount.
Now that we got that down, lets look at how we allow the user to replay the game. You say that can use only "basic while loops". Fine. What we do is we declare a variable choice that holds the user's entry when prompted to replay. We initialise choice to true and then keep asking the user if he'd like to play again until he decides not to.
String choice = "yes" ;
while(choice.equalsIgnoreCase("yes"))
{
playGame() ;
System.out.print("Play again(Yes/No)? ") ;
choice = scanner.next() ;
}
The playGame() method has the code to play the game.
The way we validate the user's entry is by using a length check. If the entry is out of range(i.e. from 1 to 3 inclusive) he'll be prompted to enter again.
boolean valid = false ;
while(valid == false) // loop will run until a valid number is entered
{
System.out.print("Choose rock, paper, or scissors. Type 1 for rock, 2 for paper, and 3 for scissors: ") ;
playerPick = scanner.nextInt() ;
// validation of the user's entry
if(playerPick < 1 || playerPick > 3)
System.out.println("Invalid entry! Try again.") ;
else
valid = true ;
}
Having acquired a valid user input, the next thing we do is get a random number as the computer's pick(you've done that). Then we check who won the game and increment the number of times the winner has won. We can do this using a number of if statements like this:
// first we check if the computer and player did not pick the same thing
if(playerPick != computerPick)
{
if(playerPick == 1 && computerPick == 3) // check if the player picked rock(1) and the computer picked scissors(3)
{
playerWinCount++ ;
System.out.println("Player won!") ;
}
else if(playerPick == 3 && computerPick == 2) // check if the player picked scissors(3) and the computer picked paper(2)
{
playerWinCount++ ;
System.out.println("Player won!");
}
else if(playerPick == 2 && computerPick == 1) // check if the player picked paper(2) and the computer picked rock(1)
{
playerWinCount++ ;
System.out.println("Player won!");
}
else // otherwise, the computer has won this round
{
computerWinCount++ ;
System.out.println("Computer won!") ;
}
}
else
{
System.out.println("It's a tie!");
}
Or we can just combine the 3 conditions of winning with the OR operator(||) and use just 2 if statements:
if(playerPick != computerPick)
{
if((playerPick == 1 && computerPick == 3) || (playerPick == 3 && computerPick == 2) || (playerPick == 2 && computerPick == 1))
{
playerWinCount++ ;
System.out.println("Player won!") ;
}
else
{
computerWinCount++ ;
System.out.println("Computer won!");
}
}
else
{
System.out.println("It's a tie!");
}
And that's about it.
Here's the entire code:
import java.util.* ;
public class RockPaperScissors
{
static Scanner scanner = new Scanner(System.in) ;
static int playerWinCount, computerWinCount ;
public static void main(String[] args)
{
playerWinCount = 0 ;
computerWinCount = 0 ;
String choice = "yes" ;
while(choice.equalsIgnoreCase("yes"))
{
playGame() ;
System.out.print("Play again(Yes/No)? ") ;
choice = scanner.next() ;
}
System.out.println("\nNumber of times you won: " + playerWinCount) ;
System.out.println("Number of times computer won: " + computerWinCount) ;
System.out.println("Goodbye!") ;
}
public static void playGame()
{
System.out.println("") ;
Random random = new Random() ;
int playerPick = -1 ;
int computerPick = -1 ;
boolean valid = false ;
while(valid == false) // loop will run until a valid number is entered
{
System.out.print("Choose rock, paper, or scissors. Type 1 for rock, 2 for paper, and 3 for scissors: ") ;
playerPick = scanner.nextInt() ;
// validation of the user's entry
if(playerPick < 1 || playerPick > 3)
System.out.println("Invalid entry! Try again.") ;
else
valid = true ;
}
computerPick = random.nextInt(3) + 1 ;
System.out.println("The computer picked " + computerPick) ;
// first we check if the computer and player did not pick the same thing
if(playerPick != computerPick)
{
if(playerPick == 1 && computerPick == 3) // check if the player picked rock(1) and the computer picked scissors(3)
{
playerWinCount++ ;
System.out.println("Player won!") ;
}
else if(playerPick == 3 && computerPick == 2) // check if the player picked scissors(3) and the computer picked paper(2)
{
playerWinCount++ ;
System.out.println("Player won!");
}
else if(playerPick == 2 && computerPick == 1) // check if the player picked paper(2) and the computer picked rock(1)
{
playerWinCount++ ;
System.out.println("Player won!");
}
else // otherwise, the computer has won this round
{
computerWinCount++ ;
System.out.println("Computer won!") ;
}
}
else
{
System.out.println("It's a tie!");
}
}
}
Let's go point by point.
You aren't taking the user input for determining the choice of playing in a while loop, so your game won't run more than once. You can take that input as:
while (true) {
System.out.println("Play again? Type yes or no.");
String YoN= input.nextLine();
if (YoN.equalsIgnoreCase("yes")) {
game():
} else {
System.out.println("Computer wins: " + Cwin + "/nUser wins: " + Uwin);
break;
}
}
If user gives input other than yes, you're trying to print Cwin and Uwin, but you haven't declared those variables in the scope of main method. So your program won't compile anyways.
You can keep global variables in the class running main method.
public static int Cwin = 0;
public static int Uwin = 0;
Update
I've gone through your code and found a few more problems. As far as I understand, you want to receive choice input from user and validate it in this segment:
if (choice > 1 || choice < 3) {
System.out.println("Invalid entry. Please type 1, 2, or 3.");
}
Well, this condition doesn't supports what you've printed inside, this choice > 1 || choice < 3 condition always gets true. Also, you haven't prompted to take the entry from the user again.
You can fix this issue as below:
while (choice < 1 || choice > 3) {
System.out.println("Invalid entry. Please type 1, 2, or 3.");
choice = console.nextInt();
}
Then you're trying to make random choices for Computer. But you're selecting through upper bound and adding 1 to it. Why not set the bound to 1 more?
int comp = r.nextInt(4);
Then, finally, you're trying to compare the choice and the result. Where result was assigned -1 at the time of declaration and was never changed. That's why it'll never enter any if blocks and the Cwin and Uwin will always print 0. I bet you wanted comp here, in place of result. Also, I've tried to make the program more understandable to user while running.
if (choice == 1 && comp == 2) {
Cwin++;
System.out.println("Computer wins!");
return;
}
if (choice == 2 && comp == 3) {
Cwin++;
System.out.println("Computer wins!");
return;
}
if (choice == 3 && comp == 1) {
Cwin++;
System.out.println("Computer wins!");
return;
}
if (choice == 2 && comp == 1) {
Uwin++;
System.out.println("You win!");
return;
}
if (choice == 3 && comp == 2) {
Uwin++;
System.out.println("You win!");
return;
}
if (choice == 1 && comp == 3) {
Uwin++;
System.out.println("You win!");
return;
}
System.out.println("It's a draw!");
It will work as expected if you fix the aforementioned issues.
Note: I haven't refactored your code, I've just pointed out the problems and fixed it without modifying it much. It can be made lot more better than the current condition. Let's keep the topic for another day's question.
I modify your code somewhat.
You mention in a comment that you don't want to use an array and static variable.
so, I tried some different method hope It will help you.
It is fully working code
import java.util.*;
public class rockPaperScissors {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Welcome To Rock Paper scissors Game Type yes to continue or no for close.");
String YoN = input.nextLine();
if (YoN.equalsIgnoreCase("yes")) {
game();
} else if(YoN.equalsIgnoreCase("yes")) {
System.out.println("Thank You");
}else {
System.out.println("Enter valid input");
}
}
public static void game() {
int Uwin = 0;//user win count
int Cwin = 0;//computer win count
int tie = 0;//Tie count
while (true) {
Scanner input = new Scanner(System.in);
System.out.println("Are you sure!!! Want to continue? Type yes or no.");
String YoN = input.nextLine();
if (YoN.equalsIgnoreCase("yes")) {
Scanner console = new Scanner(System.in);
System.out.println("Choose rock, paper, or scissors. Type 1 for rock, 2 for paper, and 3 for scissors.");
int choice = console.nextInt();
int result = (int) (Math.random()*(3-1)) + 1;
if (choice < 1 || choice > 3) {
System.out.println("Invalid entry. Please type 1, 2, or 3.");
}
if((choice == 1 && result == 3) || (choice == 2 && result == 1) || (choice == 3 && result == 2)) {
System.out.println("Computer Choose"+result);
Uwin++;
}else if((choice == 1 && result == 2) || (choice == 2 && result == 3) || (choice == 3 && result == 1)) {
System.out.println("Computer Choose"+result
);
Cwin++;
}else {
System.out.println("Computer Choose"+result);
tie++;
}
} else if(YoN.equalsIgnoreCase("no")) {
System.out.println("Computer wins: " + Cwin + "\nUser wins: " + Uwin+"\nTie: "+tie);
System.out.println("Thank you");
break;
}else {
System.out.println("Enter valid input");
}
}
}
}
Track the score separately from the individual game
It looks you've written your game() method to play a single game of Rock, Paper, Scissors. In that case, you only need to return one value: who won that single game. Then your main method can keep track of the current scores and print out the totals after it's all done.
Consider an approach like the following:
import java.util.*;
public class rockPaperScissors {
public final static int USER_WON = 1; // Added these constants
public final static int COMPUTER_WON = 2;
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int Uwin = 0;// user win count // Moved from `game()`
int Cwin = 0;// computer win count // Moved from `game()`
System.out.println("Play again? Type yes or no.");
String YoN = input.next();
if (YoN.equalsIgnoreCase("yes")) {
int winner = game(); // Modified this line
if (winner == USER_WON) { // Added this section
Uwin++;
} else {
Cwin++;
}
} else {
System.out.println("Computer wins: " + Cwin + "/nUser wins: " + Uwin);
}
}
public static int game() { // Modified this line
System.out.println("Choose rock, paper, or scissors. Type 1 for rock, 2 for paper, and 3 for scissors.");
Scanner console = new Scanner(System.in);
//// Truncating for brevity ////
if (choice == 3 && result == 1) {
return COMPUTER_WON; // Modified this line
}
if (choice == 2 && result == 1) {
return USER_WON; // Modified this line
}
//// Truncating for brevity ////
}
}
Notice that I moved the Uwin and Cwin variables out of game() and into your main method. Then I changed game() to return an integer instead of nothing (void) and replaced the Cwin++ and Uwin++ statements with a simple return COMPUTER_WON or return USER_WON based on the results of the rock, paper, scissors match. That return value can then be processed in your main method to keep a running total of how many games each player has won.
Use a class
If you're interested in trying something more advanced, consider creating an Object to encapsulate the two values you want to return.
For example, by storing both win counts in a simple Scoreboard object like the one below would enable you to return the two win counts at the same time and encapsulate the process of printing the scoreboard to the screen.
If you go this route, you'd have to make sure that all games reference the same Scoreboard. There are a variety of ways to do this from using a class variable, to passing the Scoreboard as a function parameter to the game() method, to moving all your logic for playing multiple games into the game() method. There are lots of options for you to try out and see which works best for you in this situation.
public class Scoreboard {
private int computerWins;
private int playerWins;
public Scoreboard() {
computerWins = 0;
playerWins = 0;
}
public void addComputerWin() {
computerWins++;
}
public void addPlayerWin() {
playerWins++;
}
#Override
public String toString() {
return "Scoreboard: "
+ "\n - Computer wins: " + computerWins
+ "\n - Player wins: " + playerWins;
}
}

Rockpapergame with rounds and counter variables - java

I am creating a rock paper project which has the following requirement:
Continually plays rounds of rock, paper, scissors until one of the players wins three rounds. At that point, the program outputs the winner and the number of rounds it took them to win. If there is no winner after 10 rounds, the competition is declared a tie
Something seems to be missing which I am not quite able to understand or notice. How would I make my game stop after the rounds and declare a winner?
Note: No arrays, external libraries other than scanner, or any built-in methods of java allowed
This is my attempt:
import java.util.Scanner;
public class Rockpaper{
public static void main(String[]args){
Scanner keyboard = new Scanner(System.in);
String player1 = keyboard.next();
String player2 = keyboard.next();
String player = "Player1";
int round = 1;
boolean go = true;
boolean win = false;
while(go){
if (player1.equals("r") && player2.equals("p")){
win = true;
}
else if (player1.equals("p") && player2.equals("r")){
win = true;
}
else if (player1.equals("p") && player2.equals("s")){
win = true;
}
else if (player1.equals("s") && player2.equals("p")){
win = true;
}
else if (player1.equals("s") && player2.equals("r")){
win = true;
}
else if (player1.equals("r") && player2.equals("s")){
win = true;
}
else if (player1.equals("r") && player2.equals("r")){
win = false;
}
else if (player1.equals("p") && player2.equals("p")){
win = false;
}
else if (player1.equals("s") && player2.equals("s")){
win = false;
}
if (round < 5){
System.out.println(win+" after "+round+" rounds!");
go = false;
}else{
System.out.println("Tie - No winner after "+round+" rounds!");
}
if (player.equals("Player1"){
Player = "Player2";
}else{
Player = "Player1";
}
}
}
}
The problem I see is that there needs to be a separate variable that counts each of the win possibilities, for example, "win1" which would count the player1 win possibility and "win2" that would count the player2 wins. I am not quite sure about the rounds variable that would initially start counting the rounds up to 10 which is the maximum.
Sample input/output:
Currently you read the input only once, before the loop:
String player1 = keyboard.next();
String player2 = keyboard.next();
After every match, you should ask if players should continue playing. If so, then you must ask for their input again. This is, just move the "playerX" variable declaration and initialization inside the loop:
//comment/remove these
//String player1 = keyboard.next();
//String player2 = keyboard.next();
//inside the loop
while(go){
String player1 = keyboard.next();
String player2 = keyboard.next();
if (player1.equals("r") && player2.equals("p")){
/* rest of your code */
}
Also, this section:
if (round < 5){
System.out.println(win+" after "+round+" rounds!");
go = false;
}else{
System.out.println("Tie - No winner after "+round+" rounds!");
}
if (player.equals("Player1"){
Player = "Player2";
}else{
Player = "Player1";
}
}
It seems odd for two things:
round is never increased.
The else after round < 5 will be always executed, wrongly stating that there's a tie.
Reassigning Player variable for asking user input is not necessary. Instead, you could use 2 variables to store names of your players that are initialized before the game begins.
One more thing: instance of Scanner is Closeable, so each time you use it to read user input, you make sure that the instance is closed after is not needed anymore, in this case, at the end of the program.
More hints:
Reduce several if/else with the same output to a single if evaluation
You could make use of methods to ease game result.
With all this in mind, your code may look like this:
import java.util.Scanner;
public class RockPaperScizzorGame {
public static int getGameResult(String player1Move, String player2Move) {
int result = 0; //assume the game will be a tie
//player 2 wins
if (player1Move.equals("r") && player2Move.equals("p")
|| player1.equals("p") && player2.equals("s")
|| player1.equals("s") && player2.equals("r")
) {
result = 2;
}
//player 1 wins
if (player1.equals("p") && player2.equals("r")
|| player1.equals("s") && player2.equals("p")
|| player1.equals("r") && player2.equals("s")) {
result = 1;
}
//return the result: 0, 1 or 2
return result;
}
public static void main (String[] args) {
try (Scanner keyboard = new Scanner(System.in)) {
String player1Name = "Player 1";
String player2Name = "Player 2";
int round = 0;
boolean go = true;
int winsPlayer1 = 0;
int winsPlayer2 = 0;
while (go) {
System.out.println("Make your move " + player1Name + ": ");
String player1Move = keyboard.next();
System.out.println("Make your move " + player2Name + ": ");
String player2Move = keyboard.next();
int gameResult = getGameResult(player1Move, player2Move);
switch(gameResult) {
case 1:
winsPlayer1++;
break;
case 2:
winsPlayer2++;
break;
}
round++;
if (winsPlayer1 == 3) {
System.out.println(player1Name + " won after " + round + " rounds!");
go = false;
} else if (winsPlayer2 == 3) {
System.out.println(player2Name + " won after " + round + " rounds!");
go = false;
} else {
if (round == 5 && winsPlayer1 < 3 && winsPlayer2 < 3) {
System.out.println("Tie - No winner after "+round+" rounds!");
go = false;
}
}
} catch (IOException e) {
System.out.println("Issues when trying to accept user input.");
e.printStacktrace();
}
}
}
You can improve the code even more:
Use more methods to ease the code in main method.
Since your main loop depends more on a counter rather than a boolean flag, you may use a for loop rather than a while.
You may ask for user input for the name of the players.
You may create a class to encapsulate data of your players: name, currentMove, number of wins.
Problems with your code:
Not using separate variables for individual players.
Not putting input statements inside the loop as a result of which the input statements run only once.
Not changing the value of the variable, round but using its value in the condition, if (round < 5) which will always evaluate true if the value of round is not increased.
Solution
import java.util.Scanner;
public class Rockpaper {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int round = 1;
boolean go = true;
int player1Score = 0;
int player2Score = 0;
while (go && round <= 10) {
String player1 = keyboard.next();
String player2 = keyboard.next();
if (player1.equals("r") && player2.equals("p")) {
player2Score++;
} else if (player1.equals("p") && player2.equals("r")) {
player1Score++;
} else if (player1.equals("p") && player2.equals("s")) {
player2Score++;
} else if (player1.equals("s") && player2.equals("p")) {
player1Score++;
} else if (player1.equals("s") && player2.equals("r")) {
player2Score++;
} else if (player1.equals("r") && player2.equals("s")) {
player1Score++;
}
if (player1Score >= 3) {
System.out.println("Player1 wins " + " after " + round + " rounds!");
go = false;
}
if (player2Score >= 3) {
System.out.println("Player2 wins " + " after " + round + " rounds!");
go = false;
}
round++;
}
if (round > 10) {
System.out.println("Tie - No winner after " + (round - 1) + " rounds!");
}
}
}
First sample run:
p
r
r
s
s
s
r
r
p
r
Player1 wins after 5 rounds!
Second sample run:
p
p
p
r
r
r
s
s
p
p
s
s
s
s
p
p
r
p
s
p
Tie - No winner after 10 rounds!

java.util.NoSuchElementException: No line found. Works before, but not later. I don't know why

I'm trying to make a game, and for whatever reason the Scanner works before in a separate method, but not in this one.
Works in:
Scanner in = new Scanner(System.in); // Scanner in case of invalid input
for (int i = 1; i <= p.getSpeed(); i++) { // loop to account for invalid direction
if (d.equalsIgnoreCase("right") || d.equalsIgnoreCase("r") && p.getX() <= width - 2) { // right
if (board[p.getY()][p.getX() + 1] == ' ') {
board[p.getY()][p.getX()] = ' ';
p.setX(p.getX() + 1);
board[p.getY()][p.getX()] = 'P';
}
else { // right not open
System.out.println("Please input a valid direction");
d = in.nextLine();
i--;
}
}
Doesn't work in:
Scanner in = new Scanner(System.in); // Scanner in case of invalid input
int i = 1;
while (i == 1) {
if (d.equalsIgnoreCase("right") || d.equalsIgnoreCase("r") && p.getX() <= width - 2) { // right
for (int j = 0; j <= numZombies - 1; j++) {
if (zombie[j].getX() == p.getX() + 1 && zombie[j].getY() == p.getY()) { // checks each zombie to see if it is one to the right of the player
zombie[j].subtractHealth(p.getAttack());
break;
}
if (zombie[j].getX() == p.getX() + 2 && zombie[j].getY() == p.getY()) {
zombie[j].subtractHealth(p.getAttack());
break;
}else if (j == numZombies - 1) { // if no zombies are found
System.out.println("There is no zombie there, please insert a new direction");
d = in.nextLine();
i--;
}
}
}
}
The methods all work and the logic is fine, I just don't know why it works for the first but not the second one
Closing the first scanner was the problem, getting rid of that code fixed it. Thanks Charles

PlayerDecision Trouble

I am trying to write up a game of rock-paper-scissors, and I think I am almost done. However, I am having trouble calling one last method.
This is my code so far:
import java.util.*;
public class RPS {
public static void main(String[] args) {
PlayerChoice();
ComputerChoice();
System.out.println("You played " + playerDecision + ". The computer played " + computerPlay +".");
}
public static void PlayerChoice() {
System.out.print("Type R(ock), P(aper) or S(cissors): ");
int r = "rock";
int p = "paper";
int s = "scissors";
String r = console.r();
string p = console.p();
String s = console.s();
Random rand = new Random();
int playerDecision = nextInt();
if(playerDecision.equalsIgnoreCase("r")){
System.out.println("rock");
}else if(playerDecision.equalsIgnoreCase("p")){
System.out.println("paper");
}else if(playerDecision.equalsIgnoreCase("s")){
System.out.println("scissors");
}
while(!nextInt = 'r' || 'p' || 's'){
System.out.println("Invalid answer. Re-type R, P or S: ");
}
System.out.print(playerDecision);
}
public static void ComputerChoice() {
int rock = 1, paper = 2, scissors = 3;
Random rand = new Random();
int computerPlay = rand.nextInt(3) + 1;
if(computerPlay == 0){
System.out.println("rock");
}else if(computerPlay == 1){
System.out.println("paper");
}else if(computerPlay == 2){
System.out.println("scissors");
}
System.out.print(computerPlay);
}
}
However, my code cannot find the playerDecision or computerPlay. I want the method PlayerChoice to put out the players decision, as stated in its name. If they put in "R", register rock, "P" for paper, and "S" for scissors, regardless of case. The ComputerChoice method seems to be working fine.
Does anybody know what am I doing wrong while calling the decisions? I do not know why it won't read right, and I am out of ideas.
Does anybody have a suggestion for me?
Your "short-cut" syntax is illegal. And your logic is a bit off. while(!nextInt = 'r' || 'p' || 's'){ should be something like
while (nextInt != 'r' && nextInt != 'p' && nextInt != 's') {
or apply DeMorgan's Laws, and get
while (!(nextInt == 'r' || nextInt == 'p' || nextInt == 's')) {
Also, ComputerChoice is not "working fine". You are generating values in the range 1 to 3 (inclusive), but you are only checking zero, one and two. Remove the + 1 in int computerPlay = rand.nextInt(3) + 1; (or fix the if logic).

Dice Roll Simulation

So I am lost. This is the goal:
Ask how many times to roll one six-sided dice.
Randomly roll this dice.
Print out how many times each number between one and six appeared
Is this loop thing on the right track? What should I begin with I'm really confused sorry
while(dice > 0)
{
rolldice = gen.nextInt(6) + 1; //(1-6)
if (rolldice == 1)
{
one++;
}
else if (rolldice == 2)
{
two++;
}
else if (rolldice == 3)
{
three++;
}
else if (rolldice == 4)
{
four++;
}
else if (rolldice == 5)
{
five++;
}
else if (rolldice == 6)
{
six++;
}
}
Scanner in = new Scanner(System.in);
Random gen = new Random();
int rollDice;
int one = 0, two = 0, three = 0, four = 0, five = 0, six = 0;
System.out.println("How many die do you want to roll: ");
int dice = in.nextInt();
while(dice > 0)
{
rolldice = gen.nextInt(6) + 1; //(1-6)
if (rolldice == 1)
{
one++;
}
else if (rolldice == 2)
{
two++;
}
else if (rolldice == 3)
{
three++;
}
else if (rolldice == 4)
{
four++;
}
else if (rolldice == 5)
{
five++;
}
else if (rolldice == 6)
{
six++;
}
dice--;
}
Now just print out the variables and you are done!
I could also do this with a switch statement, but I'll let you figure out how to convert if thats what you want to use.
Im assuming the dice integer is the input from the user. If you decrement dice each time you iterate, you will roll the dice(go through the loop) as many times as the user asked.
Not sure if you have implemented it so that the user can input a number of dicerolls yet, if thats what you need help with take a look at Scanner.

Categories