how do i repeatedly ask the user to enter an input until the user enters a negative number. If the user enters a negative number or 0, the program will end?
import java.util.Scanner;
public class OddEvenInt {
public static void main(String args[]) {
Scanner s = new Scanner(System. in );
int x;
do {
System.out.println("Enter an integer to check if it is odd or even ");
x = s.nextInt();
if (x % 2 == 0)
System.out.println("You entered an even number.");
else
System.out.println("You entered an odd number.");
} while (x % 2 == 0);
}
}
You gotta change the while clause :
while (x>0)
use < and >
public static void main(String[] arguments) {
Scanner s = new Scanner(System.in);
int x = 0;
do {
System.out.println("Enter an integer to check if it is odd or even ");
try {
x = Integer.parseInt(s.nextLine());
if (x > 0) {
System.out.println("You entered an even number.");
} else if (x == 0) {
System.out.println("You entered 0, thats not negativ or positiv.");
} else {
System.out.println("You entered an odd number.");
}
} catch (Exception e) {
//e.printStackTrace();
System.out.println("U call this an Integer? :P");
}
} while (x > 0);
return;
}
last edit: check if your input is numberic, if you want to check the error you can remove // from the catch-block
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 working on a homework problem of creating a guessing game. I've got that part working, but we have to validate the input. I've tried using hasNextInt, but I keep getting an error saying "int cannot be dereferenced" and points to the "!guess.hasNextInt" code.
I've tried many iterations, but I still get the same error. The code I'm including is just my most recent try.
How do I get hasNextInt to work or how else should I validate the input?
import java.util.Scanner;
public class GuessNumber {
public static void main(String[] args) {
int num = (int) (Math.random() * 101);
Scanner input = new Scanner(System.in);
System.out.println("Welcome to my Guessing Game!");
int guess = -1;
//Loop goes as long as guess doesn't equal num
while (guess != num) {
System.out.print("Guess a number between 1 and 100: ");
guess = input.nextInt();
//Validates input
while (!guess.hasNextInt()) {
System.out.println("Invalid response, try again.");
in.next();
}
if (guess == num)
System.out.println("Correct!");
else if (guess < num)
System.out.println("Your guess was too low");
else
System.out.println("Your guess was too high");
}
}
}
i fixed the code:
public static void main(String[] args) {
int num = (int) (Math.random() * 101);
System.out.println(num);
Scanner input = new Scanner(System.in);
System.out.println("Welcome to my Guessing Game!");
int guess = -1;
//Loop goes as long as guess doesn't equal num
while (guess != num) {
System.out.print("Guess a number between 1 and 100: ");
guess = input.nextInt();
if (guess == num) {
System.out.println("Correct!");
break;}
else if (guess < num)
System.out.println("Your guess was too low");
else
System.out.println("Your guess was too high");
//Validates input
while (!input.hasNextInt()) {
System.out.println("Invalid response, try again.");
input.next();
}
}
}
if the user guessed the number the game ends using break
in while (!guess.hasNextInt()) you were using a integer where it's expect the Scanner input
If you want to parse your number you can use Integer.parseInt() method as shown. Also you are using hasNextInt() incorrectly. You are also not storing in.next() value in any variable.
import java.util.Scanner;
public class GuessNumber {
public static void main(String[] args) {
int num = (int)(Math.random() * 101);
Scanner input = new Scanner(System.in);
System.out.println("Welcome to my Guessing Game!");
int guess = -1;
//Loop goes as long as guess doesn't equal num
while (true) {
System.out.print("Guess a number between 1 and 100: ");
String numberString = input.nextLine();
//Validates input
try {
guess = Integer.parseInt(numberString);
if (guess == num) {
System.out.println("Correct!");
break;
} else if (guess < num)
System.out.println("Your guess was too low");
else
System.out.println("Your guess was too high");
} catch (Exception e) {
System.out.println("Invalid response, try again.");
}
}
}
}
I need help coding a set of statements of data validation that checks if a user entry is within a range of 0 and 100, and anything the user types that ISNT a non-decimal integer between 1 and 100 should display an error message. Also I need a way to code how I can get a "goodbye" output to only display if the user enters "n" not "n" and "y." N meaning no and y meaning yes.
Heres my code.
import java.util.Scanner;
public class GuessingGameCalc {
private static void displayWelcomeMessage(int max) {
System.out.println("Welome to the Java Guessing Game!");
System.out.println(" ");
System.out.println("I'm thinking of a number between 1 and" + " " + max + " " + "let's see if you guess what it is!");
System.out.println(" ");
}
public static int calculateRandomValue(int max) {
double value = (int) (Math.random() * max + 1);
int number = (int) value;
number++;
return number;
}
public static void validateTheData(int count) {
if( count < 3) {
System.out.println("Good job!");
} else if (count < 7) {
System.out.println("Need more practice.");
} else{
System.out.println("Need way more practice.");
}
}
public static void main(String[] args) {
final int max = 100;
String prompt = "y";
displayWelcomeMessage(max);
int unit = calculateRandomValue(max);
Scanner sc = new Scanner(System.in);
int counter = 1;
while (prompt.equalsIgnoreCase("y")) {
while (true) {
System.out.println("Please enter a number.");
int userEntry = sc.nextInt();
if (userEntry < 1 || userEntry > max) {
System.out.println("Invalid guess! Guess again!");
continue;
}
if (userEntry < unit) {
if ( (unit - userEntry) > 10 ) {
System.out.println("Way Too low! Guess higher!");
} else {
System.out.println("Too low! Guess higher!");
}
} else if (userEntry > unit) {
if( (userEntry - unit) > 10 ){
System.out.println("Way Too high! Guess lower!");
} else {
System.out.println("Too high! Guess lower!");
}
} else {
System.out.println("Congratulations! You guessed it in" + " " + counter + " " + "tries!\n");
validateTheData(counter);
break;
}
counter++;
}
System.out.println("Would you like to try again? Yes or No?");
prompt = sc.next();
System.out.println("Goodbye!");
}
}
}
Instead of using .nextInt() rather use .nextLine(), which returns a String and then parse it to an int and catch the NumberFormatException
So basically you'll have this structure:
try {
int userEntry = Integer.parseInt(sc.nextLine());
...
} catch (NumberFormatException nfe) {
System.out.println("Please enter a valid number.");
}
Oh, just a comment on the rest of your code. You don't really need two while loops, one will be more than sufficient.
The program checks the user input and determines if it's positive or negative.
How can I catch the error when the user provides an invalid input (non-integer) such as "444h" or "ibi".
I was thinking the final else statement would catch the exception but it does not.
import java.util.Scanner;
public class Demo
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.print("Enter any number: ");
int num = scan.nextInt();
scan.close();
if(num > 0)
{
System.out.println(num+" is positive");
}
else if(num < 0)
{
System.out.println(num+" is negative");
}
else if(num == 0)
{
System.out.println(num+" is neither positive nor negative");
}
else
{
System.out.println(num+" must be an integer");
}
}
}
I expect the program to catch the exception and prompt input of a valid integer
Simply wrap your code in a try..catch block.
Full code:
import java.util.Scanner;
import java.util.InputMismatchException;
class Main {
public static void main(String[] args) {
System.out.println("Hello world!");
Scanner scan = new Scanner(System.in);
System.out.print("Enter any number: ");
try {
int num = scan.nextInt();
if (num > 0) {
System.out.println(num + " is positive");
} else if (num < 0) {
System.out.println(num + " is negative");
} else if (num == 0) {
System.out.println(num + " is neither positive nor negative");
}
} catch (InputMismatchException e) {
System.out.println("Error: Value Must be an integer");
}
scan.close();
}
}
Good luck :)
int num = 0;
try{
num =input.nextInt();
}catch(InputMismatchException ex) {
System.out.println("Enter Integer Value Only");
}
You have to write int num = scan.nextInt(); this statement inside try block if you get non-integer value from input then InputMismatchException will arise then catch block will executed.
First off, don't close the Scanner if you plan on using it again during the operation of your application. Once you close it, you will need to restart your application in order to use it again.
As already mentioned, you could utilize a try/catch on the Scanner#nextInt() method:
Scanner scan = new Scanner(System.in);
int num = 0;
boolean isValid = false;
while (!isValid) {
System.out.print("Enter any number: ");
try {
num = scan.nextInt();
isValid = true;
}
catch (InputMismatchException ex) {
System.out.println("You must supply a integer value");
isValid = false;
scan.nextLine(); // Empty buffer
}
}
if (num > 0) {
System.out.println(num + " is positive");
}
else if (num < 0) {
System.out.println(num + " is negative");
}
else if (num == 0) {
System.out.println(num + " is neither positive nor negative");
}
Or you could use the Scanner#nextLine() method instead which accepts string:
Scanner scan = new Scanner(System.in);
String strgNum = "";
boolean isValid = false;
while (!isValid) {
System.out.print("Enter any Integer value: ");
strgNum = scan.nextLine();
/* See if a signed or unsigned integer value was supplied.
RegEx is used with the String#matches() method for this.
Use this RegEx: "-?\\d+(\\.\\d+)?" if you want to allow
the User to enter a signed or unsigned Integer, Long,
float, or double values. */
if (!strgNum.matches("-?\\d+")) {
System.out.println("You must supply a numerical value (no alpha characters allowed)!");
continue;
}
isValid = true; // set to true so as to exit loop
}
int num = Integer.parseInt(strgNum); // Convert string numerical value to Integer
/* Uncomment the below line if you use the other RegEx. You would have to also
comment out the above line as well. */
// double num = Double.parseDouble(strgNum); // Convert string numerical value to double
if (num > 0) {
System.out.println(num + " is positive");
}
else if (num < 0) {
System.out.println(num + " is negative");
}
else if (num == 0) {
System.out.println(num + " is neither positive nor negative");
}
Use regex to check if input is a number
import java.util.regex.*;
Pattern.matches("[0-9]+", "123"); // this will return a boolean
This question already has answers here:
try/catch with InputMismatchException creates infinite loop [duplicate]
(7 answers)
Closed 7 years ago.
[SOLVED] By adding console.next(); to my catch statement.
catch(InputMismatchException fe) {
System.out.println("You didnt enter an integer. Try again");
restart = 'y';
console.next();
}}
while(restart=='y');
}}
[Solution]^^^^^^
static public char restart;
public static void main(String[] args) {
do {
try {
int num1, num2, check, sum = 0, count = 1, sqsum = 0;
do {
System.out.println("Please enter a number");
num1 = console.nextInt();
Here is where i have set restart as public so i can use it with the try catch in order to restart the program when a inputmissmatchexception happens
catch(InputMismatchException fe) {
System.out.println("You didnt enter an integer. Try again");
restart = 'y';
}}
while(restart=='y');
}}
and here is the catch where if it does catch the exception i set restart to y then if it is y then the do while would restart the program. But it doesn't it just asks the user to enter a number then displays my catch message "you didn't enter an integer....." I believe this means the scanner isn't searching for another value to place in the variable, but i have tried and don't know how to fix this.
FULL: This is a project for school where i have to have them enter two number and do things to them. It works and does everything its supposed to but i just would like to have the program restart if the user inputs a non integer.
package p321ex9;
import java.util.*;
public class p321ex9 {
static Scanner console = new Scanner(System.in);
static public char restart = 'n';
public static void main(String[] args) {
do {
try {
int num1, num2, check, sum = 0, count = 1, sqsum = 0;
do {
System.out.println("Please enter a number");
num1 = console.nextInt();
System.out.println("Please enter a second number that is grester than the first number you entered which "
+ "was " + num1 + ".");
num2 = console.nextInt();
if (num1 > num2) {
System.out.println("the first number was greater than your second number, please enter new numbers and "
+ "make sure the second is greater.");
}
}
while (num1 > num2);
System.out.println("List of odd numbers between the first and second numbers you entered inclusive:");
while (num1 <= num2) {
check = (num1 % 2);
if (check == 1) {
sqsum += (num1 * num1);
System.out.print(num1 + " ");
} else {
sum += num1;
}
num1++;
}
System.out.println();
System.out.println("The sum of all even numbers the first and second numbers you entered inclusive"
+ ": " + sum);
System.out.println("Sum of the squares of all the odd numbers between your two entered numbers inclusive: " + sqsum);
System.out.println("All numbers from 1 to 10 squared");
while (count <= 10) {
System.out.print(count + " squared = " + (count * count) + " ");
count++;
}
} catch (InputMismatchException fe) {
System.out.println("You didnt enter an integer. Try again");
restart = 'y';
}
}
while (restart == 'y');
}
}
because when you set restart='y', you did not reset it when user enter valid input (integer)
Better way of doing this:
public static void main (String[] args){
Scanner console=new Scanner(System.in);
int num1,num2,check,sum=0,count=1,sqsum=0;
do{
System.out.println("Please enter a number");
String input=console.nextLine();
if(input.replaceAll("\\d","").length()==0){
num=Integer.parseInt(input);
restart='n';
}
else{
System.out.println("You didnt enter an integer. Try again");
restart='y';
}
}
while (restart=='y');
}