How do I parse a string as an Integer - java

OK I have my rock,paper,scissors game working. All but the Q to quit works. Since my scanner is only taking integers, how can I pass the "Q" string to it. I would assume I just add a simple if(string.equals("Q") {break;} in the while loop and I'll be good to go. Let me know what you think.
import java.util.Scanner;
import java.util.Random;
public class RockPaperScissors
{
/**
* (Insert a brief description that describes the purpose of this method)
*
* #param args
*/
public static void main(String[] args)
{
int compint;
String usermove = "";
String compmove = "";
String winner = "";
int count = 0;
int input=0;
Scanner in = new Scanner(System.in);
Random gen = new Random();
System.out.print("Enter Rock(1), Paper(2), Scissors(3) {Q to quit]: ");
input=in.nextInt();
while (count < 3)
{
compint = gen.nextInt(3) + 1;
if (input == 1)
{
usermove = "Rock";
}
else if (input == 2)
{
usermove = "Paper";
}
else if (input == 3)
{
usermove = "Scissors";
}
if (compint == 1)
{
compmove = "Rock";
}
else if (compint == 2)
{
compmove = "Paper";
}
else if (compint == 3)
{
compmove = "Scissors";
}
if (compint == input)
{
winner = "TIE";
}
else if (compint == 1 && input == 3)
{
winner = "COMPUTER";
}
else if (compint == 2 && input == 1)
{
winner = "COMPUTER";
}
else if (compint == 3 && input == 2)
{
winner = "COMPUTER";
}
else
{
winner = "USER";
}
System.out.print("Computer: " + compmove + " | ");
System.out.print("You: " + usermove + " | ");
System.out.println("Winner: " + winner);
System.out.println();
count++;
System.out.print("Enter Rock(1), Paper(2), Scissors(3) {Q to quit]: ");
input = in.nextInt();
}
}
}

This code worked for me:
package com.sandbox;
import java.util.Random;
import java.util.Scanner;
public class Sandbox {
/**
* (Insert a brief description that describes the purpose of this method)
*
* #param args
*/
public static void main(String[] args) {
int compint;
String usermove = "";
String compmove = "";
String winner = "";
int count = 0;
String rawInput = null;
int input = 0;
Scanner in = new Scanner(System.in);
Random gen = new Random();
System.out.print("Enter Rock(1), Paper(2), Scissors(3) {Q to quit]: ");
rawInput = in.next();
if ("Q".equals(rawInput)) {
return; //exit main
}
input = Integer.parseInt(rawInput);
while (count < 3) {
compint = gen.nextInt(3) + 1;
if (input == 1) {
usermove = "Rock";
} else if (input == 2) {
usermove = "Paper";
} else if (input == 3) {
usermove = "Scissors";
}
if (compint == 1) {
compmove = "Rock";
} else if (compint == 2) {
compmove = "Paper";
} else if (compint == 3) {
compmove = "Scissors";
}
if (compint == input) {
winner = "TIE";
} else if (compint == 1 && input == 3) {
winner = "COMPUTER";
} else if (compint == 2 && input == 1) {
winner = "COMPUTER";
} else if (compint == 3 && input == 2) {
winner = "COMPUTER";
} else {
winner = "USER";
}
System.out.print("Computer: " + compmove + " | ");
System.out.print("You: " + usermove + " | ");
System.out.println("Winner: " + winner);
System.out.println();
count++;
System.out.print("Enter Rock(1), Paper(2), Scissors(3) {Q to quit]: ");
input = in.nextInt();
}
}
}
What I'm doing is taking the input as a String. I save that into a variable named rawInput. Then I check if that's equal to "Q". If it is, I quit. If it's not, I convert it to an Integer and use the rest of your logic.
The #MadProgrammer had some good advice on how to make this code more fault tolerant which I'd follow but I posted this code because it directly answers your question.

You have two options:
Either use a numerical value to quit (0 or -1), or
Convert your program to accept both strings and numbers. The way you do this is through Integer.parseInt().
// This assumes that input is of type String instead
int option = 0;
System.out.print("Enter Rock(1), Paper(2), Scissors(3) {Q to quit]: ");
input=in.nextLine();
try {
option = Integer.parseInt(input);
} catch (NumberFormatException nfe) {
// wasn't a number, so it was either bogus input or the quit option.
if("Q".equalsIgnoreCase(input)) {
System.out.println("Quitting.");
System.exit(0);
} else {
System.out.println("Bogus input.");
}
}
while (count < 3 && option != 0) {
// logic
}

Integer.parseInt(myString)
Just plug in myString
class JTest
{
public static void main(String[] args)
{
String a = "5";
int b = Integer.parseInt(a);
System.out.println(b);
}
}

provided user doesnt input other than 0-9 and "q" or "Q" then it should work:
Scanner sc = new Scanner(System.in);
String a = sc.next();
if(a.equalsIgnoreCase("q")){
System.out.println("quit game");
}
else{
int input = Integer.parseInt(a);
}

Change your program as follows :
public static void main(String... args) {
Scanner in = new Scanner(System.in);
int compint;
String usermove = "";
String compmove = "";
String winner = "";
int count = 0;
int input = 0;
Random gen = new Random();
Set<Boolean> set = new HashSet<Boolean>();
boolean contains = false;
while (count < 3) {
System.out.print("Enter Rock(1), Paper(2), Scissors(3) {Q to quit]: ");
String nextLine=in.next().trim();
do {
for (int index = 0; index < nextLine.length(); index++) {
set.add(Character.isLetter(nextLine.charAt(index)));
}
contains = set.contains(true);
if(contains) {
if (nextLine.equals("Q")) {
System.out.println("program exited");
return;
} else {
System.out .print("Re-enter Rock(1), Paper(2), Scissors(3) {Q to quit]: ");
nextLine=in.next();
}
} else {
input=Integer.parseInt(nextLine);
}
set.remove(true);
} while (contains);
compint = gen.nextInt(3) + 1;
if (input == 1) {
usermove = "Rock";
} else if (input == 2) {
usermove = "Paper";
} else if (input == 3) {
usermove = "Scissors";
}
if (compint == 1) {
compmove = "Rock";
} else if (compint == 2) {
compmove = "Paper";
} else if (compint == 3) {
compmove = "Scissors";
}
if (compint == input) {
winner = "TIE";
} else if (compint == 1 && input == 3) {
winner = "COMPUTER";
} else if (compint == 2 && input == 1) {
winner = "COMPUTER";
} else if (compint == 3 && input == 2) {
winner = "COMPUTER";
} else {
winner = "USER";
}
System.out.print("Computer: " + compmove + " | ");
System.out.print("You: " + usermove + " | ");
System.out.println("Winner: " + winner);
System.out.println();
count++;
}
System.out.println("program's end");
}

Related

Issues with counter and for loop. Assitance appreciated

Having issues with my for loops and the counter it should add up each value of the numbers I have added and ask me what that value is, at the end of the for loop. I added the number-2 to end the loop, so I tried to subtract it from the total before printing, but it doesn't work.
Help!
import java.util.*;
public class CountingCards {
public static void main(String[] args) {
Counting();
}
public static void Counting() {
Random rand = new Random();
int count = 0;
int sum = 0;
Scanner in = new Scanner(System.in);
for (int a = 0; a < 110; a++) {
int player = rand.nextInt((10) + 1);
System.out.println(" ");
System.out.println("You got this card: " + player);
System.out.println("What is the value of that card");
int answer = in.nextInt();
if (player == 1) {
if (answer == -1) {
System.out.println("That is CORRECT");
count = -1;
}
if (answer != -1) {
System.out.println("Sorry, that is INCORRECT");
count = -1;
}
}
if (player == 2) {
if (answer == -1) {
count = -1;
System.out.println("That is CORRECT");
}
if (answer != -1) {
count = -1;
System.out.println("Sorry, that is INCORRECT");
}
}
if (player == 3) {
if (answer == -1) {
count = -1;
System.out.println("That is CORRECT");
}
if (answer != -1) {
count = -1;
System.out.println("Sorry, that is INCORRECT");
}
}
if (player == 4) {
if (answer == -1) {
count = -1;
System.out.println("That is CORRECT");
}
if (answer != -1) {
count = -1;
System.out.println("Sorry, that is INCORRECT");
}
}
if (player == 5) {
if (answer == -1) {
count = -1;
System.out.println("That is CORRECT");
}
if (answer != -1) {
count = -1;
System.out.println("Sorry, that is INCORRECT");
}
}
if (player == 6) {
if (answer == -1) {
count = -1;
System.out.println("That is CORRECT");
}
if (answer != -1) {
count = -1;
System.out.println("Sorry, that is INCORRECT");
}
}
if (player == 7) {
if (answer == 0) {
count = 0;
System.out.println("That is CORRECT");
}
if (answer != 0) {
count = 0;
System.out.println("Sorry, that is INCORRECT");
}
}
if (player == 8) {
if (answer == 0) {
count = 0;
System.out.println("That is CORRECT");
}
if (answer != 0) {
count = 0;
System.out.println("Sorry, that is INCORRECT");
}
}
if (player == 9) {
if (answer == 0) {
count = 0;
System.out.println("That is CORRECT");
}
if (answer != 0) {
count = 0;
System.out.println("Sorry, that is INCORRECT");
}
}
if (player == 10) {
if (answer == 1) {
count = 1;
System.out.println("That is CORRECT");
}
if (answer != 1) {
count = 1;
System.out.println("Sorry, that is INCORRECT");
}
}
if (answer == -2) {
sum = sum - 2;
System.out.println("Your total count is: " + sum);
break;
}
sum = sum + count;
}
}
}
the sum should add all the counters I've acquired, throughout the for loop, and ask me each time to see if the answer I give them adds to the total counter each time. It's ways off and I dont know why
I could not understand what exactly this game is; but looking at your code, I guessed that you have made a logical mistake in the following line:
int player = rand.nextInt((10) + 1);
It should be
int player = rand.nextInt(10) + 1;
Second thing is, you can replace the following code:
if (answer == -1) {
System.out.println("That is CORRECT");
count = -1;
}
if (answer != -1) {
System.out.println("Sorry, that is INCORRECT");
count = -1;
}
with
if (answer == -1) {
System.out.println("That is CORRECT");
count = -1;
} else {
System.out.println("Sorry, that is INCORRECT");
count = -1;
}
For more help, you need to clearly mention the rules of the game.
Changing
int player = rand.nextInt((10) + 1);
to
int player = rand.nextInt(10) + 1;
should solve your problem. Hope it helps..
Have a good day !

Variable not being recognized in method

I am relatively new to Java, and I am writing a simple program to play rock, paper, scissors. This is the code:
import java.util.Random;
import java.util.Scanner;
public class Main {
public static String comChoice() {
Random rand = new Random();
int num = rand.nextInt(299) + 1;
if (num >= 1 && num <= 99) {
String pick = "SCISSORS";
} else if (num >= 100 && num <= 199) {
String pick = "ROCK";
} else if (num >= 200 && num <= 299) {
String pick = "PAPER";
}
return pick;
}
public static void main(String args[]) {
int wins = 0;
int losses = 0;
int ties = 0;
while (1 == 1) {
Scanner s = new Scanner(System.in);
System.out.println("Would you like to play Rock Paper Scissors? Y/N");
String n = s.next();
if (n.equalsIgnoreCase("Y")) {
Scanner t = new Scanner(System.in);
System.out.println("Enter your pick: rock, paper, or scissors");
String userChoice = t.next();
String pick = comChoice();
if (userChoice.equalsIgnoreCase("SCISSORS") && pick.equalsIgnoreCase("SCISSORS")) {
System.out.println("TIE");
ties++;
} else if (userChoice.equalsIgnoreCase("ROCK") && pick.equalsIgnoreCase("SCISSORS")) {
System.out.println("WIN");
wins++;
} else if (userChoice.equalsIgnoreCase("PAPER") && pick.equalsIgnoreCase("SCISSORS")) {
System.out.println("LOSE");
losses++;
} else if (userChoice.equalsIgnoreCase("SCISSORS") && pick.equalsIgnoreCase("ROCK")) {
System.out.println("LOSE");
losses++;
} else if (userChoice.equalsIgnoreCase("SCISSORS") && pick.equalsIgnoreCase("PAPER")) {
System.out.println("WIN");
wins++;
} else {
System.out.println("Enter a valid choice");
}
} else {
System.out.println("You won " + wins + " matches");
System.out.println("You tied " + ties + " matches");
System.out.println("You lost " + losses + " matches");
break;
}
}
}
}
I'm getting an error in my method which says this:
Main.java:23: error: cannot find symbol
return pick;
^
symbol: variable pick
location: class Main
1 error
exit status 1
I can't figure out how to fix this error. I would appreciate your input as well as any other general advice
Thanks
Your variable is only visible in the if statement. Read about scopes.
Change to:
import java.util.Scanner;
import java.util.Random;
public class Main {
public static String comChoice() {
Random rand = new Random();
int num = rand.nextInt(299) + 1;
String pick = null;
if (num >= 1 && num <= 99) {
pick = "SCISSORS";
} else if (num >= 100 && num <= 199) {
pick = "ROCK";
} else if (num >= 200 && num <= 299) {
pick = "PAPER";
}
return pick;
}
....
}
pick is out of scope. Try declaring at the start of the comChoice method.
Hence :
public static String comChoice() {
String pick=null;
Random rand = new Random();
int num = rand.nextInt(299) + 1;
if (num >= 1 && num <= 99) {
pick = "SCISSORS";
} else if (num >= 100 && num <= 199) {
pick = "ROCK";
} else if (num >= 200 && num <= 299) {
pick = "PAPER";
}
return pick;
}
variable pick is out of scope. You have to declare it outside the all if else statements. if all if else condition fail then comChoice method will not be able to find variable pick (as it is declared inside the if else block only)which it has to return.
corrected code
import java.util.Scanner;
import java.util.Random;
public class Main
{
public static String comChoice()
{
Random rand = new Random();
int num = rand.nextInt(299) + 1;
String pick = "";
if(num >= 1 && num <= 99)
{
pick = "SCISSORS";
}
else if (num >= 100 && num <= 199)
{
pick = "ROCK";
}
else if (num >= 200 && num <= 299)
{
pick = "PAPER";
}
return pick;
}
public static void main (String args[])
{
int wins = 0;
int losses = 0;
int ties = 0;
while (1 == 1)
{
Scanner s = new Scanner (System.in);
System.out.println("Would you like to play Rock Paper Scissors? Y/N");
String n = s.next();
if (n.equalsIgnoreCase("Y"))
{
Scanner t = new Scanner (System.in);
System.out.println("Enter your pick: rock, paper, or scissors");
String userChoice = t.next();
String pick = comChoice();
if (userChoice.equalsIgnoreCase("SCISSORS") && pick.equalsIgnoreCase("SCISSORS"))
{
System.out.println("TIE");
ties++;
}
else if (userChoice.equalsIgnoreCase("ROCK") && pick.equalsIgnoreCase("SCISSORS"))
{
System.out.println("WIN");
wins++;
}
else if (userChoice.equalsIgnoreCase("PAPER") && pick.equalsIgnoreCase("SCISSORS"))
{
System.out.println("LOSE");
losses++;
}
else if (userChoice.equalsIgnoreCase("SCISSORS") && pick.equalsIgnoreCase("ROCK"))
{
System.out.println("LOSE");
losses++;
}
else if (userChoice.equalsIgnoreCase("SCISSORS") && pick.equalsIgnoreCase("PAPER"))
{
System.out.println("WIN");
wins++;
}
else
{
System.out.println("Enter a valid choice");
}
}
else
{
System.out.println("You won " + wins + " matches");
System.out.println("You tied " + ties + " matches");
System.out.println("You lost " + losses + " matches");
break;
}
}
}
}
You declared your variable pick in the if else structure. Doing this causes the problem that your variable cannot be accessed from outside that if else structure. In simple words, the variable pick's scope is limited to your if else structure. You have to declare your variable (and initialize it as well, otherwise you'll get an error in your case) outside of the if else structure. Like this:
String pick = null;
if(num >= 1 && num <= 99) {
...
...
...// All your if's and else's
}
return pick;
Hope this helps!

Choosing Between 2 games in one code

I am doing a project to make a user login, then ask the user to select which game to play, then write the code for the game. I have done everything apart from being able to choose to between the 2 games. Any tips on how to do this would greatly help!
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.Scanner;
import java.io.InputStreamReader;
public class SkillsDemo31 {
private static boolean again = true;
private static int action;
public static void main(String[] args) throws IOException {
//***************************
//Login
//***************************
class User {
User (String username, String password)
{
this.username = username;
this.password = password;
}
String GetUsername() {return username;}
String GetPassword() {return password;}
private String username;
private String password;
}
String greeting = "Hello";
String username;
String password;
// Used to hold the instance of a user who successfully logged in
User loggedInUser = null;
// Create an empty list to hold users
List<User> listOfUsers = new ArrayList<>();
// Add 3 users to the list
listOfUsers.add(new User("Gerry","spintown"));
listOfUsers.add(new User("Evelyn","poker"));
listOfUsers.add(new User("Joan","bonus"));
BufferedReader br = new BufferedReader(
new InputStreamReader(System.in));
System.out.println("*** Welcome to the program ***\n");
System.out.println(greeting);
System.out.println("Please type your username :");
username = br.readLine();
System.out.println("Please type your password :");
password = br.readLine();
for (User user : listOfUsers)
{
if (user.GetUsername().equals(username))
{
if (user.GetPassword().equals(password))
{
loggedInUser = user;
// when a user is found, "break" stops iterating through the list
break;
}
}
}
// if loggedInUser was changed from null, it was successful
if (loggedInUser != null)
{
System.out.println("User successfully logged in: "+loggedInUser.GetUsername());
}
else
{
System.out.println("Invalid username/password combination");
}
//**********************************
//Choice of Games
//**********************************
again = true;
action = 0;
while (again)
{
System.out.println("Please type 1 for Rock, Paper, Scissors or 2 for Play pick up sticks:");
action = Integer.parseInt(br.readLine());
if (action == 1)
{
System.out.println("\nYou have chosen to play Rock, Paper, Scissors");
}
else if (action == 2)
{
System.out.println("\nYou have chosen to Play pick up sticks");
again = false;
}
//******************************
//Rock,Paper,Scissors
//********************************
Random rnd = new Random();
int input;
int score = 0;
int B = 1;
System.out.println("Pick 1,2, or 3 for:");
System.out.println("Rock (1), Paper(2), or Scissors (3)");
while (B != 0) {
// 1 = rock
// 2 = paper
// 3 = scissors
// N= Integer.parseInt(br.readLine())
int Rock = 1, Paper = 2, Scissor = 3;
input = Integer.parseInt(br.readLine());
int randomNumber = rnd.nextInt(3 - 1 + 1) + 1;
if (randomNumber == Rock) {
if (input == Rock) {
System.out.println("Rock Vs. Rock: Tie");
} else if (input == Paper) {
System.out.println("Paper Vs. Rock: You Win!");
System.out.println("Congratulations!");
score++;
} else if (input == Scissor) {
System.out.println("Scissors Vs. Rock: You Lose");
}
} else if (randomNumber == Paper) {
if (input == Rock) {
System.out.println("Rock Vs. Paper: You Loose");
} else if (input == Paper) {
System.out.println("Paper Vs. Paper: Tie");
} else if (input == Scissor) {
System.out.println("Scissors Vs. Paper: You Win");
System.out.println("Congratulations!");
score++;
}
} else if (randomNumber == Scissor) {
if (input == Rock) {
System.out.println("Rock Vs. Scissors: You Win");
System.out.println("Congratulations!");
score++;
} else if (input == Paper) {
System.out.println("Paper Vs. Scissors: You Loose");
} else if (input == Scissor) {
System.out.println("Scissors Vs. Scissors: Tie");
}
}
int Y=5, N=10;
System.out.println("Your score is "+ score);
System.out.println("Do you want to play again? Press(5) For Yes/(10) For No");
input = Integer.parseInt(br.readLine());
if(input==Y){
B=1;
System.out.println("Rock, Paper,Scissors");
}
else if(input==N)
{System.exit(0);
System.out.println("Have A Good Day!");
}
//***********************
//Pick Up Sticks
//***********************
Scanner scanner = new Scanner(System.in);
while (true) {
int numSticks = 21;
System.out.println("Would You Like to go first? (Yes/No)");
Scanner input1 = new Scanner(System.in);
String goFirst = input1.nextLine();
Scanner take = new Scanner (System.in);
int numToTake = 0;
int score2 = 0;
while (numSticks > 0) {
if (goFirst.equals("Yes") || goFirst.equals("yes")) {
System.out.println("There are " + numSticks + " sticks ");
System.out.println("How many sticks do you want to take (1 or 2)");
numToTake = take.nextInt();
if (numToTake > 2) {
numToTake = 2;
}
else if (numToTake < 1) {
numToTake = 1;
}
numSticks = numSticks - numToTake;
if (numSticks <= 0) {
System.out.println("You lose");
System.out.println("Your score is " + score );
}
else {
if((numSticks - 2) % 3 == 0 || numSticks - 2 == 0) {
numToTake = 1;
}
else {
numToTake = 2;
}
System.out.println("Computer takes " + numToTake + " sticks " );
numSticks = numSticks - numToTake;
if (numSticks <= 0) {
System.out.println(" You win ");
score++;
System.out.println("Your score is " + score );
}
}
}
else {
if((numSticks - 2) % 3 == 0 || numSticks - 2 == 0) {
numToTake = 1;
}
else {
numToTake = 2;
}
System.out.println("Computer takes " + numToTake + " sticks " );
numSticks = numSticks - numToTake;
if (numSticks <= 0) {
System.out.println("You win");
score++;
System.out.println("Your score is " + score );
}
else {
System.out.println("There are " + numSticks + " sticks ");
System.out.println("How many sticks do you want to take (1 or 2)");
numToTake = take.nextInt();
if (numToTake > 2) {
numToTake = 2;
}
else if (numToTake < 1){
numToTake = 1;
}
numSticks = numSticks - numToTake;
if(numSticks <0){
System.out.println("You win");
score++;
}
}
}
}
System.out.println("Do you want to play again, type (5) for yes or (10) for no");
if (scanner.nextLine().equals("10")) {
break;
}
}
}
}
}
You should create for every game a class and create a start method there to start the game based on your user input for example:
System.out.println("Please type 1 for game 1 or 2 for game2:");
action = Integer.parseInt(br.readLine());
if (action == 1)
{
System.out.println("\nYou have chosen to game 1");
Game1 game1 = new Game1();
game1.start();
}
else if (action == 2)
{
System.out.println("\nYou have chosen game 2");
Game2 game2 = new Game2();
game2.start();
}
This code is based on your code.
Bob, I just check through your code.
According to what I saw, my understanding of your question is that "After user login and selected the game type, both game would run subsequently, while you only want to run the game user chose".
If that is the case, then the solution is easy:
Take the games code parts out from the
while(again){
// In this block, only keeps your user choice code.
}
block. That block would be just for getting user's choice.
After that choice block, you get your users' choice from variable "action". Now you just need to add a if block as below:
if(action == 1){
// Put your Rock,Paper,Scissors game code here, as user chose 1
//******************************
//Rock,Paper,Scissors
//********************************
...
}else if(action == 2){
// Put your Pick Up Sticks game code here, as user chose 2.
//***********************
//Pick Up Sticks
//***********************
...
}
As you only want to run one game at a time, you need a "IF" condition to tell the code which game to run.
So just "IF" is enough, but separating the "Choice" part and "Game" part, from my opinion, would make the code more simpler and easier to be understood.

Encountering Error with Pig Code

My variable names are pretty stupid near the bottom but that's not the point. Line 110 says that I'm making an else statement without the if and I'm nearly certain the if is there. Please help in any way you can.
Thank you
import java.util.*;
public class hw7
{
public static void main(String[] args)
{
int turnScores = 0;
int totalScores = 0;
int turnScores2 = 0;
int totalScores2 = 0;
int dice;
int dice2;
String input = "r";
char repeat;
boolean peppers;
peppers = true;
Scanner keyboard = new Scanner(System.in);
Random randomNumbers = new Random();
System.out.println("Welcome to the game of Pig!\n");
while(totalScores < 20 || totalScores2 < 20)
{
do
{
dice = randomNumbers.nextInt(6) + 1;
System.out.println("You rolled: " + dice);
if(dice == 1)
{
turnScores = 0;
System.out.print("Your lose your turn!");
System.out.println("Your Total is " + totalScores);
break;
}
else
{
turnScores += dice;
System.out.print("Your turn score is " + turnScores);
System.out.println(" and your total scores is " + totalScores);
System.out.println("If you hold, you will have " + turnScores
+ " points.");
System.out.println("Enter 'r' to roll again, 'h' to hold.");
input = keyboard.nextLine();
repeat = input.charAt(0);
if(repeat == 'h')
{
break;
}
}
}
while(input.equalsIgnoreCase("r") || dice != 1);
totalScores += turnScores;
peppers = peppers(turnScores, turnScores2);
System.out.println("Your scores is " + totalScores);
turnScores = 0;
System.out.println();
System.out.println("It is the computer's turn.");
do
{
dice2 = randomNumbers.nextInt(6) + 1;
System.out.println("The computer rolled: " + dice2);
if(dice2 == 1)
{
turnScores2 = 0;
System.out.print("The computer lost its turn!");
System.out.println(" Computer total is " + totalScores2);
break;
}
else
{
turnScores2 += dice2;
if(turnScores2 >= 20 || (totalScores2 + turnScores2) >= 20 )
{
System.out.println("The computer holds");
break;
}
}
}
while(dice2 != 1 || turnScores2 < 20);
totalScores2 += turnScores2;
System.out.println("The computer's scores is " + totalScores2 + "\n");
turnScores2 = 0;
}
}
public static boolean peppers(int chili, int ghost)
{
boolean done;
done = true;
if(chili >= 20);
{
done = false;
System.out.println(" YOU WIN!!!");
return done;
}
else (ghost >= 20);
{
done = false;
System.out.println(" COMPUTER WINS");
return done;
}
/*else
{
return done;
}
*/
}
}
Try removing the semicolons in if(chili >= 20); and else (ghost >= 20);.
public static boolean peppers(int chili, int ghost)
{
boolean done;
done = true;
if(chili >= 20)
{
done = false;
System.out.println(" YOU WIN!!!");
}
else if (ghost >= 20)
{
System.out.println(" COMPUTER WINS");
}
return done;
}
replace
else (ghost >= 20);
with
else if (ghost >= 20)
and remove the semicolons after the if-statement.

Rock, paper, scissors simple game in java

Hi I am making a simple rock, paper, scissors game and was having some trouble getting my compare method to get executed. The game prompts the user for input, and then using the computersTurn method to allow the computer to randomly select rock paper or scissors. When I try and pass both these values into my compare method, it doesn't seem to work. Any suggestions would be awesome!
import java.util.Scanner;
public class sillyGame {
public static void compare (String choice1, String choice2)
{
if (choice1.equals(choice2))
{
System.out.println("The result is a tie!");
}
if (choice1.contains("rock"))
{
if (choice2.contains("scissors"))
{
System.out.println("rock wins");
}
if (choice2.contains("paper"))
{
System.out.println("paper wins");
}
}
if (choice1.contains("scissors"))
{
if (choice2.contains("rock"))
{
System.out.println("rock wins");
}
if (choice2.contains("paper"))
{
System.out.println("scissors wins");
}
}
if (choice1.contains("paper"))
{
if (choice2.contains("rock"))
{
System.out.println("paper wins");
}
if (choice2.contains("scissors"))
{
System.out.println("scissors wins");
}
}
}
public static String computersTurn(String compFinalChoice, double randomNum){
randomNum = Math.random();
if (randomNum < 0.34)
{
compFinalChoice = "rock";
}
else if(randomNum <= 0.67)
{
compFinalChoice = "paper";
}
else
{
compFinalChoice = "scissors";
}
System.out.println("The computer chooses " + compFinalChoice);
return compFinalChoice;
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Do you choose rock, paper or scissors?");
String userChoice = scan.nextLine();
String computerDec = " ";
double rand = 0.0;
computersTurn(computerDec, rand);
compare(userChoice, computerDec);
}
Your computersTurn method doesn't need any parameters. You're just passing it " " and 0.0.
Try changing it to this method:
public static String computersTurn() {
// declare them here
double randomNum = Math.random();
String compFinalChoice = "";
if (randomNum < 0.34) {
compFinalChoice = "rock";
}
else if(randomNum <= 0.67) {
compFinalChoice = "paper";
}
else {
compFinalChoice = "scissors";
}
System.out.println("The computer chooses " + compFinalChoice);
return compFinalChoice;
}
And then in your main method, make sure when you call the computersTurn() method, you assign it to a String. Calling it does nothing for you; you need to keep the return value:
public static void main(String args[])
{
Scanner scan = new Scanner(System.in);
System.out.println("Do you choose rock, paper or scissors?");
String userChoice = scan.nextLine();
String computerDec = computersTurn(); // assign it here
compare(userChoice, computerDec);
}
You cannot update a String (or a double) from a caller so I think you should re-factor computersTurn like so
public static String computersTurn() {
String choice = "scissors";
double randomNum = Math.random();
if (randomNum < 0.34) {
choice = "rock";
} else if (randomNum <= 0.67) {
choice = "paper";
}
System.out.println("The computer chooses "
+ choice);
return choice;
}
Then you can do something like this in main
String computerDec = computersTurn();
or
String userChoice = scan.nextLine();
compare(userChoice, computersTurn());

Categories