In this Java program the user is supposed to guess a number from 1 to 100, and then if you press S it shows you a summary of the tries. The problem is that I am taking the input string and converting it to a number so I can compare it to the range, but then I also need to be able to use that string as a menu input.
UPDATE How can i make the program go back to the menu option after the user guesses correctly. So after the user wins, i would like for the problem to display the summary report which can be otherwise accessed by using S
Here is my code
public class GuessingGame {
public static void main(String[] args) {
// Display list of commands
System.out.println("*************************");
System.out.println("The Guessing Game-inator");
System.out.println("*************************");
System.out.println("Your opponent has guessed a number!");
System.out.println("Enter a NUMBER at the prompt to guess.");
System.out.println("Enter [S] at the prompt to display the summary report.");
System.out.println("Enter [Q] at the prompt to Quit.");
System.out.print("> ");
// Read and execute commands
while (true) {
// Prompt user to enter a command
SimpleIO.prompt("Enter command (NUMBER, S, or Q): ");
String command = SimpleIO.readLine().trim();
// Determine whether command is "E", "S", "Q", or
// illegal; execute command if legal.
int tries = 0;
int round = 0;
int randomInt = 0;
int number = Integer.parseInt(command);
if (number >= 0 && number <= 100) {
if(randomInt == number){
System.out.println("Congratulations! You have guessed correctly." +
" Summary below");
round++;
}
else if(randomInt < number)
{
System.out.println("your guess is TOO HIGH. Guess again or enter Q to Quit");
tries++;
}
else if(randomInt > number){
System.out.println("your guess is TOO LOW. Guess again or enter Q to Quit");
tries++;
}
} else if (command.equalsIgnoreCase("s")) {
// System.out.println("Round Guesses");
// System.out.println("-------------------------");
// System.out.println(round + "" + tries);
} else if (command.equalsIgnoreCase("q")) {
// Command is "q". Terminate program.
return;
} else {
// Command is illegal. Display error message.
System.out.println("Command was not recognized; " +
"please enter only E, S, or q.");
}
System.out.println();
}
}
}
You should check for the S/Q value first, then parse the string to an integer. If you catch NumberFormatException (thrown by Integer.parseInt()), you can determine if the input is a valid value. I would do something like that:
if ("s".equalsIgnoreCase(command)) {
// Print summary
} else if ("q".equalsIgnoreCase(command)) {
// Command is "q". Terminate program.
return;
} else {
try {
Integer number = Integer.parseInt(command);
if(number < 0 || number > 100){
System.out.println("Please provide a value between 0 and 100");
} else if(randomInt == number){
System.out.println("Congratulations! You have guessed correctly." +
" Summary below");
round++;
} else if(randomInt < number) {
System.out.println("your guess is TOO HIGH. Guess again or enter Q to Quit");
tries++;
} else if(randomInt > number) {
System.out.println("your guess is TOO LOW. Guess again or enter Q to Quit");
tries++;
}
} catch (NumberFormatException nfe) {
// Command is illegal. Display error message.
System.out.println("Command was not recognized; " +
"please enter only a number, S, or q.");
}
}
With this algorithm (I'm sure it can be optimized), you treat following cases:
User enters s/S
User enters q/Q
User enters a non valid value (not a number)
User enters a non valid number (less than 0 or greater than 100)
User enters a valid number
To check if a string is an integer, just attempt to parse it as an integer and if an exception is thrown, then it is not an Integer.
See:
http://bytes.com/topic/java/answers/541928-check-if-input-integer
String input = ....
try {
int x = Integer.parseInt(input);
System.out.println(x);
}
catch(NumberFormatException nFE) {
System.out.println("Not an Integer");
}
Integer.parseInt(command) will give you NumberFormatException if the String is not valid. It is possible in your code if the user enters 'S' or 'E' which cannot be parsed to int value.
I have modified your code. Check this code :
while (true) {
// Prompt user to enter a command
SimpleIO.prompt("Enter command (NUMBER, S, or Q): ");
String command = SimpleIO.readLine().trim();
// Determine whether command is "E", "S", "Q", or
// illegal; execute command if legal.
int tries = 0;
int round = 0;
int randomInt = 0;
if(!command.equals("S") && !command.equals("E")) {
// Only then parse the command to string
int number = Integer.parseInt(command);
if (number >= 0 && number <= 100) {
if(randomInt == number){
You're trying to convert the incoming String to an int before you check if its an escape sequence (S or Q).
Try rearranging your if statement to check for S and Q first then try converting the value to an int.
I'd also recommend you wrap the Integer.parseInt call (it's subsequent, reliant code) in a try-catch block, so you can provided an error statement to the user if they type in anything that isn't an int
Related
I need to write a java program reading in an indefinite amount of numbers and saves them to a collection of numbers, until an (even number) is entered in by the user. I have tried with a while loop, that when a positive number is found in it it stops. But it is not really working. Here is codes I have tried:
public static void main(String[] args) {
int programInteger = 1;
int inputtedInteger;
while (programInteger < 2) {
System.out.println("Enter a number: "); //Asks user to input a number
Scanner in = new Scanner(System.in);
inputtedInteger = Scanner(in.nextLine);
if (inputtedInteger != 0) {
System.out.println("The number "+ inputtedInteger +" that you inputted is not an even number, try again: ");
inputtedInteger=in.nextInt();
}
else if (inputtedInteger % 2 == 0){
programInteger =+1;
System.out.println("The number "+inputtedInteger+" that you entered is an even number!");
}
}
}
/* if(inputtedInteger % 2 == 0) {
System.out.println("The number "+ inmatatTal +" you entered is an even number!");
}
else {
System.out.println("Enter a number?! ");
inputtedInteger = in.nextInt();
}
Fixing a few things in the logic of the loop should work:
int inputtedInteger = 0;
Scanner in = new Scanner(System.in);
while (inputtedInteger < 1) {
System.out.println("Enter a number: "); //Asks user to input a number
inputtedInteger = in.nextInt();
if (inputtedInteger % 2 != 0) {
System.out.println("The number "+ inputtedInteger +" that you inputted is not an even number, try again: ");
}
else if (inputtedInteger % 2 == 0){
System.out.println("The number "+inputtedInteger+" that you entered is an even number!");
}
}
I would setup an outline for the code like this:
setup Scanner, create collection
while true:
userInput = scanner.nextInt()
if userInput > 0: break
collection.add(userInput)
print('user entered', collection.length(), 'numbers.')
Hope that helps. I'll leave you to fill this using actual Java syntax.
I wrote a comment on the OP on why your structure is failing to solve the issue at hand.
I'm trying to have my loop only occur three times. So if the user doesn't guess the correct number after their third guess then the loop ends which I have but it doesn't display what the number was. I need the number displayed after the third guess but not sure why it's not displaying the correct number.
import java.util.Scanner;
public class GuessNumberDoWhileA {
public static void main(String[] args) {
//Generate random number from 1-10
int number = (int) (Math.random()*9 + 1);
int count = 0;
//Auto Generated Method stub
Scanner Input = new Scanner(System.in);
//Tell the user to guess a number
System.out.println("Guess a number between 1 and 10");
//int guess = -1;
//while (guess != number) {
while (count < 3) {
count++;
System.out.print("\nEnter your guess: ");
int guess = Input.nextInt();
if (guess == number)
System.out.println("Correct the number was " + number);
else if (guess > number)
System.out.println("Your guess is to high try again!");
else if (guess < number)
System.out.println("Your guess is to low try again!");
else
System.out.println("The correct number is " + number);
}
System.out.println("The number was " + number);
}
}
You need a boolean variable that can be used to check whether user was able to guess the number correctly or not. Initial value of this boolean variable should be false.
You don't need the last else statement in the loop. If user guesses the number correctly, set the boolean variable to true and break out of the loop. After the loop, check if the boolean variable is false or not. If it is false, that means user was not able to guess the number, so display the correct number to the user.
If user is able to guess the number then the first if statement in the loop will print the correct number on the console and break out of the loop. It will also set the boolean variable to true, so correct number will be printed only once on the console.
boolean guessed = false;
while (count < 3) {
count++;
System.out.print("\nEnter your guess: ");
int guess = Input.nextInt();
if (guess == number) {
System.out.println("Correct the number was " + number);
guessed = true;
break;
}
else if (guess > number)
System.out.println("Your guess is to high try again!");
else if (guess < number)
System.out.println("Your guess is to low try again!");
}
if (!guessed) System.out.println("Number was: " + number);
I am working on a project that involves creating a rental car calculator.
What I am trying to do is make it to where when asked: "What vehicle would you like to rent??". If a number that is not between 1-3 is entered when the user is prompted this, then I want the program to loop back to the point of being asked vehicle type again.
Similarly, when prompted for 'Please enter the number of days rented. (Example; 3) : ' I want to only allow the user to input whole positive numbers. for instance, not allowing input of 3.1, 2.35, 0.35 -2 and, etc...
here is what I have written and my attempt at these questions :
package inter;
import java.util.Scanner;
public class Inter {
public static void main(String []args){
int count=0;
int days;
double DailyFee=0, NontaxTotal, CarType, Total,FullTotal=0;
Scanner in=new Scanner(System.in);
System.out.println("If there are any customer press 1 else press 0");
int cus=in.nextInt();
while(cus!=0){
count++;
System.out.print("What vehical would you like to rent?\n");
System.out.println("Enter 1 for an economy car\n");
System.out.println("Enter 2 for a sedan car\n");
System.out.println("Enter 3 for an SUV");
CarType = in.nextInt();
if (CarType == 1) {
DailyFee=31.76;
}
else if(CarType == 2) {
DailyFee=40.32;
}
else if(CarType == 3) {
DailyFee=47.56;
}
else if(CarType <= 0) {
System.out.println("input is not a positive Integer ");
System.out.println("Please enter a positive integer value: ");
cus = 0; }
else if(CarType > 4) {
System.out.println("input is not a positive Integer ");
System.out.println("Please enter a positive integer value: ");
cus = 0; }
System.out.print("Please enter the number of days rented. (Example; 3) : ");
days = Integer.valueOf(in.nextLine());
double x=days;
NontaxTotal = (DailyFee * x);
Total = (NontaxTotal * 1.06);
FullTotal+=Total;
System.out.printf("The total amount due is $ %.2f \n",Total);
System.out.println("If there are any customer press 1 else press 0");
cus=in.nextInt();
}
System.out.println("Count of customers : "+count);
System.out.printf("Total of the Day : $ %.2f",FullTotal);
}
}
Let me help you with this,
I made this code for you, i tried it and it worked
this will check if both answers were whole numbers (integers) and more than zero and will also check if the answer was numeric in the first place so that if the user answered with letters he will be prompted to try again
This is my suggestion:
basically i used the try-catch block with InputMismatchException to detect if the answer was not an integer (whole number ) or was not numeric at all, every time a mistake is detected i flip a boolean to false and keep looping as long as this boolean is false (i flip the boolean back to true before checking otherwise once the user gives a wrong answer he will always be prompted to answer even if he gave a correct answer after)
int vehicleType;
int numberOfDays;
double dailyFee;
boolean validAnswer1 = false;
boolean validAnswer2 = false;
Scanner scan = new Scanner(System.in);
while (validAnswer1 == false) {
validAnswer1 = true;
System.out.println("Choose Vehicle Type");
try {
vehicleType = scan.nextInt();
if (vehicleType <= 0) {
System.out.println("Number must be more than zero");
validAnswer1 = false;
} else if (vehicleType >= 4) {
System.out.println("Number should be from 1 to 3");
validAnswer1 = false;
} else {
if (vehicleType == 1) {
dailyFee=31.76;
} else if(vehicleType == 2) {
dailyFee=40.32;
}else if(vehicleType == 3) {
dailyFee=47.56;
}
while (validAnswer2 == false) {
validAnswer2 = true;
try {
System.out.println("Enter number of days rented ?");
numberOfDays = scan.nextInt();
if (numberOfDays <= 0) {
System.out.println("Number of days must be more than zero");
validAnswer2 = false;
} else {
// calculate your rent total here
}
} catch(InputMismatchException ex) {
System.out.println("Answer must be an Integer");
validAnswer2 = false;
scan.next();
}
}
}
} catch (InputMismatchException ex) {
validAnswer1 = false;
System.out.println("Answer must be an Integer");
scan.next();
}
}
Hope this was useful, do let me know if you still need help
I want to give the user a choice to quit the program while the program is running whenever they feel like it. E.g. Press Q and ENTER at anytime to quit and end program.
I have a try and catch method but whenever I press Q and ENTER, it just displays whats in the catch part.
Here is the code:
public static void partB() {
//Code for partB goes here.
//Continues on with partA but with few changes
/* The number of multiplication problems should not be fixed. Instead,
the program should keep posing new multiplication problems until the user decides to quit by entering the letter "q".
The program should be able to deal with invalid input by the user.
It should ignore such input and restate the current multiplication problem.
*/
//Uses the imported Random function.
Random num = new Random();
//Initialises the minimum and maximum numbers.
int minNumber = 10; //Minimum number to start random
int maxNumber = 20; //Maximum number to start random
int counter = 0; //Counts the number of questions answered.
int correctAnswers = 0; //Counts the number of correct answers given.
final int numberOfQuestions = 0;
while(numberOfQuestions >= 0) {
//Generates a random integer between 10 and 20.
int randInt1 = (num.nextInt(maxNumber - minNumber) + minNumber);
//Repeats for the 2nd integer to get the product of the two numbers.
int randInt2 = (num.nextInt(maxNumber - minNumber) + minNumber);
//Initialise the Scanner function.
Scanner input = new Scanner(System.in);
//Output the Question.
System.out.println("What is " + randInt1 + " X " + randInt2 + "?" + " " + "(Press 'q' and ENTER to quit)");
//Waits for user input.
try {
int userInput = input.nextInt();
String quit = input.nextLine();
//If user input is 'q', quit program.
if(quit.equalsIgnoreCase("q")) {
System.out.println("Exiting...");
System.exit(0);
} else {
int answer = randInt1 * randInt2;
//Checks if the users input is correct.
if (answer == userInput) {
System.out.println("That is correct!");
correctAnswers++;
}
else {
System.out.println("That is incorrect! " + "The correct answer should be " + answer);
counter++;
}
}
} catch(InputMismatchException e) {
System.out.println("You have entered something other than an integer or 'q'! Please try again with a different question!");
}
}
}
If you want to accept both a number and a letter, it is better to use nextLine(). First you check for q, and then parse to number, as follows (note that parseInt will throw a NumberFormatException):
try {
String userInput = input.nextLine();
// If user input is 'q', quit program.
if (userInput.equalsIgnoreCase("q")) {
System.out.println("Exiting...");
System.exit(0);
} else {
int userAnswer = Integer.parseInt(userInput);
int answer = randInt1 * randInt2;
// Checks if the users input is correct.
if (answer == userAnswer) {
System.out.println("That is correct!");
correctAnswers++;
} else {
System.out.println("That is incorrect! " + "The correct answer should be " + answer);
counter++;
}
}
} catch (NumberFormatException e) {
System.out.println(
"You have entered something other than an integer or 'q'! Please try again with a different question!");
}
**Thanks Adi219 & Charles Spencer for helping with my part 1.
Now i'm trying a different approach, by validating the input before it store into an array, it look fine most of the time, but the exception only run once.
This is what i input to test the validating
1) I input "a", it returned "enter number between 0 to 100" which is correct.
2) I input 1000, and it returned "Invalid age" which i can tell that my IF conditions works.
3) No issue when i input the correct value for User no.1
Problem happens when i try to run the same test on User no.2. After I input correct value for User no.1, I type in "A" again and the programs just bypass all those conditions and captured no integer value.
import java.util.Scanner;
public class test2
{
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int i = 0;
double x = 0;
double Total = 0;
double Average = 0;
int Users = 2; //I fixed a number for testing purpose
boolean isNumber =false;
double ages[] = new double[Users];
for(int counter =0; counter < Users; counter++){
System.out.print("Enter the age for users "+(counter+1)+ ": ");
do{
try {
x =input.nextDouble();
if(x<0 || x>100){
System.out.print("Invalid age.. try again.. ");
}else if(x>0 || x<100){isNumber=true;}
}catch(Exception e){
System.out.print("Please enter number between 0 to 100 ");
input.next();
}
}while(!(isNumber));
System.out.println("User Age is "+ x); //Just to check input user's age
}
}
}
Because your entire do/while loop is based on whether isNumber is false, if you enter a valid number for user1, the isNumber variable is set to true, and the do/while loop will never run again because you never set isNumber back to false. There are two places were I set isNumber back to false, I've marked them. But I'm pretty sure this whole thing should be rewritten. For example there's no need to do:
else if(x > 0 || x < 100)
because you've already done:
if(x<0 || x>100)
If you do the first condition as x <= 0 || x >= 100 there's no need to do an else if statement.
for(int counter = 0; counter < Users; counter++)
{
System.out.print("Enter the age for users "+(counter+1)+ ": ");
do{
try {
x = input.nextDouble();
if(x<0 || x>100)
{
isNumber = false; // Set to false if invalid number
System.out.print("Invalid age.. try again.. ");
}
else if(x > 0 || x < 100)
{isNumber = true;} // If the age for user1 is valid, isNumber is set
// to true
}catch(Exception e)
{
isNumber = false; // Set to false if number invalid
System.out.print("Please enter number between 0 to 100 ");
input.next();
}
}while(!(isNumber));