I wrote a small code :
System.out.println("Please enter a number");
int number = scan.nextInt();
if(number == 1) {
System.out.println("Number is 1");
} else if(number == 2) {
System.out.println("Number is 2");
} else {
System.out.println("Invalid selection");
}
When the user enters a number different than 1 and 2, user gets "Invalid selection" message and then code terminates. I don't want it to terminate, I want it to run again until user writes 1 or 2. I tried do-while loop but it become an infinite loop. What are your suggestions?
You can use while loop here
Scanner scanner = new Scanner(System.in);
boolean status = true;
while (status) { // this runs if status is true
System.out.println("Please enter a number");
int number = scanner.nextInt();
if (number == 1) {
System.out.println("Number is 1");
status=false; // when your condition match stop the loop
} else if (number == 2) {
System.out.println("Number is 2");
status=false;// when your condition match stop the loop
} else{
System.out.println("Invalid selection");
}
}
Try this...
int number;
do{
System.out.println("Please enter a number");
number = scan.nextInt();
if(number == 1)
{
System.out.println("Number is 1") ;
}
else if(number == 2)
{
System.out.println("Number is 2") ;
}
else
{
System.out.println("Invalid selection") ;
}
}while(number!=1 && number!=2);
I recommend you check if there is an int with Scanner.hasNextInt() before you call Scanner.nextInt(). And, that makes a nice loop test condition if you use it in a while loop.
Scanner scan = new Scanner(System.in);
System.out.println("Please enter a number");
while (scan.hasNextInt()) {
int number = scan.nextInt();
if (number == 1) {
System.out.println("Number is 1");
break;
} else if (number == 2) {
System.out.println("Number is 2");
break;
} else {
System.out.println("Invalid selection");
}
}
// ...
#Dosher, reposting #Raj_89's answer with correction in while loop condition. Please notice While loop condition
int number = 0;
do{
System.out.println("Please enter a number");
Scanner scan = new Scanner(System.in);
number = scan.nextInt();
if(number == 1)
{
System.out.println("Number is 1") ;
}
else if(number == 2)
{
System.out.println("Number is 2") ;
}
else
{
System.out.println("Invalid selection") ;
}
}while(number==1 || number==2);
Related
We were given a task by my teacher that will ask user for an input of an integer 1 to 50, I've nearly completed my code but the only thing missing is a catch on informing the user if they input more than 50. Can you help me what is the missing in my code. I've read my handouts there is no such thing as an Exception that limiting a certain amount of integer or whatsoever.
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int answer = 28;
int attempts = 0;
boolean condition = false;
System.out.println("Guess a Number 1 - 50:");
do {
condition = true;
try {
int input = scan.nextInt();
scan.nextLine();
if(input > answer) {
System.out.println("Too Big");
System.out.println(); //Spacing
System.out.println("Guess a Number 1 - 50:");
attempts++;
} else if (input < answer) {
System.out.println("Too Small");
System.out.println(); //Spacing
System.out.println("Guess a Number 1 - 50:");
attempts++;
} else {
int totalA = attempts + 1;
System.out.println(); //Spacing
System.out.println("Congratulations! "+ "You attempted " + totalA + " times." );
}
} catch (InputMismatchException e) {
System.out.println("Numbers only");
System.out.println(); //Spacing
System.out.println("Guess a Number 1 - 50:");
condition = true;
scan.nextLine();
}
} while(condition);
}
I think it is very important that you know that you can create your own Exception classes that have their specific messages and uses.
For example:
public class NumberTooHighException extends Exception {
public NumberTooHighException() {
super("The number inputted is wayyyy to high...");
}
}
And then you can use your Exception as any other:
if(input > 50)
{
throw new NumberTooHighException(); // Here you throw it...
}
And if you wanna catch it, you wrap your code in a try-catch block. More on that here.
But as the comments hint:
An exception is a way of having a method tell the caller of that
method that something went wrong
So try to avoid using them for specific use cases (as this one for example). Even though yours is homework/schoolwork.
So in order to throw an exception from your code, you need to do this ...
if(input > answer) {
...
throw new IllegalArgumentException("Argument is too big");
...
} else if (input < answer) {
...
throw new IllegalArgumentException("Argument is too small");
...
} else {
...
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int answer = 28;
int attempts = 0;
int maxNumber = 50;
boolean condition = false;
System.out.println("Guess a Number 1 - 50:");
do {
condition = true;
try {
int input = scan.nextInt();
scan.nextLine();
if (input > maxNumber){
throw new InputMismatchException();
}else if(input > answer) {
System.out.println("Too Big");
System.out.println(); //Spacing
System.out.println("Guess a Number 1 - 50:");
attempts++;
} else if (input < answer) {
System.out.println("Too Small");
System.out.println(); //Spacing
System.out.println("Guess a Number 1 - 50:");
attempts++;
} else {
int totalA = attempts + 1;
System.out.println(); //Spacing
System.out.println("Congratulations! "+ "You attempted " + totalA + " times." );
}
} catch (InputMismatchException e) {
System.out.println("Numbers only");
System.out.println(); //Spacing
System.out.println("Guess a Number 1 - 50:");
condition = true;
scan.nextLine();
}
} while(condition);
}
I have written the code below. I have run the program and it allows the user to guess the correct number and return the message successfully. However, I couldn't get it to regenerate a new random number? I also couldn't include an option to ask whether the user wants to quit or not. Please help. Thank you.
import java.util.*;
class CompterAge {
public static void main (String[] args) {
Scanner sc = new Scanner(System.in);
boolean correctGuess = false;
Random r = new Random();
int randNum = r.nextInt(100-1+1) + 1;
while (!correctGuess) {
System.out.println("Guess the computer's age: ");
int guess = sc.nextInt();
if ((guess > 0) && (guess <= 100)) {
if (guess > randNum) {
System.out.println("Your guess is bigger than the number. You should go lower.");
correctGuess = false;
} else if (guess < randNum) {
System.out.println("Your guess is smaller than the number. You should go higher.");
correctGuess = false;
} else {
System.out.println("Congratulations. You got the number! The number is " + randNum);
System.out.println("Do you wish to continue the game? Yes/No");
String input = sc.next();
if (input == "Yes") {
correctGuess = false;
} else {
break;
}
}
} else {
System.out.println("Please enter a number between 1 to 100.");
correctGuess = false;
}
}
}
}
This code works, I have added another flag variable and corrected some logical errors. See the comments.
boolean correctGuess = false;
boolean endGame = false;
Random r = new Random();
while (!endGame){
int randNum = r.nextInt(101); //Why did you have (100-1+1) + 1 ?? Simple (101) was enough
correctGuess = false;
while (!correctGuess) {
System.out.println("Guess the computer's age: ");
int guess = sc.nextInt();
if ((guess > 0) && (guess <= 100)) {
if (guess > randNum) {
System.out.println("Your guess is bigger than the number. You should go lower.");
correctGuess = false;
} else if (guess < randNum) {
System.out.println("Your guess is smaller than the number. You should go higher.");
correctGuess = false;
} else {
correctGuess = true; //Will exit the Inner Loop
System.out.println("Congratulations. You got the number! The number is " + randNum);
System.out.println("Do you wish to continue the game? Yes/No");
String input = sc.next().toLowerCase();
if (input.equals("yes")) { //You can not use == for String Comparisons
endGame = false;
} else {
endGame = true;
}
}
} else {
System.out.println("Please enter a number between 1 to 100.");
correctGuess = false;
}
}
}
Your random number generation is done outside of your while loop so when they input that they want to continue the game it should then generate a new number:
System.out.println("Congratulations. You got the number! The number is " + randNum);
System.out.println("Do you wish to continue the game? Yes/No");
String input = sc.next();
if (input.equals("Yes")) {
randNum = r.nextInt(100-1+1) + 1;
correctGuess = false;
} else {
break;
}
I'm working on this simple task called "Guess my number" and Im trying to implement my code so when user guesses the right number the application displays "Congratulations " and allow the user to choose whether to play again or not. I think a do while loop will do it, but Im still not sure how to implement that. Any ideas?. Thank you in advanced!
Here's my code that runs just fine.
Random random = new Random();
while (true)
{
int randomNumber = random.Next(1, 5);
int counter = 1;
while (true)
{
Console.Write("Guess a number between 1 and 5");
int input = Convert.ToInt32(Console.ReadLine());
if (input < randomNumber)
{
Console.WriteLine("Too low, try again.");
++counter;
continue;
}
else if (input > randomNumber)
{
Console.WriteLine("Too high, try again.");
++counter;
continue;
}
else
{
Console.WriteLine("Congratulations. You guessed the number!");
break;
}
}
}
You can add a boolean flag to set inside your outermost loop to break if the user says "No":
Random random = new Random();
while (true)
{
int randomNumber = random.Next(1, 5);
int counter = 1;
bool retry = true;
while (true)
{
Console.Write("Guess a number between 1 and 5");
int input = Convert.ToInt32(Console.ReadLine());
if (input < randomNumber)
{
Console.WriteLine("Too low, try again.");
++counter;
continue;
}
else if (input > randomNumber)
{
Console.WriteLine("Too high, try again.");
++counter;
continue;
}
else
{
Console.WriteLine("Congratulations. You guessed the number!");
Console.WriteLine("Would you like to retry? y/n");
string answer = Console.ReadLine();
if (answer != "y")
{
retry = false;
}
break;
}
}
if (!retry) break;
}
and for the do-while version:
bool retry = true;
Random random = new Random();
do
{
int randomNumber = random.Next(1, 5);
int counter = 1;
while (true)
{
Console.Write("Guess a number between 1 and 5");
int input = Convert.ToInt32(Console.ReadLine());
if (input < randomNumber)
{
Console.WriteLine("Too low, try again.");
++counter;
continue;
}
else if (input > randomNumber)
{
Console.WriteLine("Too high, try again.");
++counter;
continue;
}
else
{
Console.WriteLine("Congratulations. You guessed the number!");
Console.WriteLine("Would you like to retry? y/n");
string answer = Console.ReadLine();
if (answer != "y")
{
retry = false;
}
break;
}
}
} while (retry);
Implementing a do.. while loop in your code is easy no much difference
Random random = new Random();
do
{
int randomNumber = random.Next(1, 5);
int counter = 1;
do
{
Console.Write("Guess a number between 1 and 5");
int input = Convert.ToInt32(Console.ReadLine());
if (input < randomNumber)
{
Console.WriteLine("Too low, try again.");
++counter;
continue;
}
else if (input > randomNumber)
{
Console.WriteLine("Too high, try again.");
++counter;
continue;
}
else
{
Console.WriteLine("Congratulations. You guessed the number!");
break;
}
}while (true);
}while (true);
Hope that helps...
The program is a standard flight database using OOP. In this main method there are 5 options that execute different tasks. Options 1 and 2 work without a problem, but for some reason options 3-5 don't execute. The code inside the if/else if's of options 3-5 do not run, and the program just outputs the main menu again.
boolean exit = false;
while (exit == false)
{
System.out.println("Now what would you like to do?");
System.out.println("1. Print out a flight's info");
System.out.println("2. Print out the number of flights through the static variable");
System.out.println("3. Change the departure time of a flight");
System.out.println("4. Change the departure gate of a flight");
System.out.println("5. Exit");
int choice = sc.nextInt();
if (choice == 1)
{
System.out.println("Which flight would you like to print (1 or 2)?");
int choice2 = sc.nextInt();
if (choice2 == 1)
{
f1.printFlight();
}
else if (choice2 == 2)
{
f2.printFlight();
}
else
{
System.out.println("Invalid choice");
}
}
else if (choice == 2)
{
System.out.println("This is the number of flights: ");
int numFlights = f1.getNumFlights();
System.out.println(numFlights);
}
else if (choice == 3)
{
System.out.println("Which flight would you like to change the departure time of (1 or 2)?");
int choice3 = sc.nextInt();
System.out.println(choice3);
if (choice3 == 1)
{
System.out.println("What is the new departure time for flight " + choice3);
int newTime = sc.nextInt();
f1.changeDeptTime(newTime);
}
else if (choice3 == 2)
{
f2.changeDeptTime();
}
else
{
System.out.println("Invalid choice");
}
}
else if (choice == 4)
{
System.out.println("Which flight would you like to change the departure gate of (1 or 2)?");
int choice4 = sc.nextInt();
if (choice4 == 1)
{
f1.changeDeptGate();
}
else if (choice4 == 2)
{
f2.changeDeptGate();
}
else
{
System.out.println("Invalid choice");
}
}
else if (choice == 5)
{
System.out.println("Exit Reached");
exit = true;
}
}
Use switch() statement for the choices for each case. Like
switch(x) {
case 1:
doSomething1();
case 2:
doSomething2();
case 3:
doSomething3();
}
I have the following method
public static int modeChooser(){
int choice = 0;
Scanner kb = new Scanner(System.in);
while(choice == 0){
try {
choice = kb.nextInt();
} catch (Exception e) {
continue;
}
if(choice < 1 || choice > 5){
continue;
}
}
return choice;
}
The goal is to only allow the user to put in 1,2,3,4, or 5;
If the user types a string or a too high/low number, the method should just restart until i have the proper int.
Here is an example for the flow:
User types: 1 -> all ok
User types: saddj -> method restarts -> user types 3 --> all ok
Any ideas?
Change to:
do {
// read choice value
if (choice < 1 || choice > 5) {
// hint to user
}
} while(choice < 1 || choice > 5);
I think you can simply put your check in the while condition itself as below:
while(choice < 1 || choice > 5){
try {
choice = kb.nextInt();
} catch (Exception e) {
//ignore the exception and continue
}
}
This way actually works fine:
public static int modeChooser(){
int choice = 0;
Scanner kb = new Scanner(System.in);
while(choice == 0){
try {
choice = kb.nextInt();
} catch (Exception e) {
System.out.println("Sorry but you have to enter 1,2,3,4, or 5! Please try again.");
choice = modeChooser();
}
}
if(choice < 1 || choice > 5){
System.out.println("Sorry but you have to enter 1,2,3,4, or 5! Please try again.");
choice = modeChooser();
}
return choice;
}
if(choice >= 1 && choice <= 5)
break;
else
choice = 0;
If kb.NextInt() fails the data in the input stream remains, you need to skip past it. If you don't skip the invalid data the loop will continuously try, and fail, to read the invalid input resulting in an infinite loop.
You can use kb.next() to skip over the invalid input:
while (true)
{
try
{
choice = kb.nextInt();
if(choice >= 1 && choice <= 5) break;
}
catch (InputMismatchException e)
{
e.printStackTrace();
kb.next();
}
}
I think it's better to use the Scanner.nextLine() and Integer.parseInt() methods:
while(choice < 1 || choice > 5){
try {
choice = Integer.parseInt(kb.nextLine());
} catch (Exception e) {
//...print error msg
}
}
You could include your condition on choice directly in the while condition:
while(choice < 1 || choice > 5){
try {
choice = kb.nextInt();
} catch (Exception e) {
continue;
}
}
(In your current code, is the user enters 7, choice takes that value, the while condition becomes false and your method returns 7, which it should not).
And instead of catching an exception, you could use the hasNextInt() method to make the code cleaner:
public static int modeChooser() {
int choice = 0;
Scanner kb = new Scanner(System.in);
while (choice < 1 || choice > 5) {
if (!kb.hasNextInt()) {
kb.next();
} else {
choice = kb.nextInt();
}
}
return choice;
}
If you do want to use a recursive method, it could look like:
public static int modeChooser() {
Scanner kb = new Scanner(System.in);
while (!kb.hasNextInt()) {
kb.next();
}
int choice = kb.nextInt();
return (choice >= 1 && choice <= 5) ? choice : modeChooser();
}