When I run this, the code skips over input.nextInt(); and goes in circles:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
// Link user to programs (ToC)
int loop = 1;
do {
try {
System.out.println("Please choose a number: ");
System.out.println("0. Exit");
System.out.println("1. Calculator");
int numChoice = input.nextInt();
if (numChoice == 0) {
System.exit(0);
} else if (numChoice == 1) {
System.out.println("Going to Calculator...");
new Calculator();
} else {
System.out.println("Not a valid choice.");
}
}
catch (Exception e) {
System.out.println("Please input a number!");
}
} while (loop == 1);
}
It seems to be skipping int numChoice for whatever reason. Also, please don't be too technical. I just code for my leisure.
Your loop goes in circles for two reasons:
You try for nextInt, but you do not clear out the input buffer on failure, and
Even if you did clear input in the catch, your loop would still go on, because there are no assignments of the loop variable which is supposed to stop your loop.
Related
package react;
import java.util.Scanner;
public class Intputfromuser {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("enter a number to compare with number 5 ");
Scanner input= new Scanner(System.in);
int a=input.nextInt();
if(a==2)
{
System.out.println("U Have Entered The same value");
}
else if(a<2)
{
System.out.println("Ur number is Smaller than 2");
}
else if(a>2)
{
System.out.println("U Have Entered the number Greater than ");
}
else {
System.out.println("U Have Enterer Invalid Input");
}
}
}
how to get only integer from the user if the user enters any thing except integer then else statement should run
Another alternative. Be sure to read the comments in code:
public static void main(String[] args) {
/* Open a keyboard input stream. There is no need to close
this stream. The JVM will do that automatically when the
application closes. */
Scanner input = new Scanner(System.in);
String val = ""; // Used to store User input:
// User Prompt with 'quit' capability and entry validation:
while (val.isEmpty()) {
System.out.print("Enter a number to compare with number 5 (q to quit): -> ");
val = input.nextLine().trim(); // Trim in case just a whitespace(s) was entered.
// Was 'q' for quit supplied?
if (val.equalsIgnoreCase("q")) {
/* Yes...then quit. Returning out of main() effectively
closes this particular application: */
System.out.println("Quiting - Bye Bye");
return;
}
// Validate Entry:
/* Is entry a string representation of a signed or unsigned Integer
value and does the supplied value fall within the relm of an int? */
if (!val.matches("-?\\d+") || (Long.parseLong(val) < Integer.MIN_VALUE) ||
(Long.parseLong(val) > Integer.MAX_VALUE)) {
// No...Inform User and allow to try again:
System.out.println("Invalid Numerical Entry! {" + val + ") Try again..."
+ System.lineSeparator());
val = ""; // Empty variable to ensure re-loop:
}
}
// If you make it to this point in code, the User input was valid!
// Now parse the String numerical value to an int:
int a = Integer.parseInt(val);
/* At this point, there are only three usable conditions:
Equal To, Less Than, and Greater Than (validity has
already been handled within the `while` loop: */
// Equal To:
if (a == 5) {
System.out.println("You have entered The same value.");
}
// Less Than:
else if (a < 5) {
System.out.println("Your number is smaller than 5.");
}
// Greater Than:
else {
System.out.println("You have entered a number greater than 5.");
}
// DONE
}
You can also create method to collect input and make it inside loop like this:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
System.out.print("enter a number to compare with number 5: ");
int userInput = getInteger();
if (userInput == 2)
{
System.out.println("U Have Entered The same value");
}
else if (userInput < 2)
{
System.out.println("Ur number is Smaller than 2");
}
else {
System.out.println("U Have Entered the number Greater than 2");
}
}
static int getInteger() {
boolean correct = false;
Scanner input = new Scanner(System.in);
int userInput = 0;
do {
try {
userInput = input.nextInt();
correct = true;
} catch (Exception e) {
System.out.println("Incorrect input");
System.out.println("Please try again: ");
} finally {
input.nextLine();
}
}
while (!correct);
input.close();
return userInput;
}
}
Important note with scanner.nextInt() or scanner.nextDouble()
you need to call scanner.nextLine() after that to clear input. Otherwise you will end up with endless loop.
Use input.nextLine() instead and parse it to a String.
To avoid a ParseException, surround it by using a try { ... } catch() { ... } block.
In the catch block you can e.g. print a message informing the user of the wrong input.
public static void main(String[] args) {
System.out.println("enter a number to compare with number 5 ");
Scanner s = new Scanner(System.in);
String userInput = s.nextLine();
try {
int option = Integer.parseInt(userInput);
if (option == 2)
{
System.out.println("U Have Entered The same value");
}
else if (option < 2)
{
System.out.println("Ur number is Smaller than 2");
}
else if (option > 2)
{
System.out.println("U Have Entered the number Greater than 2");
}
} catch (NumberFormatException e) {
System.out.println("Invalid input!");
}
}
Hope this sort of helped!
I'm having some trouble with a menu program I am writing for my java class. After one program is run, when the program goes to do a second loop it throws a NoSuchElementException on the line where it is supposed to take the user's input for the next program they want to run. I'm assuming it has something to do with the scanner getting messed up but I can't find the issue. Anyone have any ideas?
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
String pin;
int selection = 0;
boolean valid = false;
do {
System.out.print("Please enter the password: ");
pin = console.nextLine();
valid = checkPassword(pin);
} while (!valid);
while (selection != 4 && valid == true) {
System.out.printf("%nPlease select a number from the menu below %n1: Wage "
+ "Calculator 2: Tip Calculator 3: Grocery Discount 4: Exit %n");
selection = console.nextInt();
if (selection == 1) {
calc_wages();
} else if (selection == 2) {
calc_tip();
} else if (selection == 3) {
System.out.print("We haven't gotten this far yet");
} else if (selection == 4){
System.out.print("Thank you for using the program.");
break;
} else {
System.out.print("There is no option for what you entered. Try again");
}
selection = 0;
}
}//main
Your code so far is fine.
From what you're saying the problem starts after the user makes a selection.
In calc_wages() and/or calc_tip() it's possible that you use another Scanner object to get the user's input.
This is a source of problems.
Declare 1 Scanner object at the class level and use it throughout you code and close it only when it is no longer needed.
new to programming.
I have a class in java and i'm trying to write this program but it's printing none-stop and it's even bugging my browser! (Im using an online ide)
my instructions:
Q: how much do you love me?
Below 10 : wrong answer
equal to 10 and more = good answer
I know how to do it but I dont want the program to stop every time i write an answer. I want the program to keep running until i have a 10 +. So i can always input until it's 10+ out of 10.
this is my lines :
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner (System.in);
System.out.println ("how much do you love me out of 10");
int num1 = input.nextInt();
while (true)
if (num1 <= 9) {
System.out.println("Wrong answer");
}
else {
System.out.println ("Good answer");
}
}
}
This should work:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner (System.in);
System.out.println ("Out of 10, how much do you love me?");
int input = 0
while (input <= 9) {
input = scanner.nextInt();
if (input <= 9) {
System.out.println("Wrong answer");
} else {
System.out.println("Good answer");
}
}
}
}
Explanation: It loops until input is less not less than or equal to 9 (while (input <= 9)). Each time through the loop, it gets input and acts on it.
Hope this helps!
First off, you need to move the int num1 = input.nextInt(); statement inside your while loop, this will allow for a new input every time the while loop loops (iterates).
Second, if you are looking to run the program until num1 >= 10, then you could implement it in two ways.
while(num1 < 10) {
num1 = input.nextInt();
if(num1 >= 10) {
System.out.println("Good answer");
} else {
System.out.println("Wrong answer");
}
}
or using the keyword break,
while(true) {
num1 = input.nextInt();
if(num1 >= 10) {
System.out.println("Good answer");
break;
} else {
System.out.println("Wrong answer");
}
}
break simply escapes the loop it resides in when called
Hoped this helped
This is a guessing game. I want to enter user input after error message but my catch phrase keeps on printing infinitely.. please help me.
if I enter letter it will print
"Invalid Number! Try again."
"Invalid Number! Try again."
"Invalid Number! Try again."
"Invalid Number! Try again."
import java.util.*;
public class RandomGame {
public static Scanner sc = new Scanner(System.in);
public static void main(String args[]) {
Random rand = new Random();
int x = rand.nextInt(50);
int counter = 0;
int y;
boolean flag = false;
System.out.print("Give a number from 1-50:");
while(!flag) {
flag = true;
try {
y = sc.nextInt();
if (y < x) {
counter++;
System.out.println("Too low. Try again");
flag = false;
} else if (y > x) {
counter++;
System.out.println("Too high. Try again");
flag = false;
} else if (x == y) {
counter++;
System.out.println("you got it " + counter + " attempt(s):");
flag = true;
}
} catch(InputMismatchException | NumberFormatException e1) {
System.out.println("Invalid Number! Try again.");
}
flag = false;
}
System.out.println(x);
}
}
Your problem is that nextInt doesn't remove the offending character from the stream, so you keep encountering the same error over and over.
You'd be better to call next instead of nextInt, then try to parse the resulting String into an int, using Integer.parseInt. That way, if the content of the stream is non-numeric, it will actually be removed from the stream.
For this kind of things you can also use the "finally" close,
try{}
catch(Exception e){}
finally{}
finally always works (even if there wasn't any exception), even if there is any exception
and it helps the program works even if there was an error.
So I am working on a guessing number game that uses a try/catch block to catch (this is homework). If the user enters a non-integer value or a number that is below or above the given range (in this case 1-10).
But I am having issues understanding/properly placing the try catch block I read on how it works but when I try to implement it into my simple code it just seems to be ignored.
Here is the code
//import statements
import java.util.*; //for scanner class
// class beginning
class Guess {
public static void main(String[] args ) {
//Declare variables area
int secretNumber, guess;
secretNumber = (int) (Math.random() * 10 + 1);
Scanner keyboard = new Scanner(System.in);
// beginning message to user to explain the program
System.out.println("Welcome to my guess a number program!");
System.out.println("Please enter in a number to begin guess what the secret number is(1-10): ");
//Collect inputs from user or read in data here
System.out.println("Enter a guess (1-10): ");
try {
guess = keyboard.nextInt();
if (guess < 1 || guess > 10){
}
} catch (InputMismatchException e) {
guess= keyboard.nextInt();
System.out.println("Not a valid integer");
}
//Echo input values back to user here
//main code and calculations to do
do {
if (guess < 1 || guess > 10) {
System.out.println("Your guess is not in the corre try again.");
guess = keyboard.nextInt();
}
if (guess == secretNumber) {
System.out.println("Your guess is correct. Congratulations!");
guess = keyboard.nextInt();
} else if (guess < secretNumber) {
System.out
.println("Your guess is smaller than the secret number.");
guess = keyboard.nextInt();
} else if (guess > secretNumber) {
System.out
.println("Your guess is greater than the secret number.");
guess = keyboard.nextInt();
}
} while (guess != secretNumber);
//End program message
System.out.println();
System.out.println("Hope you enjoyed using this program!");
}// end main method
}// end class
It doesn't display "Your guess is correct. Congratulations!" when you guess the right number.
Am I implementing the try catch block correctly? If not how do I and can it be explained so I can do the second one where it catches the float, string and anything not a int.
what it does do
it correctly randomizes from 1-10
the program does check to see if it is within the given range
EDIT
below is the updated code my only issue I have with it now is that I can't figure out how to apply another catch if a user just hits enter without entering anything I assume I'd need to take the input from user turn it into a string then compare?
//import statements
import java.util.*; //for scanner class
// class beginning
public class Guess {
public static void main(String[] args ) {
//Declare variables area
int guess, secretNumber = (int) (Math.random() * 10 + 1), lowGuess,highGuess;
Scanner keyboard = new Scanner(System.in);
// beginning message to user to explain the program
System.out.println("Welcome to my guessing number program!");
System.out.println("Please enter in a number to start guessing(enter in a number between 1-10): ");
//main code and calculations to do
guess = 0;
lowGuess = 0;
highGuess = 11;
do {
try {
guess = keyboard.nextInt();
if (guess < 1 || guess >10){
System.out.println("Your guess is not in the correct range try again.");
}
else if(guess == secretNumber){
System.out.println("Your guess is correct. Congratulations!");
}
else if(guess < secretNumber && guess <= lowGuess){
System.out.println("The number you entered is either the same entered or lower please re-enter");
}
else if (guess < secretNumber && guess > lowGuess){
lowGuess = guess;
System.out.println("Your guess is smaller than the secret number.");
}
else if ( guess > secretNumber && guess >= highGuess ){
System.out.println("The number you entered is either the same entered or higher please re-enter");
}
else if (guess > secretNumber && guess < highGuess){
highGuess = guess;
System.out.println("Your guess is greater than the secret number.");
}
} catch (InputMismatchException e) {
System.out.println("Not a valid input please re-enter");
keyboard.next();
guess = 0;
}
} while (guess != secretNumber);
//End program message
System.out.println();
System.out.println("Hope you enjoyed using this program!");
}// end main method
}// end class
What do you want to do here ?
if (guess < 1 || guess > 10) {
}
You should try something like this :
public class Guess {
static int guess, secretNumber = (int) (Math.random() * 10 + 1);
static Scanner keyboard = new Scanner(System.in);
public static void main(String[] args ) {
do {
try {
guess = keyboard.nextInt();
if (guess < 1 || guess >10){
System.out.println("Your guess is not in the corre try again.");
}
if(guess == secretNumber){
System.out.println("Your guess is correct. Congratulations!");
}
else if (guess < secretNumber){
System.out.println("Your guess is smaller than the secret number.");
}
else if (guess > secretNumber){
System.out.println("Your guess is greater than the secret number.");
}
} catch (InputMismatchException e) {
System.out.println("Not a valid integer");
}
} while (guess != secretNumber);
}
}
EDIT : You have to put a piece of code which could maybe throw an exception, in the scope of the try block. It is state of the art to know which part of the code to put in the try block (not too much nor too less).
in-between the try and catch you have your main code/calculations to
do and then you close it off and end with the catch to see if after
all that if what was entered was valid?
You could always catch the exceptions at top level like you're saying here, but in practice that's not the way to do it. Because when an exception occurs and you don't catch it there will be a process called stack unwinding.
It's really important to understand how stack unwinding works in order to understand what's happening.
You can find information about how this process works here : Explanation of stack unwinding. It explains stack unwinding in C++ but I expect it to be (exactly) the same in Java.
This is another approach, but using Exceptions. Please, read this page to understand how try/catch block works.
//import statements
import java.util.*; //for scanner class
// class beginning
class Guess {
public static void main(String[] args ) {
//Declare variables area
int secretNumber, guess;
secretNumber = (int) (Math.random() * 10 + 1);
Scanner keyboard = new Scanner(System.in);
// beginning message to user to explain the program
System.out.println("Welcome to my guess a number program!");
System.out.println("Please enter in a number to begin guess what the secret number is(1-10): ");
//Collect inputs from user or read in data here
//main code and calculations to do
do {
System.out.println("Enter a guess (1-10): ");
try {
guess = keyboard.nextInt();
if (guess < 1 || guess > 10){
throw new Exception("Number must be between 1 and 10");
}else if(guess == secretNumber){
throw new Exception("YOU WIN");
}
else if (guess < secretNumber){
throw new Exception("NUMBER IS +");
}
else if (guess > secretNumber){
throw new Exception("NUMBER IS -");
}
} catch (InputMismatchException e)
{
System.println("mustbeanumber");
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
} while (guess != secretNumber);
//End program message
System.out.println();
System.out.println("Hope you enjoyed using this program!");
}// end main method
}// end class`