Trouble with nested if - else statements - java

I am very new at coding and attempted to make a rock paper scissors code based on one I saw on here. However, when the system is supposed to output the result of the game after in prints what the computer played, it just does not print. Any ideas? Thanks!
import java.util.Scanner;
import java.util.Random;
public class Rock {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
Random gen = new Random();
System.out.println("Hey, let's play Rock, Paper, Scissors!\n" +
"Please enter a move.\n" + "Rock = R, Paper" +
"= P, and Scissors = S.");
int computerInt = gen.nextInt(3)+1;
String computerPlay = "";
if (computerInt == 1)
computerPlay = "R";
else if (computerInt == 2)
computerPlay = "P";
else if (computerInt == 3)
computerPlay = "P";
System.out.print("Please enter your play: ");
String personPlay = scan.next();
personPlay = personPlay.toUpperCase();
System.out.println("Computer play is: " + computerPlay);
if (personPlay.equals(computerPlay))
System.out.println("It's a tie!");
else if (personPlay.equals("R"))
if (computerPlay.equals("S"))
System.out.println("Rock crushes scissors. You win!!");
else if (computerPlay.equals("P"))
System.out.println("Paper eats rock. You lose!!");
else if (personPlay.equals("P"))
if (computerPlay.equals("S"))
System.out.println("Scissor cuts paper. You lose!!");
else if (computerPlay.equals("R"))
System.out.println("Paper eats rock. You win!!");
else if (personPlay.equals("S"))
if (computerPlay.equals("P"))
System.out.println("Scissor cuts paper. You win!!");
else if (computerPlay.equals("R"))
System.out.println("Rock breaks scissors. You lose!!");
else
System.out.println("Invalid user input.");
}
}

The nesting of your if statements is totally wrong. Your indentation (kind of almost) hints at how you wish your code be executed, but the compiler does not care at all about your indentation, it only obeys the rules of the java language.
Multiple nested conditional statements like if() else if() if() are notoriously hard to determine (by a human) how they will be executed.
So: never use more than one statement without curly braces. (Some even say to always use curly braces, even if you have only one statement.)
When there is even the slightest ambiguity, (as there is in the code you have written,) make sure to always add curly braces to ensure that the compiler will compile your code the way you intend it to.
Then, your code will (probably) work.

The two big things in coding are making your code both easy to read and functional. Those if statements do not fulfill either of those needs. Also you do not use curly braces... Use curly braces{}! This is your code but I have organised it to be a little more clean. Also I honestly don't know exactly why it didn't print in your original code, but that is not the problem. This one works.
import java.util.Random;
import java.util.Scanner;
public class RockPaperScissors {
private static Scanner scan = new Scanner(System.in);
public static void main(String[] args) {
String personPlay;
String computerPlay = "";
int computerInt;
Random gen = new Random();
System.out.println("Hey, let's play Rock, Paper, Scissors!\n" + "Please enter a move.\n" + "Rock = R, Paper"
+ "= P, and Scissors = S.");
computerInt = gen.nextInt(3) + 1;
if (computerInt == 1) {
computerPlay = "R";
}
if (computerInt == 2) {
computerPlay = "P";
}
if (computerInt == 3) {
computerPlay = "P";
}
System.out.print("Please enter your play: ");
personPlay = scan.next();
personPlay = personPlay.toUpperCase();
System.out.println("Computer play is: " + computerPlay);
if (personPlay.equals(computerPlay)) {
System.out.println("It's a tie!");
}
if (personPlay.equals("R") && computerPlay.equals("S")) {
System.out.println("Rock crushes scissors. You win!!");
}
if (personPlay.equals("R") && computerPlay.equals("P")) {
System.out.println("Paper eats rock. You lose!!");
}
if (personPlay.equals("P") && computerPlay.equals("R")) {
System.out.println("Paper eats rock. You win!!");
}
if (personPlay.equals("P") && computerPlay.equals("S")) {
System.out.println("Scissor cuts paper. You lose!!");
}
if (personPlay.equals("S") && computerPlay.equals("R")) {
System.out.println("Rock breaks scissors. You lose!!");
}
if (personPlay.equals("S") && computerPlay.equals("P")) {
System.out.println("Scissor cuts paper. You win!!");
}
if (!computerPlay.equals("R") && !computerPlay.equals("P") && !computerPlay.equals("S")) {
System.out.println("Invalid user input.");
}
}
}

Related

Paper rock scissors game, probably something is missing from my code

I started learning to program in java two/three days ago and decided to try and program a simple rock paper scissors game.
it wont run and i think that i either didn't include some important code or that this whole thing is just garbage.
thanks for help!
public class Game {
public static void main(String[] args) {
String personPlay; //User's play; either R, P or S
String computerPlay = ""; //Computer's play, R, P or S as well
int computerInt; //randomly generated number to etermine computers play
String response;
Scanner scan = new Scanner(System.in);
Random generator = new Random();
System.out.prinln("Let's play Rock, Paper, Scissors!\n" + "Enter a move: \n" + "R = Rock, P = Paper, S = Scissors");
System.out.println();
computerInt = generator.nextInt(
if (personPlay.equals(computerPlay))
System.out.println("It's a tie!");
else if (personPlay.equals("R"))
if (computerPlay.equals("S"))
System.out.println("Rock crushes Scissors! You win!");
else if (personPlay.equals("S"))
if (computerPlay.equals("P"))
System.out.println("Scissors cut Paper! You win!");
else if (personPlay.equals("P"))
if (computerPlay.equals("R"))
System.out.println("Paper wraps Rock! You win!");
else if (personPlay.equals("R"))
if (computerPlay.equals("P"))
System.out.println("Paper wraps Rock! You lose!");
else if (personPlay.equals("P"))
if (computerPlay.equals("S"))
System.out.println("Scissors cut Paper! You lose!");
else if (personPlay.equals("S"))
if (computerPlay.equals("R"))
System.out.println("Rock crushes Scissors! You lose!");
else System.out.println("Invalid user imput, please try again!");
}
}
I believe this answers your question:
import java.util.Scanner;
public class Game {
public static void main(String[] args) {
String personPlay; //User's play; either R, P or S
String computerPlay = ""; //Computer's play, R, P or S as well
String response;
Scanner scan = new Scanner(System.in);
System.out.println("Let's play Rock, Paper, Scissors!\n" + "Enter a move: \n" + "R = Rock, P = Paper, S = Scissors");
System.out.print("Player > ");
personPlay = scan.nextLine();
System.out.print("Computer > ");
String options [] = {"R","P","S"};
computerPlay = options[(int)(Math.random()*3)];
System.out.println(computerPlay);
if (personPlay.equals(computerPlay)) {
System.out.println("It's a tie!");
}
else if (personPlay.equals("R")) {
if (computerPlay.equals("P")) {
System.out.println("Paper wraps Rock! You lose!");
}
else if (computerPlay.equals("S")) {
System.out.println("Rock crushes Scissors! You win!");
}
}
else if (personPlay.equals("P")) {
if (computerPlay.equals("R")) {
System.out.println("Paper wraps Rock! You win!");
}
else if (computerPlay.equals("S")) {
System.out.println("Scissors cut Paper! You lose!");
}
}
else if (personPlay.equals("S")) {
if (computerPlay.equals("R")) {
System.out.println("Rock crushes Scissors! You lose!");
}
else if (computerPlay.equals("P")) {
System.out.println("Scissors cut Paper! You win!");
}
}
else { System.out.println("Invalid user imput, please try again!"); }
}
}
There were a few problems with your code, most of them already pointed by other users. I'll only add that the way you wrote those if/else statements, it would never enter some of them.
I don't have much time right now but if you still have any doubts after seeing this answer leave a comment and I'll answer ASAP.
I see a couple of errors in the code that you have shared :
In the statement "System.out.prinln("Let's play Rock, Paper, Scissors!\n" + "Enter a move: \n" + "R = Rock, P = Paper, S = Scissors");"
, it should be System.out.println().You have a spelling-error (missing 't' in 'print')
You need to initialize variable 'personPlay' for the code to compile. It is required to initialize local variables as they do not assume a default value.
Missing closing bracket for statement :'computerInt = generator.nextInt('.
Fixing these, would let the code compile .
I would suggest using curly braces with each if, else if or else conditions, that would give the code a neat look. Also , there is a long chain of nested if-else conditions which is hard to read and debug(in case of any issue). Try to start with simple conditions and then build your logic in steps , avoiding these many if else conditions.

Why isn't my code working beyond printing the math.random? [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 6 years ago.
I'm a new programmer and trying to teach myself Java by doing random projects. Below is a "Rock, Paper, Scissors" game and the issue that I'm facing is after printing "a", the program ends and does not continue onto the if else statements below. Any help that can be given would be greatly appreciated.
package com.company;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
System.out.println("Hello & Welcome to Rock, Paper, Scissors. What's your name?");
Scanner scan = new Scanner(System.in);
String userChoice = scan.nextLine();
System.out.println("Hello, " + userChoice + ". Let's start a game!");
Scanner scan = new Scanner(System.in);
System.out.println("Choose one: Rock, Paper, Scissors");
String userFirstChoice = scan.nextLine();
System.out.println("You chose " + userFirstChoice);
double a = Math.random();
System.out.println(a);
if (a >= 0.00 && a<= 0.3){
if ( userFirstChoice== "Rock"){
System.out.println("Rock vs Rock: TIE");
}
else if (userFirstChoice == "Paper"){
System.out.println("Rock vs Paper: YOU LOSE!");
}
else if (userFirstChoice == "Scissors"){
System.out.println("Rock vs Scissors: YOU WIN!");
}
}
else if (a>=0.3 && a<=0.6){
if(userFirstChoice == "Paper"){
System.out.println("Paper vs Paper: TIE!");
}
else if (userFirstChoice == "Rock"){
System.out.println("Rock vs Paper: YOU LOSE!");
}
else if(userFirstChoice == "Scissors"){
System.out.println("Scissors vs Paper: YOU WIN!");
}
}
else if (userFirstChoice == "Scissors"){
System.out.println("Scissors vs Scissors: TIE!");
}
else if (userFirstChoice == "Paper"){
System.out.println("Paper vs Scissors: YOU LOSE!");
}
else if (userFirstChoice == "Rock") {
System.out.println("Rock vs Scissors: YOU WIN!");
}
}
}
You can't use == to compare strings in Java. (== compares the references, and the operands to == could be references to different strings even though the string contents are identical.)
Use userFirstChoice.equals("Scissors") etc. instead.
Your use of the relational operators on the double types is correct.

Java: Rock, Paper, Scissors almost completed but has a fatal error

I was tasked to create a java program that resembles rock, paper, scissors. I have written what I thought would work below. However, only when the user selects R or r (for rock) does it actually work properly. If the user selects s or p (scissors or paper) the code will completely break or give multiple answers. I have looked through the code and can't seem to find out why it's not working properly.
Also any suggestions on how to better write the switch portion of the code would be appreciated. I have a feeling the way I wrote it is not the proper way.
import java.util.Scanner;
public class Project_2 {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int compVal = (int) (3 * Math.random()) + 1;
String compActual = "";
System.out.println("Welcome to Rock, Paper, Scissors!");
System.out.print("Enter r for rock, p for paper, or s for scissors: ");
String userOriginal = keyboard.nextLine();
userOriginal = (userOriginal.toUpperCase());
switch (userOriginal) {
case "r":
userOriginal = userOriginal;
break;
case "R":
userOriginal = userOriginal;
break;
case "p":
userOriginal = userOriginal;
break;
case "P":
userOriginal = userOriginal;
break;
case "s":
userOriginal = userOriginal;
break;
case "S":
userOriginal = userOriginal;
break;
default:
System.out.println("Invalid input, please try again!");
System.exit(1); // This will exit the program if invalid input is
// given. The 1 signifies that it ended with an
// error.
}
if (compVal == 1) {
compActual = "R";
} else if (compVal == 2) {
compActual = "P";
} else if (compVal == 3) {
compActual = "S";
}
if (compActual.equals(userOriginal)) {
System.out.println("It was a tie!");
} else if (compActual.equals("R"))
if (userOriginal.equals("S")) {
System.out.println("You played Scissors and I chose Rock: Rock crushes Scissors so I win this time!");
}
if (userOriginal.equals("P")) {
System.out.println("You played Paper and I chose Rock: Paper covers Rock so you win this time!");
} else if (compActual.equals("S"))
if (userOriginal.equals("R")) {
System.out.println("You played Rock and I chose Sciccors: Rock crushes Scissors so you win this time");
}
if (userOriginal.equals("P")) {
System.out.println("You played Paper and I chose Scissors: Paper is cut by Scissors so I win this time!");
} else if (compActual.equals("P"))
if (userOriginal.equals("R")) {
System.out.println("Your played Rock and I chose Paper: Paper covers rock so I win this time!");
}
if (userOriginal.equals("S")) {
System.out.println("You played Scissors and I chose Paper: Scissors cuts Paper so you win this time!");
}
}
}
As suggested, you should clean up your code a little bit. Why not use numerical values instead of Strings for comparsion, like this:
int compVal = (int) (3 * Math.random()) + 1;
int userOriginal = 0;
String userInput = (keyboard.nextLine().toUpperCase());
switch (userInput) {
case "R":
userOriginal = 1;
break;
case "P":
userOriginal = 2;
break;
case "S":
userOriginal = 3;
break;
default:
System.out.println("Invalid input, please try again!");
System.exit(1); // This will exit the program
}
After that you can compare the user provided value with the generated one:
if (compVal == userOriginal) {
System.out.println("It was a tie!");
} else
{
//R
if (compVal == 1)
{
if (userOriginal == 2) {
System.out.println("You played Paper and I chose Rock: Paper covers Rock so you win this time!");
}
if (userOriginal == 3) {
System.out.println("You played Scissors and I chose Rock: Rock crushes Scissors so I win this time!");
}
}
//P
if (compVal == 2)
{
if (userOriginal == 1) {
System.out.println("Your played Rock and I chose Paper: Paper covers rock so I win this time!");
}
if (userOriginal == 3) {
System.out.println("You played Scissors and I chose Paper: Scissors cuts Paper so you win this time!");
}
}
//S
if (compVal == 3)
{
if (userOriginal == 1) {
System.out.println("You played Rock and I chose Sciccors: Rock crushes Scissors so you win this time");
}
if (userOriginal == 2) {
System.out.println("You played Paper and I chose Scissors: Paper is cut by Scissors so I win this time!");
}
}
}
Also, remember to always close all the resources that you used:
keyboard.close();
You have multiple commands after an if-statement, but you're missing the {}.
For instance:
else if (compActual.equals("R"))
if (userOriginal.equals("S"))
{
System.out.println("You played Scissors and I chose Rock: Rock crushes Scissors so I win this time!");
}
if (userOriginal.equals("P"))
{
System.out.println("You played Paper and I chose Rock: Paper covers Rock so you win this time!");
}
should be:
else if (compActual.equals("R"))
{
if (userOriginal.equals("S"))
{
System.out.println("You played Scissors and I chose Rock: Rock crushes Scissors so I win this time!");
}
if (userOriginal.equals("P"))
{
System.out.println("You played Paper and I chose Rock: Paper covers Rock so you win this time!");
}
}
and, I'm sorry to say, you code needs cleaning up. For instance, you're using toUpperCase(), so no need to compare with lower case input.
First: what does should do your first switch (on userOrigignal values)?
If is is way to check if values is correct you have better way - create collection of possible values ("R", "P", "S") and check input against this collections:
private static final Collection<String> TYPES = new HashSet<>();
static {
TYPES.add("R");
TYPES.add("P");
TYPES.add("S");
}
private static boolean correctInput(String input) {
TYPES.contains(input.toUpperCase());
}
so you could replace this awful switch with simple call to function correctInput.
Next problem - you wrote totally wrong if's block: for example if (compActual.equals("R")) cases not surrounded with braces. So you checked R against S and after it simple entry for user "P"... It is better way to surround every if's body with braces - in this case you won't be confused by stylings and will see exact if's bodies.
And last problem - don't closed Scanner object. In current program it wouldn't bring any problem, but it is strongly recommended to always close resources.
PS you can make it much easelly with prepared table:
import java.util.*;
public class Project_2 {
private static final Map<String, Map<Integer, String>> TYPES = new HashMap<>();
static {
Map<Integer, String> subMap = new HashMap<Integer, String>();
subMap.put(0, "It was a tie!");
subMap.put(1, "You played Rock and I chose Scissors: Rock crushes Scissors so you win this time");
subMap.put(2, "Your played Rock and I chose Paper: Paper covers rock so I win this time!");
TYPES.put("R", subMap);
subMap = new HashMap<Integer, String>();
subMap.put(0, "You played Scissors and I chose Rock: Rock crushes Scissors so I win this time!");
subMap.put(1, "It was a tie!");
subMap.put(2, "You played Scissors and I chose Paper: Scissors cuts Paper so you win this time!");
TYPES.put("S", subMap);
subMap = new HashMap<Integer, String>();
subMap.put(0, "You played Paper and I chose Rock: Paper covers Rock so you win this time!");
subMap.put(1, "You played Paper and I chose Scissors: Paper is cut by Scissors so I win this time!");
subMap.put(2, "It was a tie!");
TYPES.put("P", subMap);
}
private static boolean checkInput(String input) {
TYPES.containsKey(input.toUpperCase());
}
public static void main(String[] args) {
int compVal = new Random().nextInt(3);
System.out.println("Welcome to Rock, Paper, Scissors!");
System.out.print("Enter r for rock, p for paper, or s for scissors: ");
String userOriginal = null;
try (Scanner keyboard = new Scanner(System.in)) {
userOriginal = keyboard.nextLine();
}
if (!checkInput(userOriginal)) {
System.out.println("Invalid input, please try again!");
System.exit(1); // This will exit the program if invalid input is
// given. The 1 signifies that it ended with an
// error.
}
System.out.println(TYPES.get(userOriginal, compVal));
}
}

Rock, Paper, Scissors Game Java [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I'm new to programming and I'm trying to write a very simple Rock, Paper, Scissors game in Java. It will compile and run fine, but I am looking to say something like "Invalid move. Try again." or something along those lines for when the user (personPlay) does not enter a correct character (r, p, or s). What would be the best way to do so? For example, if you enter a "q", it should print "Invalid move." Thank you so much in advance!
// *************
// Rock.java
// *************
import java.util.Scanner;
import java.util.Random;
public class Rock
{
public static void main(String[] args)
{
String personPlay; //User's play -- "R", "P", or "S"
String computerPlay = ""; //Computer's play -- "R", "P", or "S"
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("Hey, let's play Rock, Paper, Scissors!\n" +
"Please enter a move.\n" + "Rock = R, Paper" +
"= P, and Scissors = S.");
System.out.println();
//Generate computer's play (0,1,2)
computerInt = generator.nextInt(3)+1;
//Translate computer's randomly generated play to
//string using if //statements
if (computerInt == 1)
computerPlay = "R";
else if (computerInt == 2)
computerPlay = "P";
else if (computerInt == 3)
computerPlay = "S";
//Get player's play from input-- note that this is
// stored as a string
System.out.println("Enter your play: ");
personPlay = scan.next();
//Make player's play uppercase for ease of comparison
personPlay = personPlay.toUpperCase();
//Print computer's play
System.out.println("Computer play is: " + computerPlay);
//See who won. Use nested ifs
if (personPlay.equals(computerPlay))
System.out.println("It's a tie!");
else if (personPlay.equals("R"))
if (computerPlay.equals("S"))
System.out.println("Rock crushes scissors. You win!!");
else if (computerPlay.equals("P"))
System.out.println("Paper eats rock. You lose!!");
else if (personPlay.equals("P"))
if (computerPlay.equals("S"))
System.out.println("Scissor cuts paper. You lose!!");
else if (computerPlay.equals("R"))
System.out.println("Paper eats rock. You win!!");
else if (personPlay.equals("S"))
if (computerPlay.equals("P"))
System.out.println("Scissor cuts paper. You win!!");
else if (computerPlay.equals("R"))
System.out.println("Rock breaks scissors. You lose!!");
else
System.out.println("Invalid user input.");
}
}
I would recommend making Rock, Paper and Scissors objects. The objects would have the logic of both translating to/from Strings and also "knowing" what beats what. The Java enum is perfect for this.
public enum Type{
ROCK, PAPER, SCISSOR;
public static Type parseType(String value){
//if /else logic here to return either ROCK, PAPER or SCISSOR
//if value is not either, you can return null
}
}
The parseType method can return null if the String is not a valid type. And you code can check if the value is null and if so, print "invalid try again" and loop back to re-read the Scanner.
Type person=null;
while(person==null){
System.out.println("Enter your play: ");
person= Type.parseType(scan.next());
if(person ==null){
System.out.println("invalid try again");
}
}
Furthermore, your type enum can determine what beats what by having each Type object know:
public enum Type{
//...
//each type will implement this method differently
public abstract boolean beats(Type other);
}
each type will implement this method differently to see what beats what:
ROCK{
#Override
public boolean beats(Type other){
return other == SCISSOR;
}
}
...
Then in your code
Type person, computer;
if (person.equals(computer))
System.out.println("It's a tie!");
}else if(person.beats(computer)){
System.out.println(person+ " beats " + computer + "You win!!");
}else{
System.out.println(computer + " beats " + person+ "You lose!!");
}
You could insert something like this:
personPlay = "B";
while (!personPlay.equals("R") && !personPlay.equals("P") && !personPlay.equals("S")) {
//Get player's play from input-- note that this is
// stored as a string
System.out.println("Enter your play: ");
personPlay = scan.next();
//Make player's play uppercase for ease of comparison
personPlay = personPlay.toUpperCase();
if (!personPlay.equals("R") && !personPlay.equals("P") && !personPlay.equals("S"))
System.out.println("Invalid move. Try again.");
}
Before we try to solve the invalid character problem, the lack of curly braces around the if and else if statements is wreaking havoc on your program's logic. Change it to this:
if (personPlay.equals(computerPlay)) {
System.out.println("It's a tie!");
}
else if (personPlay.equals("R")) {
if (computerPlay.equals("S"))
System.out.println("Rock crushes scissors. You win!!");
else if (computerPlay.equals("P"))
System.out.println("Paper eats rock. You lose!!");
}
else if (personPlay.equals("P")) {
if (computerPlay.equals("S"))
System.out.println("Scissor cuts paper. You lose!!");
else if (computerPlay.equals("R"))
System.out.println("Paper eats rock. You win!!");
}
else if (personPlay.equals("S")) {
if (computerPlay.equals("P"))
System.out.println("Scissor cuts paper. You win!!");
else if (computerPlay.equals("R"))
System.out.println("Rock breaks scissors. You lose!!");
}
else
System.out.println("Invalid user input.");
Much clearer! It's now actually a piece of cake to catch the bad characters. You need to move the else statement to somewhere that will catch the errors before you attempt to process anything else. So change everything to:
if( /* insert your check for bad characters here */ ) {
System.out.println("Invalid user input.");
}
else if (personPlay.equals(computerPlay)) {
System.out.println("It's a tie!");
}
else if (personPlay.equals("R")) {
if (computerPlay.equals("S"))
System.out.println("Rock crushes scissors. You win!!");
else if (computerPlay.equals("P"))
System.out.println("Paper eats rock. You lose!!");
}
else if (personPlay.equals("P")) {
if (computerPlay.equals("S"))
System.out.println("Scissor cuts paper. You lose!!");
else if (computerPlay.equals("R"))
System.out.println("Paper eats rock. You win!!");
}
else if (personPlay.equals("S")) {
if (computerPlay.equals("P"))
System.out.println("Scissor cuts paper. You win!!");
else if (computerPlay.equals("R"))
System.out.println("Rock breaks scissors. You lose!!");
}
Why not check for what the user entered and then ask the user to enter correct input again?
eg:
//Get player's play from input-- note that this is
// stored as a string
System.out.println("Enter your play: ");
response = scan.next();
if(response=="R"||response=="P"||response=="S"){
personPlay = response;
}else{
System.out.println("Invaild Input")
}
for the other modifications, please check my total code at pastebin
int w =0 , l =0, d=0, i=0;
Scanner sc = new Scanner(System.in);
// try tentimes
while (i<10) {
System.out.println("scissor(1) ,Rock(2),Paper(3) ");
int n = sc.nextInt();
int m =(int)(Math.random()*3+1);
if(n==m){
System.out.println("Com:"+m +"so>>> " + "draw");
d++;
}else if ((n-1)%3==(m%3)){
w++;
System.out.println("Com:"+m +"so>>> " +"win");
}
else if(n >=4 )
{
System.out.println("pleas enter correct number)");
}
else {
System.out.println("Com:"+m +"so>>> " +"lose");
l++;
}
i++;

Java rock paper scissors loop

I'm having to make a paper rock scissors program that has the user enter in a choice, then tests it against the computer's choice. After every game, it should ask the player if they want to continue, and they should enter in 'Y' or 'N' to continue or quit. The best I could think was a while loop, and everything works fine except the very last bit.
import java.util.Scanner;
public class rockpaperscissors {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
char cont = 'y';
while (cont == 'y'){
int com = (int)(Math.random() * 3);
System.out.println("Paper (0), Rock (1), or Scizzors (2)?");
int hum = input.nextInt();
if (com==(hum))
System.out.println("It's a tie!");
else if (hum == 0)
{
if (com == 1)
System.out.println ("You chose paper, computer chose rock You Win!");
else if (com == 2)
System.out.println ("You chose paper, Computer chose scissors You Lose!");
}
else if (hum == 1)
{
if (com == 2)
System.out.println ("You chose Rock, computer chose scissors You Win!");
else if (com == 0)
System.out.println ("You chose Rock, Computer chose paper You Lose!");
}
else if (hum == 2)
{
if (com == 0)
System.out.println ("You chose Scissors, computer chose paper You Win!");
else if (com == 1)
System.out.println ("You chose Scissors, Computer chose rock You Lose!");
}
System.out.println("Would you like to continue? (Y/N)");
cont = input.nextLine().charAt(0);
}
}
}
When I run it, the loop runs fine, the game is played, but then I get a 'string out of index range' error. Any idea how to resolve this?
Your nextInt() just reads the number from the input buffer, leaving the new line in it. So when you call input.nextLine() you're getting an empty line - the rest of the first line after the number. You should read the next-line and make sure it's not empty. If it is, just read it again.
Incidentally, your code that figures out who won is a bit cumbersome. If I were you, I would try to make it a little more general and clean. Think about a solution that can handle a more complex game, such as Rock Paper Scissors Lizard Spock without adding too much code.
When you get the answer from the user, you don't read the next line so the scanner still has a new line character. Then when you read the nextline you read that new line, and therefore there is no charat(0).
Change:
cont = input.nextLine().charAt(0);
to:
cont = input.next().charAt(0);
package rockpaper;
import java.util.Scanner;
/**
*
* #author Allen E.
*/
public class RockPaper {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
int rock = 0;
int paper = 1;
int Scissors = 2;
int user = 0;
int computer = 0;
int gamesplayed = 0;
Scanner scan = new Scanner(System.in);
while (gamesplayed < 3)
{
System.out.println("Rock = 0 , Paper = 1, Scissors = 2");
String userinput = scan.nextLine();
int convertinput = Integer.valueOf(userinput);
int Computerinput = (int)(Math.random()*3);
if (Computerinput == 1 && convertinput == 0)
{
System.out.println("Paper beats Rock " +
"\nThe computer won");
gamesplayed++;
computer++;
}
else if (convertinput == 1 && Computerinput == 0)
{
System.out.println("Paper beats Rock " +
"\nYou Win!");
gamesplayed++;
user++;
}
if (Computerinput == 0 && convertinput == 2)
{
System.out.println("Rock beats Scissors " +
"\nThe computer won");
gamesplayed++;
computer++;
}
else if (convertinput == 0 && Computerinput == 2)
{
System.out.println("Rock beats Scissors " +
"\nYou Win!");
gamesplayed++;
user++;
}
if (Computerinput == 2 && convertinput == 1)
{
System.out.println("Scissors beats Paper " +
"\nThe computer won");
gamesplayed++;
computer++;
}
else if (convertinput == 2 && Computerinput == 1 )
{
System.out.println("Scissors beats Paper " +
"\nYou Win");
gamesplayed++;
user++;
}
/*************************************************
* *
* *
* Handling a tie *
* *
* *
*************************************************/
if (Computerinput == 0 && convertinput == 0)
{
System.out.println("Rock ties Rock " +
"\nTie");
}
if (Computerinput == 1 && convertinput == 1)
{
System.out.println("Paper ties Paper " +
"\nTie");
}
if (Computerinput == 2 && convertinput == 2)
{
System.out.println("Scissors ties Scissors " +
"\nTie");
}/*End of While Loop*/
}
}
}

Categories

Resources