I am working on a rock paper scissors homework assignment for my java class. I am done with the program and I compiled it successfully. I ran the file and it looked like it was working. It gives me the menu and I choose a variable, R for example, and when I press enter it doesn't do anything but go to the next line. I press enter again and it gives me an index out of bounds error which I assume is because the second time it didn't have a variable to use. How do I get the program to move forward? The program is supposed to play five times then return a winner. Thanks in advance.This image is what I get when I run the program and press enter twice
package Rock;
import java.util.Scanner;
public class RPSG {
public static void main(String[] args) {
String[] computerHandArray = {"R","P","S"};
String computerHand ="", thisWinner="", theFinalWinner="";
int index=0;
int timesIWon=0;
int timesComputerWon=0;
Scanner in = new Scanner(System.in);
System.out.println("\tMenu\n\n(R) Rock\n(P) Paper\n(S) Scissors" + "\n\nEnter Your Hand (R, P, or S): ");
for (int i=0; i<5; i++) {
String myHandString = in.nextLine();
String myHand = myHandString.substring(0,1);
myHand = myHand.toUpperCase();
index = (int)(Math.random() * 10) % 3;
computerHand = computerHandArray[index];
thisWinner = theWinnerofOneGame(myHand, computerHand);
if(thisWinner.equals("ME")){
timesIWon++;
}
else if(thisWinner.equals("COMPUTER")) {
timesComputerWon++;
}
}
if(timesIWon == timesComputerWon)
theFinalWinner = "TIE";
else if(timesIWon > timesComputerWon)
theFinalWinner = "ME";
else if(timesComputerWon > timesIWon)
theFinalWinner = "COMPUTER";
System.out.println("I won :" + timesIWon);
System.out.println("I won :" + timesComputerWon);
System.out.println("The Final Winner after 5 games is:" +theFinalWinner);
}
private static String theWinnerofOneGame(String myHand, String computerHand){
String theWinner = "Tie";
if(myHand.equals(computerHand)) {
theWinner = "Tie";
}
else if(myHand.equals("R")) {
if (computerHand.equals("P")) {
theWinner = "COMPUTER";
}
}
else if(computerHand.equals("S")) {
theWinner = "ME";
}
else if(myHand.equals("P")) {
if (computerHand.equals("R")) {
theWinner = "ME";
}
else if(computerHand.equals("S")) {
theWinner = "COMPUTER";
}
}
else if(myHand.equals("S")) {
if (computerHand.equals("R")) {
theWinner = "COMPUTER";
}
else if(computerHand.equals("P")) {
theWinner = "ME";
}
}
return theWinner;
}
}
You print the prompt for input only once, i.e. before the for loop. Now when you enter your first input, the content of the loop will be executed. Because you don't print anything inside the loop, there is no prompt for the next round. After you press enter a second time, the in.nextLine() returns an empty string and subsequently, the substring method throws the exception.
You should probably do something like this (note the marked lines):
System.out.println("\tMenu\n\n(R) Rock\n(P) Paper\n(S) Scissors" + "\n\n");
for (int i=0; i<5; i++) {
> System.out.println("Enter Your Hand (R, P, or S): ");
String myHandString = in.nextLine();
String myHand = myHandString.substring(0,1);
myHand = myHand.toUpperCase();
index = (int)(Math.random() * 10) % 3;
computerHand = computerHandArray[index];
thisWinner = theWinnerofOneGame(myHand, computerHand);
if(thisWinner.equals("ME")){
timesIWon++;
> System.out.println("You won.");
} else if(thisWinner.equals("COMPUTER")) {
timesComputerWon++;
> System.out.println("The computer won.");
}
}
And even better, check if the input of the user is valid before computing the substring.
Good day, i'm stuck figuring out correct way to implement a function, the function has the following functionality.
1. When program starts, text is displayed to enter a key or leave field empty.
2. If text was entered , do A.
3. If text wasn't entered do B.
This is what i've done so far.
System.out.println("Enter any key to get data or leave empty");
//Just give some value
int value = 0;
try {
for (int i = 5; i > 0; i--) {
System.out.println("Starting in " + i);
Thread.sleep(1000);
//If enter was pressed then theoretically value
//should be 1(Not working)
value = System.in.read();
}
if (value != 0) {
Database.getInstance().getAllStamps();
} else {
start();
}
} catch (Exception e) {
e.printStackTrace();
}
Scanner sc = new Scanner(System.in);
for (int i = 5; i > 0; i--) {
System.out.println("Starting in " + i);
Thread.sleep(1000); // Execution pauses
if(sc.hasNext())
// call your function
break;
}
}
or
boolean flag = false;
for (int i = 5; i > 0; i--) {
System.out.println("Starting in " + i);
Thread.sleep(1000); // Execution pauses
if(sc.hasNext())
flag = true;
}
}
if(flag) {
// call your function
}
One way to get raw input is to use a java.util.Scanner.
Use something like this:
Scanner sc = new Scanner(System.in);
if(sc.hasNext()){
//do stuff with input
}
else{
//handle stuff
}
So my objective is to create a maths game where the user selects if he/she wants a maths question from a file or a random generate one consisting of the 4 maths elements in 3 difficulties.I have created a lot of methods... I have an idea where im going but now im stuck. I need to have it so it keeps a score of questions answered correctly. How do i return the points to the main method and have the game going until the user presses 3 on the gamePlay()method
public class MathsGameProject2 {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int score;
int points = 0;
int questionType;
System.out.print("Please enter the what type of question you want" + "\n 1 Question from a file" + "\n 2 Random question" + "\n 3 Quit game\n");
questionType = keyboard.nextInt();
while (questionType != 3) {
if (questionType == 1) {
questionFromFile();
} else if (questionType == 2) {
randomQuestion();
} else {
System.out.println("Please enter the what type of question you want" + "\n 1 Question from a file" + "\n 2 Random question" + "\n 3 Quit game\n");
}
}
}
public static questionFromFile() {
}
public static randomQuestion() {
Scanner keyboard = new Scanner(System.in);
int difficulty;
System.out.println("Please enter the difficulty you want to play." + "\n 1. Easy" + "\n 2. Medium" + "\n 3. Hard\n");
difficulty = keyboard.nextInt();
if (difficulty == 1) {
easy();
} else if (difficulty == 2) {
medium();
} else if (difficulty == 3) {
hard();
} else {
System.out.println("Please enter a number between 1-3\n");
}
}
public static easy() {
Scanner keyboard = new Scanner(System.in);
int mathElement;
System.out.print("What element of maths do you want?" + "\n1 Additon" + "\n2 Subtraction" + "\n3 Multiplication" + "\n4 Division\n");
mathElement = keyboard.nextInt();
if (mathElement == 1) {
easyAdd();
} else if (mathElement == 2) {
easySub();
} else if (mathElement == 3) {
easyMulti();
} else if (mathElement == 4) {
easyDiv();
} else {
System.out.println("Please enter a number between 1-4\n");
}
}
public static easyAdd() {
Scanner keyboard = new Scanner(System.in);
Random rand = new Random();
int num = rand.nextInt(10) + 1;
int num2 = rand.nextInt(10) + 1;
int correct = num + num2;
int answer;
System.out.print("What is the answer of " + num + " + " + num2 + " ?");
answer = keyboard.nextInt();
if (answer == correct) {
}
}
In order to keep track of how many questions the user answers successfully, you will need to:
For each question, return whether or not the user answered correctly
Have a counter which increments whenever a user answers a question correctly
Optionally, have a counter which increments whenever a question is answered wrong
For #1, you can use a boolean return value for specifying if the question was answered successfully.
return (answer == correct);
You will want to propagate that return value all the way up to the main() method.
static void main() {
....
boolean isCorrect = randomQuestion();
....
}
static boolean randomQuestion() {
....
return easy();
....
}
static boolean easy() {
....
return easyAdd();
....
}
static boolean easyAdd() {
...
return (answer == correct);
}
Then for #2 and #3, you can increment counter(s) defined in main based on the value returned by randomQuestion()
int numberCorrect = 0;
int numberWrong = 0;
....
boolean isCorrect = randomQuestion();
if (isCorrect) {
numberCorrect++;
} else {
numberIncorrect++;
}
Additionally (no pun intended), you can use a while loop to continuously receive user input until you get your exit code, which in this case is 3. One way to do this is to use a while(true) loop and break out when the user enters 3.
while (true) {
/* Get user input */
....
if (questionType == 3) {
break;
}
}
Finally, after your loop, you can simply print out the value of your numberCorrect and numberIncorrect counters.
Hope this helps.
EDIT: None of the answers so far work. The closest I've gotten (Thank you, TNT) is using:
while (true) {
try {
value = s.nextDouble();
break;
} catch (java.util.InputMismatchException ex) {
System.out.println("That is not a number! Please enter a numerical value.");
}
}
but if the user inputs something like "foo", it puts me in an infinite loop saying "That is not a number! Please enter a numerical value."
My program here asks for an unit to choose from (fl.oz, gal, oz, lb, in, ft, or mi), asks how much of it they have, and asks for the unit they wish to convert to (mL, l, g, kg, mm, cm, m, or km).
My program works, refusing to convert from silly conversions such as gal to cm, telling you to re-input if they enter anything other than fl.oz, gal, etc.
The only thing I cannot figure out is if the user inputs something like "foo" when the program prompts the user for how much of the unit they have. My goal is to have the program say something like "That is not a number! Please enter a numerical value." If I run the program currently and enter anything but a numerical value, I get errors in the console. I'm pretty sure there is going to be loops involved, and I've looked up the API documentation for parse, but I'm still stuck.
Here is my program (it's long, sorry!):
import java.util.Scanner;
public class UnitConversions {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("What kind of unit do you have? Choose from: fl.oz, gal, oz, lb, in, ft, or mi. ");
String startingVariable = s.next();
while (!startingVariable.equals("fl.oz") && !startingVariable.equals("gal") && !startingVariable.equals("oz")
&& !startingVariable.equals("lb") && !startingVariable.equals("in") && !startingVariable.equals("ft") &&
!startingVariable.equals("mi")) {
System.out.println("That is not what I asked. Please choose from: fl.oz, gal, oz, lb, in, ft, or mi. ");
startingVariable = s.next();
}
System.out.println("How much of it do you have? ");
double value = s.nextDouble();
//here, I don't know what to put!
System.out.println("What would you like to convert to? Choose from: mL, l, g, kg, mm, cm, m, or km ");
String convertedVariable = s.next();
while (!convertedVariable.equals("mL") && !convertedVariable.equals("l") && !convertedVariable.equals("g")
&& !convertedVariable.equals("kg") && !convertedVariable.equals("mm") && !convertedVariable.equals("cm") &&
!convertedVariable.equals("m") && !convertedVariable.equals("km")) {
System.out.println("That is not what I asked. Please choose from: mL, l, g, kg, mm, cm, m, or km. ");
convertedVariable = s.next();
}
double result = 0;
if (startingVariable.equals("fl.oz")) {
if (convertedVariable.equals("mL")) {
result = (29.5735 * value);
} else if (convertedVariable.equals("l")) {
result = (0.0295735 * value);
} else if (convertedVariable.equals("g")) {
result = 0;
} else if (convertedVariable.equals("kg")) {
result = 0;
} else if (convertedVariable.equals("mm")) {
result = 0;
} else if (convertedVariable.equals("cm")) {
result = 0;
} else if (convertedVariable.equals("m")) {
result = 0;
} else if (convertedVariable.equals("km")) {
result = 0;
}
if (result == 0) {
System.out.println("You cannot convert from " + startingVariable + " to " + convertedVariable + ".");
System.out.println("]:");
}
}
if (startingVariable.equals("gal")) {
if (convertedVariable.equals("mL")) {
result = (3785.41 * value);
} else if (convertedVariable.equals("l")) {
result = (3.78541 * value);
} else if (convertedVariable.equals("g")) {
result = 0;
} else if (convertedVariable.equals("kg")) {
result = 0;
} else if (convertedVariable.equals("mm")) {
result = 0;
} else if (convertedVariable.equals("cm")) {
result = 0;
} else if (convertedVariable.equals("m")) {
result = 0;
} else if (convertedVariable.equals("km")) {
result = 0;
}
}
if (startingVariable.equals("oz")) {
if (convertedVariable.equals("mL")) {
result = (29.5735 * value);
} else if (convertedVariable.equals("l")) {
result = (0.0295735 * value);
} else if (convertedVariable.equals("g")) {
result = (28.3495 * value);
} else if (convertedVariable.equals("kg")) {
result = (0.0283495 * value);
} else if (convertedVariable.equals("mm")) {
result = 0;
} else if (convertedVariable.equals("cm")) {
result = 0;
} else if (convertedVariable.equals("m")) {
result = 0;
} else if (convertedVariable.equals("km")) {
result = 0;
}
}
if (startingVariable.equals("lb")) {
if (convertedVariable.equals("mL")) {
result = 0;
} else if (convertedVariable.equals("l")) {
result = 0;
} else if (convertedVariable.equals("g")) {
result = (453.592 * value);
} else if (convertedVariable.equals("kg")) {
result = (0.453592 * value);
} else if (convertedVariable.equals("mm")) {
result = 0;
} else if (convertedVariable.equals("cm")) {
result = 0;
} else if (convertedVariable.equals("m")) {
result = 0;
} else if (convertedVariable.equals("km")) {
result = 0;
}
}
if (startingVariable.equals("in")) {
if (convertedVariable.equals("mL")) {
result = 0;
} else if (convertedVariable.equals("l")) {
result = 0;
} else if (convertedVariable.equals("g")) {
result = 0;
} else if (convertedVariable.equals("kg")) {
result = 0;
} else if (convertedVariable.equals("mm")) {
result = (25.4 * value);
} else if (convertedVariable.equals("cm")) {
result = (2.54 * value);
} else if (convertedVariable.equals("m")) {
result = (0.0254 * value);
} else if (convertedVariable.equals("km")) {
result = (0.000025400 * value);
}
}
if (startingVariable.equals("ft")) {
if (convertedVariable.equals("mL")) {
result = 0;
} else if (convertedVariable.equals("l")) {
result = 0;
} else if (convertedVariable.equals("g")) {
result = 0;
} else if (convertedVariable.equals("kg")) {
result = 0;
} else if (convertedVariable.equals("mm")) {
result = (304.8 * value);
} else if (convertedVariable.equals("cm")) {
result = (30.48 * value);
} else if (convertedVariable.equals("m")) {
result = (0.30481 * value);
} else if (convertedVariable.equals("km")) {
result = (0.0003048 * value);
}
}
if (startingVariable.equals("mi")) {
if (convertedVariable.equals("mL")) {
result = 0;
} else if (convertedVariable.equals("l")) {
result = 0;
} else if (convertedVariable.equals("g")) {
result = 0;
} else if (convertedVariable.equals("kg")) {
result = 0;
} else if (convertedVariable.equals("mm")) {
result = (1609344 * value);
} else if (convertedVariable.equals("cm")) {
result = (160934 * value);
} else if (convertedVariable.equals("m")) {
result = (1609.34 * value);
} else if (convertedVariable.equals("km")) {
result = (1.60934 * value);
}
}
if (result == 0) {
System.out.println("You cannot convert from " + startingVariable + " to " + convertedVariable + ". Sorry dude.");
System.out.println("]:");
} else {
System.out.println("░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░");
System.out.printf(value + " " + startingVariable + " = %.3f " + convertedVariable + ".\n", result);
System.out.println("░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░");
}
if (result > 10000) {
System.out.println("That's a lot of " + convertedVariable +"!");
}
}
}
You can use a while loop and try-catch for a situation like this. As long as something other than a double is entered, an InputMismatchException will be thrown, so the break statement will never be reached unless the user enters a number.
double value;
while (true) {
try {
value = s.nextDouble();
break;
} catch (java.util.InputMismatchException ex) {
System.out.println("That is not a number! Please enter a numerical value.");
s.nextLine();
}
}
s.nextLine();
The reason why it was in an infinite loop before was because the scanner continued attempting to parse the invalid input in the case that the user did not enter a number. The string kept causing an InputMismatchException to be thrown, which explains the infinite loop. Adding s.nextLine() consumes the invalid input and prevents this from happening. In the event that the user does enter a number, the s.nextLine() statement would consume the input so the user will be prompted to enter the next string.
I'm assuming the errors are along the lines of a conversion error? You need to catch the exception in a try block and you can then alert the user and get another input.
you need to catch the exception:
try
{
double value = s.nextDouble();
}
catch(InputMismatchException exception)
{
System.out.println("This is not a number");
}
Use the try catch to handle this kind of situation.
when the user input non-numeric it will throw an exception then catch it then perform any thing you want from the catch block.
try{
System.out.println("How much of it do you have? ");
double value = s.nextDouble();
}catch(InputMismatchException ime){
System.out.println("This is not a number");
}
public class InputMismatchException extends NoSuchElementException
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.
"but if the user inputs something like "foo", it puts me in an infinite loop saying "That is not a number! Please enter a numerical value.""
It does not "put you in an infinite loop", it just keeps asking until you enter a number, like you asked in the original question. What would you like it to do instead?
the program will ask the user to enter the code of the item he wants to search for. if the item's code exists it will print it to the screen and all works fine until here. The problem is when the user enters code that not exists, the program won't work. it doesn't print "Item not found"
here is the code
public void searchItem(){
boolean invalidInput;
int q = -1;
do {
try {
boolean found = false;
invalidInput = false;
System.out.println("Enter the item's code you want to search for : ");
q = s.nextInt();
out: for (int i = 0; i<items.length; i++){
if(q == items[i].getCode()){
System.out.println(items[i].toString());
found = true;
System.exit(2);
}
counter++;
}
if(!found)
System.out.print("Item not found");
} catch (InputMismatchException e) {
System.out.println("Please enter a valid code [Numbers Only]");
s.next();
invalidInput = true; // This is what will get the program to loop back
}
} while (invalidInput);
}
If i use this (condensed form) of your code it works, and prints "Item not found" as we would expect... So the problem is somewhere else I feel....
Please provide further information about what happens if you enter a missing (but valid) item number!
public static void main(String[] args) {
boolean invalidInput;
int q = -1;
int[] items = { 1, 2, 3, 4 };
do {
boolean found = false;
invalidInput = false;
System.out.println("Enter the item's code you want to search for : ");
q = 5;
for (int i = 0; i < items.length; i++) {
if (q == items[i]) {
System.out.println(items[i]);
found = true;
System.exit(2);
}
}
if (!found)
System.out.print("Item not found");
} while (invalidInput);
}