Java String Method returning Null? - java

I was tasked with making a simple program that will play Rock-Paper-Scissors with the user. Unfortunately, when I try to run the program, my return(sentence+outcome) both returns null. I am new to using methods, so please explain what I am doing wrong here... Thank you!
package rockpaperscissors;
/**
*
* #author Owner
*/
import java.util.Scanner;
import java.io.IOException;
public class RockPaperScissors {
static int weaponChoice;
static int computerChoice;
static int tie = 0;
static int lose = 0;
static int win = 0;
static String outcome;
static String sentence;
/**
* #param args the command line arguments
* #throws java.io.IOException
*/
public static void main(String[] args) throws IOException {
Scanner userInput = new Scanner(System.in);
System.out.println(" =========================");
System.out.println("====ROCK=PAPER=SCISSORS====");
System.out.println(" =========================");
int playAgain = 1; //sets a play again function
do {
System.out.println("Please select your weapon.");
System.out.println("1 - Rock");
System.out.println("2 - Paper");
System.out.println("3 - Scissors");
System.out.println("Choose wisely:");
String choice = userInput.nextLine();
weaponChoice = Integer.parseInt(choice);
do {
if (weaponChoice != 1 && weaponChoice != 2 && weaponChoice != 3) {
System.out.println("Please choose again, grasshopper. There are only"
+ " three choices.");
System.out.println("1 - Rock");
System.out.println("2 - Paper");
System.out.println("3 - Scissors");
choice = userInput.nextLine();
weaponChoice = Integer.parseInt(choice);
}
} while (weaponChoice != 1 && weaponChoice != 2 && weaponChoice != 3);
if (weaponChoice == 1) {
System.out.println("You have selected Rock as your weapon.");
} else if (weaponChoice == 2) {
System.out.println("You have selected Paper as your weapon.");
} else {
System.out.println("You have selected Scissors as your weapon.");
}
//Computer's Choice
computerChoice = 1 + (int) (Math.random() * ((3 - 1) + 1));
if (computerChoice == 1) {
System.out.println("The computer has chosen Rock.");
} else if (computerChoice == 2) {
System.out.println("The computer has chosen Paper.");
} else {
System.out.println("The computer has chosen Scissors.");
}
determineOutcome(outcome, sentence);
System.out.println(sentence+outcome);
System.out.println("==SCORES==");
System.out.println("WINS: " + win);
System.out.println("TIES: " + tie);
System.out.println("LOSSES: " + lose);
System.out.println("Press 1 to play again, or any other number to exit.");
String play = userInput.nextLine();
playAgain = Integer.parseInt(play);
} while (playAgain == 1);
}
public static String determineOutcome(String outcome, String sentence) {
sentence = "Your result is: ";
do {
if (weaponChoice == 1 && computerChoice == 1 || weaponChoice == 2 && computerChoice == 2 || weaponChoice == 3 && computerChoice == 3) {
tie++;
outcome = "TIE";
} else if (weaponChoice == 1 && computerChoice == 3 || weaponChoice == 2 && computerChoice == 1 || weaponChoice == 3 && computerChoice == 2) {
win++;
outcome = "You WON!";
} else {
lose++;
outcome = "You LOSE. Better luck next time?";
}
} while (lose <0 || win < 0 || tie < 0);
return(sentence+outcome);
}
}

To make this work, you'll need to replace
determineOutcome(outcome, sentence);
System.out.println(sentence+outcome);
with
String valueReturned = determineOutcome(outcome, sentence);
System.out.println(valueReturned);
because Java is pass by value, not pass by reference. That means that the determineOutcome method will work with its own copies of outcome and sentence, and not modify the versions that belong to the method that called it.
But also, the method is not actually using the two arguments you pass into it. It would be much less confusing if you just omit the parameters entirely, and change it to public static String determineOutcome() ... and declare String sentence; and String outcome; inside the method.

When calling a function that is returning a result you must either call the function within System.out.println() or assign the result to a variable which you then print.
Option 1:
String result = determineOutcome(outcome, sentence);
System.out.println(result);
or option 2:
System.out.println(determineOutcome(outcome, sentence));

In addition to the points other people made in their answers, it looks like your while loop is never being executed. The variables tie, win and lose are never less than 0, so the condition of the while loop is never true. You can try changing it to:
while (lose <= 0 || win <= 0 || tie <= 0);
But be warned, this will result in an infinite loop, so you may need to rethink your logic. You may not need a loop here, depending on what you're trying to do.

Related

I am trying to add an option to replay or end the game. Also, my results aren't popping up properly

I am trying to add an exit option to this code. Also, my results will not read correctly, and I am not sure what I am doing wrong. I've tried using a do while loop, but I can't seem to place it in the correct place.
//import Scanner Class
import java.util.Scanner;
import java.util.Random;
public class JavaMidterm {
public static void main(String[] args) {
String result = " ", symbola = " ", symbolb = " ";
Scanner s = new Scanner(System.in);
//prompt user
System.out.print("Scissor (0), rock (1), paper (2): ");
// read user choice
int choice=s.nextInt();
//Create random class object
Random random = new Random();
//Generate a random number from 0, 1, 2
int pick = random.nextInt(3);
if(choice == pick)
result = "It is a draw";
else {
if (((choice == 0) && (pick == 2)) || ((choice == 1) && (pick ==0)) || ((choice == 2) && (pick == 1)) )
result = "You won";
else
result = "You lose";
}
if(pick == 0)
symbola = "Scissor";
if(choice == 0)
symbolb = "Scissor";
//assigning symbols to the corresponding values
if(pick == 1)
symbolb = "Rock";
if(pick == 2)
symbola = "Paper";
if(choice == 2)
symbolb = "Paper";
System.out.println("The computer is" +
symbola + ". You are" + symbolb + ". " + result);
}
}
You can try my solution below. I have also included checking for invalid inputs. I also simplified the checking for your result.
//import Scanner Class
import java.util.Random;
import java.util.Scanner;
public class JavaMidterm {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
// Create random class object
Random random = new Random();
String[] choices = new String[] { "Scissor", "Rock", "Paper" };
int choice;
// prompt user
System.out.print("Scissor (0), rock (1), paper (2): ");
while (true) {
try {
String result = "";
// read user choice
choice = Integer.parseInt(s.nextLine());
if (choice < 0 || choice > 2) {
throw new Exception();
}
// Generate a random number from 0, 1, 2
int pick = random.nextInt(3);
if (choice == pick)
result = "It is a draw";
else if (((choice == 0) && (pick == 2)) || ((choice == 1) && (pick == 0))
|| ((choice == 2) && (pick == 1)))
result = "You won";
else
result = "You lose";
System.out.println("The computer is " + choices[pick] + ". You are " + choices[choice] + ". " + result);
System.out.print("Do you want to play again? Yes (0), No (1): ");
while (true) {
try {
// read user choice
choice = Integer.parseInt(s.nextLine());
if (choice < 0 || choice > 1) {
throw new Exception();
}
if (choice == 0)
System.out.print("Scissor (0), rock (1), paper (2): ");
break;
} catch (Exception e) {
System.out.println("Invalid input.");
System.out.print("Do you want to play again? Yes (0), No (1): ");
}
}
if (choice == 1) {
break;
}
} catch (Exception e) {
System.out.println("Invalid input.");
System.out.print("Scissor (0), rock (1), paper (2): ");
}
}
s.close();
}
}
I assume that you wish to end the game in case of a "win" and continue the game in case of "losing". Assuming that the code can be modified like below,
boolean isGoodToContinue = true;
while (isGoodToContinue) {
String result = " ", symbola = " ", symbolb = " ";
Scanner s = new Scanner(System.in);
// prompt user
System.out.print("Scissor (0), rock (1), paper (2): ");
// read user choice
int choice = s.nextInt();
// Create random class object
Random random = new Random();
// Generate a random number from 0, 1, 2
int pick = random.nextInt(3);
if (choice == pick)
result = "It is a draw";
else {
if (((choice == 0) && (pick == 2)) || ((choice == 1) && (pick == 0))
|| ((choice == 2) && (pick == 1))) {
result = "You won";
isGoodToContinue = false;
}
else {
result = "You lose";
isGoodToContinue = true;
}
}

How do I use the "return" value of one method in another method

I am currently working on this project that plays the high low dice game. I am stuck on how to use the returned char from getHighLow and the returned int from getBet and getRoll in determineWinnings. This is my first year learning Java currently, so any help would be appreciated. Thank you in advance for any help you can give!
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int currentPool = 100;
getBet(keyboard, currentPool);
getHighLow(keyboard);
getRoll();
>> determineWinnings(highLow, userBet, rollSum);
}
// Given a Scanner and a current maximum amount of money, prompt the user for
// an integer representing the number of dollars that they want to bet. This
// number must be between 0 and to maximum number of dollars. If the user enters
// a number that is out of bounds, display an error message and ask again.
// Return the bet to the calling program.
private static int getBet(Scanner inScanner, int currentPool) {
int userBet = -1;
while (userBet == -1) {
inScanner = new Scanner(System.in);
System.out.println("You have $" + currentPool);
System.out.println("Enter an amount to bet (0 to quit): ");
userBet = inScanner.nextInt();
if (userBet > currentPool || userBet < 0) {
System.out.println("Your bet MUST be between 0 and " + currentPool + " dollars");
userBet = -1;
}
if (userBet == 0) {
System.out.println("You have " + currentPool + " dollars left.");
System.out.println("Goodbye!");
}
}
return userBet;
}
// Given a Scanner, prompt the user for a single character indicating whether
// they
// would like to bet High ('H'), Low ('L') or Sevens ('S'). Your code should
// accept
// either capital or lowercase answers, but should display an error if the user
// attempts
// to enter anything but one of these 3 values and prompt for a valid answer.
// Return the character to the calling program.
private static char getHighLow(Scanner inScanner) {
Scanner keyboard = new Scanner(System.in);
int i = 0;
String userChoice = "";
while (i == 0) {
System.out.println("High, low or sevens (H/L/S): ");
userChoice = keyboard.nextLine();
if (userChoice.length() > 1 || (userChoice.charAt(0) != 'H' && userChoice.charAt(0) != 'h'
&& userChoice.charAt(0) != 'L' && userChoice.charAt(0) != 'l' && userChoice.charAt(0) != 'S'
&& userChoice.charAt(0) != 's')) {
System.out.println("ERROR: You must type H, L, or S.");
} else {
i++;
}
}
char highLow = 'N';
if (userChoice.charAt(0) == 'H' || userChoice.charAt(0) == 'h') {
highLow = 'H';
} else if (userChoice.charAt(0) == 'L' || userChoice.charAt(0) == 'l') {
highLow = 'L';
} else {
highLow = 'S';
}
return highLow;
}
// Produce a random roll of a single six-sided die and return that value to the
// calling
// program
private static int getRoll() {
int dieOne = (int) (Math.random() * 6 + 1);
System.out.println("Die 1 rolls: " + dieOne);
int dieTwo = (int) (Math.random() * 6 + 1);
System.out.println("Die 2 rolls: " + dieTwo);
int rollSum = dieOne + dieTwo;
System.out.println("The total of two dice is: " + rollSum);
return rollSum;
}
// Given the choice of high, low or sevens, the player's bet and the total
// result of
// the roll of the dice, determine how much the player has won. If the player
// loses
// the bet then winnings should be negative. If the player wins, the winnings
// should
// be equal to the bet if the choice is High or Low and 4 times the bet if the
// choice
// was Sevens. Return the winnings to the calling program.
private static int determineWinnings(char highLow, int bet, int roll) {
int highLowValue = 0;
int winnings = 0;
if (highLow == 'H') {
highLowValue = 8;
} else if (highLow == 'L') {
highLowValue = 6;
} else {
highLowValue = 7;
}
if (roll >= 8 && highLowValue == 8) {
winnings = bet;
System.out.println("You won " + winnings + " dollars!");
} else if (roll <= 6 && highLowValue == 6) {
winnings = bet;
System.out.println("You won " + winnings + " dollars!");
} else if (roll == 7 && highLowValue == 7) {
winnings = bet * 4;
System.out.println("You won " + winnings + " dollars!");
} else {
winnings = -1 * bet;
}
return winnings;
}
You can assign the output of each method to variable or call methods directly on determineWinnings.
plan 1)
int userBet = getBet(keyboard, currentPool);
char highLow = getHighLow(keyboard);
int roll = getRoll();
determineWinnings(highLow, userBet, roll);
plan 2)
determineWinnings(getHighLow(keyboard), getBet(keyboard, currentPool), getRoll());
There are following approaches to get the result of one method to another.
Pass result of one method to another
Define private/static members
Better way would be passing result of one method to another method.

Repeating no matter my input

So the program that I am trying to write is something like this. The opponent picks a number at random where each number corresponding to a person. then the user does the same thing. then the out is to show what the user pick, what the opponent picked and who won that match. its similiar to rock, paper scissor but with some more stuff added to it. i also have to show the numbers of rounds played and how many times the user had won. But my problem is this. No matter what my input is, it keeps saying that i made an invalid choice and to pick it again. This is what I have.
public static void main(String[] args) {
int game=0;
int won = 0;
int opponent;
Random rand = new Random();
System.out.println("Welcome to the game. Here are the rules:");
Scanner in = new Scanner(System.in);
rules();
choices();
int choice = selected(in);
while (choice !=0) {
rules();
choices();
choice = selected(in);
opponent = opp();
result(choice, opponent, in);
game+=1;
}
System.out.println("You played " +game+" games.");
System.out.println("Quitting");
}
public static void rules(){
System.out.println("\nFlurg beats Stuga and Kvartal");
System.out.println("Stuga beats Kvartal");
System.out.println("Kvartal beats Lerberg");
System.out.println("Lerberg beats Flurg and Stuga");
System.out.println("The computer wins in the event of a tie.");
System.out.println();
}
public static int opp(){
Random rand = new Random();
int opponent = rand.nextInt(4)+1;
return opponent;
}
public static void choices(){
System.out.println("Please select your choice:");
System.out.println("'1' for Flurg ");
System.out.println("'2' for Stuga ");
System.out.println("'3' for Kvartal ");
System.out.println("'4' for Lerberg ");
System.out.println("'0' to Quit ");
System.out.print("Selection: ");
}
public static int selected(Scanner in){
int choice = in.nextInt();
while (choice != 1 && choice != 2 &&
choice != 3 && choice != 4 &&
choice != 0) {
System.out.println("Invalid choice");
choices();
choice = in.nextInt();
}
return choice;
}
public static int result(int choice, int opponent, Scanner in) {
int won=0;
System.out.print("You picked:" +choice+". Opponent picked:" +opponent+".");
if(choice == 1 && (opponent == 2) || (opponent == 3)){
System.out.println("You won!");
won+=1;
}
else if(choice == 2 && opponent == 3){
System.out.println("You won!");
won+=1;
}
else if(choice == 3 && opponent == 4){
System.out.println("You won!");
won=+1;
}
else if(choice == 4 && (opponent == 1 || opponent == 2)){
System.out.println("You won!");
won+=1;
}
else {
System.out.println("You lost!");
}
return won;
}
}
EDIT
So I fixed exactly what i was told about the !=1 part. but it is again looping. for some reason, it does not want to run result()
EDIT#2
Main also has been fixed with the similar problem.
EDIT#3
I have added more lines based on what I was told.
change this
choice != '1' && choice != '2' &&
choice != '3' && choice != '4' &&
choice != '0'
to this
choice != 1 && choice != 2 &&
choice != 3 && choice != 4 &&
choice != 0
What you were trying to do was int != char and the value for '1' in ASCII is 49 SO it was indeed not 1. You are reading int from the Scanner.
The problem is here
int choice = in.nextInt();
while (choice != '1' && choice != '2' &&
choice != '3' && choice != '4' &&
choice != '0') {
System.out.println("Invalid choice");
nextInt() will return the decimal value of an int type. (int)1 != (char)'1'. The easiest solution I can think of is
while (choice != 1 && choice != 2 &&
choice != 3 && choice != 4 &&
choice != 0) {
You are comparing the found values to chars.
int choice = in.nextInt();
while (choice != '1' //...
However, this compares the entered numerical value to the ASCII-code of the character which is 49 for the character '1'. Therefore, your loop will continue until you enter one of the numbers 48 ('0') to 52 ('4').
You should compare to the numbers instead:
while (choice != 1 && choice != 2 && choice != 3 && choice != 4 && choice != 0) {
System.out.println("Invalid choice");
}
The same goes for
while (choice !='0') {
rules();
choices();
selected(in);
opp();
result(choice, opponent, in);
}
in your main method -- change this to
while (choice != 0) { // change this to 0 instead of '0'
rules();
choices();
choice = selected(in); // assign the value to choice
opponent = opp(); // assign the value to opponent
result(choice, opponent, in);
}
You also did not assign the return values of the methods to the local variables -- they are never going to change and the loop will never end like that!

intro java coding. don't understand what i'm doing wrong

i'm really not sure what's wrong with my code. It's supposed to do rock paper scissors against the computer by taking in the user choice, comparing it to the random computer choice, and displaying the results.
I get two errors that i have no return statements for the 3rd and 4th methods. Also, when i run it without fixing the errors, the nested if statements starting at line 60 only print out one of the two println statements, which really makes zero sense to me.
import java.util.Random;
import java.util.Scanner;
public class Chapter5ProjectPart2 {
public static void main(String[] args) {
Random generator = new Random();
Scanner keyboard = new Scanner(System.in);
int userNum;
int compNum;
String userChoice = "";
String compChoice = "";
int rnum;
int result = 0;
boolean keepPlaying;
int input = 1;
do
{
compNum = generator.nextInt(2)+1;
compChoice = numToChoice(compNum);
menu();
userNum = keyboard.nextInt();
userChoice = numToChoice(userNum);
keyboard.nextInt();
System.out.println();
System.out.println("you chose " + userChoice);
System.out.println("the computer chose " + compChoice);
result = resultCheck(userNum, compNum);
if (result == 1) // user wins
{
if (userNum == 1) //user won choosing rock
{
System.out.println("rock beats scissors");
System.out.println("you win");
}
else if (userNum == 2) //user won choosing paper
{
System.out.println("paper beats rock");
System.out.println("you win");
}
else if (userNum == 3) //user won choosing scissors
{
System.out.println("scissors beats paper");
System.out.println("you win");
}
}
else if (result == 3) //user loses
{
if (userNum == 1) //user lost choosing rock
{
System.out.println("paper beats rock");
System.out.println("you lose");
}
else if (userNum == 2) //user lost choosing paper
{
System.out.println("scissors beats paper");
System.out.println("you lose");
}
else if (userNum == 3) //user lost choosing scissors
{
System.out.println("rock beats scissors");
System.out.println("you lose");
}
else if (result == 2) //draw
System.out.println("draw");
}
System.out.println("would you like to play again?");
System.out.println("1 = yes");
System.out.println("2 = no");
input = keyboard.nextInt();
keepPlaying = play(input);
} while (keepPlaying == true);
}
// method 1 (menu)
public static void menu()
{
System.out.println("Enter your choice of rock, paper, or scissors\n" + "1 = rock\n" + "2 = paper\n" + "3 = scissors");
}
// method 2 (result check)
public static int resultCheck(int userNum, int compNum)
{
if (userNum == 2 && compNum == 1)
return 1;
else if (userNum == 1 && compNum == 3)
return 1;
else if (userNum == 3 && compNum == 2)
return 1;
else if (userNum == compNum)
return 2;
else
return 3;
}
// method 3 (converting number choice to rock/paper/scissors
public static String numToChoice(int num)
{
if (num == 1)
return "rock";
else if (num == 2)
return "paper";
else if (num == 3)
return "scissors";
}
//method 4 (play again)
public static boolean play(int input)
{
if (input == 1)
return true;
else if (input == 2)
return false;
}
}
I get two errors that i have no return statements for the 3rd and 4th methods.
Right. Let's look at the third:
public static String numToChoice(int num)
{
if (num == 1)
return "rock";
else if (num == 2)
return "paper";
else if (num == 3)
return "scissors";
}
Suppose num isn't 1, 2, or 3? Then what should the return value of the method be? That's why you're getting the error, you need a final else (with no if) saying what that return value should be when none of the earlier branches has returned a value. Without it, the method causes a compile-time error.
Also, when i run it without fixing the errors, the nested if statements starting at line 60 only print out one of the two println statements, which really makes zero sense to me.
You can't run it without fixing the errors, because these are compile-time errors. If you try to compile this source code with those errors in place, it fails, and you don't get an updated class file. So if you then try to run, and it seems to work, you're running an earlier copy of the class file you compiled before those errors were there. That class file doesn't relate to the current source code, and so it's understandable that it would make no sense to you. You're not looking at what the JVM is running.
If you correct the methods so that things compile (by adding the final else with no if on it), then run the compiled result, things should make more sense. Meanwhile, you might want to delete the previous Chapter5ProjectPart2.class file, since it's out of date.
public static String numToChoice(int num)
{
if (num == 1)
return "rock";
else if (num == 2)
return "paper";
else if (num == 3)
return "scissors";
}
//method 4 (play again)
public static boolean play(int input)
{
if (input == 1)
return true;
else if (input == 2)
return false;
}
These methods should always return something. Method 3 for example, if int num is 4 it won't return anything. Solve it by adding:
else return "";
That's because you are not ending your else-if statement in methods 3 and 4 with an else clause.
You indeed lack return statements. Java expects a non-void method to always return a value or throw an exception. Having a non-void method end without returning or throwing an exception is an error.
public static String numToChoice(int num)
{
if (num == 1)
return "rock";
else if (num == 2)
return "paper";
else if (num == 3)
return "scissors";
}
Here, your method doesn't return anything if num isn't 1, 2 or 3. Likewise:
public static boolean play(int input)
{
if (input == 1)
return true;
else if (input == 2)
return false;
}
Here inputs that aren't 1 or 2 lack their return statements.
First of all, never run code that doesn't compile.
Second: examine this method:
public static boolean play(int input)
{
if (input == 1)
return true;
else if (input == 2)
return false;
}
What would the method return if input is 6, or -67, or 789? You didn't tell, and the compiler can't guess it. So it refuses to compile until you tell it what to return in these cases.
If the other cases should never happen, then throw an exception:
public static boolean play(int input)
{
if (input == 1)
return true;
else if (input == 2)
return false;
else {
throw new IllegalStateException("input is " + input + ". Something's really wrong");
}
}
Java method MUST return a value unless it states void as return.
In your play method, if input is not 1 or 2, Java won't return any value. This does not allow to compile in Java.
In your numToChoice method, if num is not 1, 2 or 3, Java won't return any value. This does not allow to compile in Java.
Add an else close to return a value in "unexpected" cases, and allow Java to compile.

How do I make a String int terminator?

So im making everyone's fun game "Rock, Paper, Scissors" I got everything working, except having the while loop repeat 3 time before stopping. Well it does repeat 3 times and stops, but the 2nd and 3rd repeat the variables don't change. Take a look at the code and tell me what I'm doing wrong.
**UPDATE: Now that I have everything working how do I get this "Q" string to terminate the loop?
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;
Scanner in = new Scanner(System.in);
Random gen = new Random();
System.out.println("Enter Rock(1), Paper(2), Scissors(3) {Q to quit]: ");
int 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();
System.out.println("Enter Rock(1), Paper(2), Scissors(3) {Q to quit]: ");
input = in.nextInt();
count++;
}
}
}
Output:
Enter Rock(1), Paper(2), Scissors(3) {Q to quit]:
1
Computer: Scissors | You: Rock | Winner: USER
Enter Rock(1), Paper(2), Scissors(3) {Q to quit]:
2
Computer: Rock | You: Paper | Winner: USER
Enter Rock(1), Paper(2), Scissors(3) {Q to quit]:
Q
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at RockPaperScissors.main(RockPaperScissors.java:102)
The logic that actually does anything with the input – all those if statements – is outside of the loop. With each iteration through the look, none of that logic is not actually executed. It all just happens first. Try this instead:
for (int count=0; count < 3; count++)
{
int input = in.nextInt();
int compint = gen.nextInt(3) + 1;
// all the if statements and printing here
}
**UPDATE: Now that I have everything working how do I get this "Q" string to terminate the loop?
You're getting an InputMismatchException when typing Q but the code calls Scanner#nextInt(). The docs are pretty clear on what the problem is:
Thrown by a Scanner to indicate that the token retrieved does not match the pattern for the expected type, or that the token is out of range for the expected type.
It's basically the Scanner's way of telling you "you asked for an int but the next token isn't one." You can add an additional check before the nextInt() calls, using Scanner#hasNextInt(), to verify that the next token actually is an int. If it's not an int, then you can plan on parsing it just as a string.
So instead of this:
input = in.nextInt();
Do something like this:
if (in.hasNextInt())
{
input = in.nextInt();
} else if (in.hasNext("Q")) {
// quit
}
seems you wanted to use do - while loop
it would work:
do{
compint = gen.nextInt(3) + 1;
System.out.println("Enter Rock(1), Paper(2), Scissors(3) {Q to quit]: ");
int input = in.nextInt();
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("Enter Rock(1), Paper(2), Scissors(3) {Q to quit]: ");
input = in.nextInt();
count++;
}while (count < 3);

Categories

Resources