Issues with counter and for loop. Assitance appreciated - java

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 !

Related

Stuck in logic for movie guess game in java (by udacity)

I am making a movie guessing game(much like hangman but doesn't contain the stick figure and stuff) on Java that takes input from the user, letter by letter. I am stuck where I want the letter entered to replace all instances of that letter in the title of the movie. My code is not working completely.
Later, I am gonna apply the logic that stops the user from entering the same letter again. But at the moment I need to fix this particular issue. Any help?
This is the game process function in my game class.
public void GameProcess(char[] dashedarray) {
Scanner input = new Scanner(System.in);
char guess;
int i = 0;
int spaces = 0;
int correct = 0;
int wrong = 0;
boolean run = true;
while (run) {
if (dashedarray[i] == ' ') {
spaces++;
i++;
continue;
} else {
System.out.println("Enter your guess.");
guess = input.next().charAt(0);
for (int j = 0; j < dashedarray.length; j++) {
if (dashedarray[j] != ' ') {
if (moviename.charAt(i) == guess) {
dashedarray[i] = guess;
correct++;
}
else if(moviename.charAt(j) == guess) {
dashedarray[j] = guess;
correct++;
}
}
else
{
wrong++;
}
}
i++;
PrintArray(dashedarray);
if (correct == (moviename.length() - spaces)) {
System.out.println("You have won.");
break;
} else if (wrong == 10) {
System.out.println("You have lost.");
break;
}
System.out.println("The number of wrong guesses is " + wrong + ".");
}
}
You don't need i at all. spaces is to count the number of spaces in your answer, which does not need to be guessed. You should do that outside of the loop.
Scanner input = new Scanner(System.in);
char guess;
int i = 0;
int spaces = 0;
int correct = 0;
int wrong = 0;
boolean run = true;
for (int i = 0; i < dashedarray.length; i++) {
spaces++;
}
while (run) {
System.out.println("Enter your guess.");
guess = input.next().charAt(0);
boolean match = false;
for (int j = 0; j < dashedarray.length; j++) {
if (dashedarray[j] != ' ') {
if(moviename.charAt(j) == guess) {
dashedarray[j] = guess;
correct++;
match = true;
}
}
}
// It matched nothing, this input is wrong.
if (!match) {
wrong++;
}
PrintArray(dashedarray);
if (correct == (moviename.length() - spaces)) {
System.out.println("You have won.");
break;
} else if (wrong == 10) {
System.out.println("You have lost.");
break;
}
System.out.println("The number of wrong guesses is " + wrong + ".");
}

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!

Math Practice issues

I have to do this project for my programming class that requires us to prompt the user for how many math problems they want to solve, the difficulty they desire (easy or hard), and then to randomly ask math problems based on their input. For some reason, I cannot get the code to operate past asking for the difficulty level. I think the issue is the way I'm trying to randomly select operators, but I'm not sure. Here's my code:
import java.util.Scanner;
import java.util.Random;
public class MathPractice {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
Random rand = new Random();
int answer;
int count = 0;
int solution;
int correct = 0;
int numEasy1 = rand.nextInt(10);
int numEasy2 = rand.nextInt(10);
int numHard1 = rand.nextInt(20) - 9;
int numHard2 = rand.nextInt(20) - 9;
int sign = rand.nextInt(4);
System.out.print("How many problems do you want? ");
int number = keyboard.nextInt();
System.out.print("What level difficulty would you prefer (easy/hard)? ");
String difficulty = keyboard.next();
if (difficulty == "easy" || difficulty == "Easy") {
while (count < number) {
if (sign == '0') {
System.out.print(numEasy1+" + "+numEasy2+" = ");
answer = keyboard.nextInt();
solution = numEasy1 + numEasy2;
count++;
if (answer == solution) {
System.out.println("Correct!");
correct++;
count++;
} else {
System.out.println("Incorrect. Correct answer is "+solution);
count++;
}
} else if (sign == '1') {
System.out.print(numEasy1+" - "+numEasy2+" = ");
answer = keyboard.nextInt();
solution = numEasy1 - numEasy2;
count++;
if (answer == solution) {
System.out.println("Correct!");
correct++;
count++;
} else {
System.out.println("Incorrect. Correct answer is "+solution);
count++;
}
} else if (sign == '2') {
System.out.print(numEasy1+" * "+numEasy2+" = ");
answer = keyboard.nextInt();
solution = numEasy1 * numEasy2;
count++;
if (answer == solution) {
System.out.println("Correct!");
correct++;
count++;
} else {
System.out.println("Incorrect. Correct answer is "+solution);
count++;
}
} else if (sign =='3') {
System.out.print(numEasy1+" / "+numEasy2+" = ");
answer = keyboard.nextInt();
solution = numEasy1 / numEasy2;
count++;
if (answer == solution) {
System.out.println("Correct!");
correct++;
count++;
} else {
System.out.println("Incorrect. Correct answer is "+solution);
count++;
}
}//inner if statement
}//while loop
} else if (difficulty == "hard" || difficulty == "Hard") {
while (count < number) {
if (sign == '0') {
System.out.print(numHard1+" + "+numHard2+" = ");
answer = keyboard.nextInt();
solution = numHard1 + numHard2;
count++;
if (answer == solution) {
System.out.println("Correct!");
correct++;
count++;
} else {
System.out.println("Incorrect. Correct answer is "+solution);
count++;
}
} else if (sign == '1') {
System.out.print(numHard1+" - "+numHard2+" = ");
answer = keyboard.nextInt();
solution = numHard1 - numHard2;
count++;
if (answer == solution) {
System.out.println("Correct!");
correct++;
count++;
} else {
System.out.println("Incorrect. Correct answer is "+solution);
count++;
}
} else if (sign == '2') {
System.out.print(numHard1+" * "+numHard2+" = ");
answer = keyboard.nextInt();
solution = numHard1 * numHard2;
count++;
if (answer == solution) {
System.out.println("Correct!");
correct++;
count++;
} else {
System.out.println("Incorrect. Correct answer is "+solution);
count++;
}
} else if (sign == '3') {
System.out.print(numHard1+" / "+numHard2+" = ");
answer = keyboard.nextInt();
solution = numHard1 / numHard2;
count++;
if (answer == solution) {
System.out.println("Correct!");
correct++;
count++;
} else {
System.out.println("Incorrect. Correct answer is "+solution);
count++;
}
}//inner if statement
}//while loop
} //if statement
System.out.println("You got "+correct+" correct out of "+number+".");
}
}
try using nextLine. which will consume new line character after the input
System.out.print("How many problems do you want? ");
int number = keyboard.nextInt();
keyboard.nextLine();
System.out.print("What level difficulty would you prefer (easy/hard)? ");
String difficulty = keyboard.next();
and use equals method to compare string values ,== will compare the object reference.
Your code if (sign == '0') { is comparing an integer form the rand.nextInt() function to a char. Change '0' to just 0 for all your if statements
You need to change if (difficulty == "easy" || difficulty == "Easy") to if (difficulty.equalsIgnoreCase("easy")) and do the same for the "hard" loop.
Also, you have sign declared as an int but you compare it as if it were a char. change all your (sign == '3') lines to (sign == 3) and you should be good.

Why does this keep looping?

The error I'm getting when I try to run my program is that it keeps looping between turnFirstNumber() and turnSecondNumber() after I go through all 3 'turns' entirely the first time.
EDIT: SEE BOTTOM.
My Test Class:
public class testLock
{
public static void main (String[] args)
{
Lock testLock = new Lock();
testLock.turnLock();
return;
}
}
Here's my code segments causing me grief:
public void turnLock()
{
System.out.print("This is a lock that goes from 0 to 39. You must turn the knob clockwise first, then counterclockwise twice, ");
System.out.print("then clockwise for the final input. Specify how many revolutions you want (Positive number indicates ");
System.out.println("COUNTER CLOCKWISE. Negative number indicates CLOCKWISE.");
turnFirstNumber();
turnSecondNumber();
turnThirdNumber();
System.out.println("The combination you chose was: " + tempFirst + ", " + tempSecond + ", and " + tempThird + ".");
return;
}
private boolean turnFirstNumber()
{
revoCount = 0;
System.out.print("11111111What is your desired direction and number of revolutions? (Positive number is counterclockwise, negative number is clockwise): ");
count = in.nextInt();
if (count > 0)
isClockwise = false;
else if (count < 0)
isClockwise = true;
else
{
throw new IllegalArgumentException("Your desired direction of spinning the lock is invalid. Please choose a number other than 0.");
}
System.out.print("\n11111111111What is your desired first number?: ");
desiredNumber = in.nextInt();
if (!isClockwise) //user desires countercockwise revolution
{
do {
for (int i = 0; i < (count * 40); i++)
{
activeNumber++;
if (activeNumber > 39)
activeNumber = 0;
if (activeNumber == desiredNumber)
revoCount++;
}
} while ((activeNumber != desiredNumber) && (revoCount < count));
}
else if (isClockwise) //user desires clockwise revolution
{
do {
for (int i = 0; i < (Math.abs(count) * 40); i++)
{
activeNumber--;
if (activeNumber < 0)
activeNumber = 39;
if (activeNumber == desiredNumber)
revoCount++;
}
} while ((activeNumber != desiredNumber) && (revoCount < Math.abs(count)));
}
tempFirst = activeNumber;
if ((activeNumber == first) && (count < 0)) //if first number is correct and user picked correct orientation and revolutions
return true;
else
return false;
}
private boolean turnSecondNumber()
{
revoCount = 0;
System.out.print("2222222222What is your desired direction and number of revolutions? (Positive number is counterclockwise, negative number is clockwise): ");
count = in.nextInt();
if (count > 0)
isClockwise = false;
else if (count < 0)
isClockwise = true;
else
{
throw new IllegalArgumentException("Your desired direction of spinning the lock is invalid. Please choose a number other than 0.");
}
System.out.print("\n222222222What is your desired second number?: ");
desiredNumber = in.nextInt();
if (!isClockwise) //user desires countercockwise revolution
{
do {
for (int i = 0; i < (count * 40); i++)
{
activeNumber++;
if (activeNumber > 39)
activeNumber = 0;
if (activeNumber == desiredNumber)
revoCount++;
}
} while ((activeNumber != desiredNumber) && (revoCount < count));
}
else if (isClockwise) //user desires clockwise revolution
{
do {
for (int i = 0; i < (Math.abs(count) * 40); i++)
{
activeNumber--;
if (activeNumber < 0)
activeNumber = 39;
if (activeNumber == desiredNumber)
revoCount++;
}
} while ((activeNumber != desiredNumber) && (revoCount < Math.abs(count)));
}
tempSecond = activeNumber;
if ((activeNumber == second) && (count == 2)) //if second number is correct and user picked correct orientation and revolutions
return true;
else
return false;
}
private boolean turnThirdNumber()
{
revoCount = 0;
System.out.print("Enter '1' to twist the dial counterclockwise until you reach your desired number. Enter '-1' to twist the dial clockwise until you reach your desired number.: ");
count = in.nextInt();
if (count == 1)
isClockwise = false;
else if (count == (-1))
isClockwise = true;
else
{
throw new IllegalArgumentException("You are not supposed to do a full revolution on the third number of the combination. Now you have to restart.");
}
System.out.print("\n333333333What is your desired third and final number?: ");
activeNumber = in.nextInt();
activeNumber = Math.abs(activeNumber);
tempThird = activeNumber;
if (activeNumber > 39)
{
throw new IllegalArgumentException("You desire a number that is not on the lock. The lock goes from 0 to 39. Try again.");
}
if ((activeNumber == third) && (isClockwise)) //if third number is correct and user picked correct orientation and revolutions
return true;
else
return false;
}
EDIT: So after testing more carefully, I found that my openLock() method may be calling my turnFirst, turnSecond, and turnThird methods somehow. I commented out my turnLock() method in my test class and ran the openLock() method and it started calling turnFirst and turnSecond multiple times and finally turnThird for some reason after a few loops. Here's the openLock():
public void openLock()
{
if ((turnFirstNumber()) && (turnSecondNumber()) && (turnThirdNumber()) && (isClosed)) //if all 3 passed and lock is not open already
{
isClosed = false;
System.out.println("Your combination is correct and the lock has been opened.");
return;
}
else if (!isClosed) //lock's already open
{
System.out.println("The lock is already open.");
return;
}
else if ((!turnFirstNumber()) && (turnSecondNumber()) && (turnThirdNumber())) //first wrong
{
System.out.println("The first number you input is incorrect.");
return;
}
else if ((!turnFirstNumber()) && (!turnSecondNumber()) && (turnThirdNumber())) //first and second wrong
{
System.out.println("The first 2 numbers you input are incorrect.");
return;
}
else if ((!turnFirstNumber()) && (turnSecondNumber()) && (!turnThirdNumber())) //first and third wrong
{
System.out.println("The first and last numbers you input are incorrect.");
return;
}
else if ((turnFirstNumber()) && (turnSecondNumber()) && (!turnThirdNumber())) //third wrong
{
System.out.println("The last number you input is incorrect.");
return;
}
else if ((turnFirstNumber()) && (!turnSecondNumber()) && (!turnThirdNumber())) //second and third wrong
{
System.out.println("The second and last numbers you input are incorrect.");
return;
}
else if ((turnFirstNumber()) && (!turnSecondNumber()) && (turnThirdNumber())) //second is wrong
{
System.out.println("The second number you input is incorrect.");
return;
}
else
{
System.out.println("Your entire combination is INCORRECT. Please try again."); //all wrong
return;
}
}
Are you sure it's looping?
In your openLock method it's calling the methods turnFirstNumber, turnSecondNumber and turnThirdNumber in every if-statement.
In case the last number is incorrect, it has called the methods turnFirstNumber, turnSecondNumber and turnThirdNumber each 5 times.
I think it's better to introduce variables like firstTurnCorrect, secondTurnCorrect and thirdTurnCorrect and compare those values to get the right message:
boolean firstTurnCorrect = turnFirstNumber();
boolean secondTurnCorrect = turnSecondNumber();
boolean thirdTurnCorrect = turnThirdNumber();
if (!firstTurnCorrect && secondTurnCorrect && thirdTurnCorrect) ...
This way those methods only gets called once.

How do I parse a string as an Integer

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");
}

Categories