Im constructing a program in which the user inputs a height between 3 and 10 and a triforce from zelda is printed in java. At the current moment, whenever the user inputs numbers outside that range an exception is thrown, however I want the program to throw an exception whenever any string is inputted. Im not sure how to utilise the InputMismatchException. This is my code so far:
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int height;
try {
System.out.print("Enter height: ");
height = keyboard.nextInt();
}
catch (InputMismatchException e) {
System.out.println("");
System.out.println("Invalid height.");
}
if (height < 3 || height > 10) {
System.out.println("Invalid height.");
System.exit(0);
}
try {
System.out.print("Enter height: ");
height = keyboard.nextInt();
if (height < 3 || height > 10) {
System.out.println("Invalid height.");
System.exit(0);
}
// print triforce from zelda
// ...
} catch (InputMismatchException e) {
System.out.println("please input a int");
}
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've been sitting here (embarrassingly) for hours trying to get a do-while loop to to accept user input until it's valid, but I seem to be messing up when it comes to the boolean that I'm using to try and exit the loop. Whenever I can get the program to partially work the catch exception just ends up repeating itself infinitely.
Scanner scnr = new Scanner(System.in);
double wallHeight = 0.0;
boolean valid = false;
// Implement a do-while loop to ensure input is valid
// Prompt user to input wall's height
do {
try {
System.out.println("Enter wall height (feet): ");
wallHeight = scnr.nextDouble();
valid = false;
if (wallHeight <=0) {
throw new Exception ("Invalid Input");
}
}
catch (Exception e) {
System.out.println("Invalid Input");
}
} while (!valid);
Start by assuming the input is valid (and set valid to true on every iteration of the loop). Only set valid to false when you encounter an exception (hopefully the one you raised).
do {
valid = true;
try {
System.out.println("Enter wall height (feet): ");
wallHeight = scnr.nextDouble();
if (wallHeight <= 0) {
throw new Exception("Invalid Input");
}
} catch (Exception e) {
valid = false;
System.out.println("Invalid Input");
}
} while (!valid);
Note that you do not appear to need an exception here, as
do {
valid = true;
System.out.println("Enter wall height (feet): ");
wallHeight = scnr.nextDouble();
if (wallHeight <= 0) {
System.out.println("Invalid Input");
valid = false;
}
} while (!valid);
would also work. Of course, that assumes the user only inputs valid double(s). If you need handle arbitrary input, you should check that there is a double before you attempt to consume it (and you must consume anything that isn't a double or you have an infinite loop). Like,
do {
valid = true;
System.out.println("Enter wall height (feet): ");
if (scnr.hasNextDouble()) {
wallHeight = scnr.nextDouble();
if (wallHeight <= 0) {
System.out.println("Invalid Input");
valid = false;
}
} else {
System.out.println("Invalid Input " + scnr.nextLine());
valid = false;
}
} while (!valid);
Here is another take.I just moved the code that sets valid = true after the if check. It can make it that far only when its valid. Otherwise valid will be false and it will loop.
public class BasicDoWhile {
public static void main(String[] args) {
double wallHeight = 0.0;
boolean valid = false;
Scanner scnr = new Scanner(System.in);
// Implement a do-while loop to ensure input is valid
// Prompt user to input wall's height
do {
try {
System.out.println("Enter wall height (feet): ");
wallHeight = scnr.nextDouble();
if (wallHeight <= 0) {
throw new Exception("Invalid Input");
}
valid = true;
}
catch (Exception e) {
System.out.println("Invalid Input");
}
} while (!valid);
}
}
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
I am trying a program on exception handling to calculate height in centimeters.
import java.util.*;
class Ex{
private static double height(int feet, int inches) throws Exception{
if(feet < 0 || inches < 0)
throw new Exception("Please enter positive values only.");
return (feet * 30.48) + (inches * 2.54);
}
public static void main(String args[]){
Scanner scanner=new Scanner(System.in);
boolean continueLoop = true;
do{
try
{
System.out.println("Enter height in feet:");
int feet=scanner.nextInt();
System.out.println("and in inches:");
int inches = scanner.nextInt();
double result = height(feet,inches);
System.out.println("Result:"+result+" cm");
continueLoop = false;
}
catch(InputMismatchException e){
System.out.println("You must enter integers. Please try again.");
}
catch(Exception e){
System.out.println(e.getMessage());
}
}while(continueLoop);
}
}
When an InputMismatchException occurs, the program enters into an infinite loop. What is the fault in my logic here? What change(s) should I do?
You should add scanner.nextLine() to your catch blocks, in order to consume the rest of the current line, so that nextInt can attempt to read new input from the next line.
do{
try
{
System.out.println("Enter height in feet:");
int feet=scanner.nextInt();
System.out.println("and in inches:");
int inches = scanner.nextInt();
double result = height(feet,inches);
System.out.println("Result:"+result+" cm");
continueLoop = false;
}
catch(InputMismatchException e){
System.out.println("You must enter integers. Please try again.");
scanner.nextLine();
}
catch(Exception e){
System.out.println(e.getMessage());
scanner.nextLine();
}
}while(continueLoop);
so what I am trying to do is have the user input a valid coordinate in a matrix, that is an INT which is greater than -1,
Scanner scanner = new Scanner (System.in);
int coordinates[] = new int[2];
coordinates[0]=-1;
coordinates[1]=-1;
boolean check = true;
while (((coordinates[0]<0)||(coordinates[0]>R)) && check) {
System.out.print("Please enter a valid row number:\t");
try {
coordinates[0]=scanner.nextInt();
break;
}
catch (InputMismatchException e) {
}
}
while (((coordinates[1]<0)||(coordinates[1]>C)) && check) {
System.out.print("Please enter a valid col number:\t");
try {
coordinates[1]=scanner.nextInt();
break;
}
catch (InputMismatchException e) {
}
}
the problem is that it loops endlessly after entering a not valid input
int R is the size of the row
int C is the size of the collumn
Your problem is that you're not handling the error you're catching.
If you'll provide wrong format of number for the nextInt() method, then the InputMismatchException will be thrown. Then because the catch does nothing, the loop will continue (start from begining) and the scanner will read the same incorrect value, and so on...
So instead of this:
catch (InputMismatchException e) {
}
Try this:
catch (InputMismatchException e) {
System.out.println("Wrong number entered.");
scanner.nextLine();
}
This way you'll force scanner to move past the last incorrect input.
EDIT:
You're loop is also broken because you do break after reading the input. In that case if you'll put the negative number you'll break as well and won't check the loop condition. Remove the break statement and it will work as expected:
while (((coordinates[0]<0)||(coordinates[0]>R)) && check) {
System.out.print("Please enter a valid row number:\t");
try {
coordinates[0]=scanner.nextInt();
}
catch (InputMismatchException e) {
System.out.println("That's not a valid number.");
scanner.nextLine();
}
}
EDIT2:
public static void main(final String args[])
{
int maxRowsNumber = 10;
int maxColsNumber = 10;
Scanner scanner = new Scanner (System.in);
int coordinates[] = new int[2];
coordinates[0]=-1;
coordinates[1]=-1;
boolean check = true;
while (((coordinates[0]<0)||(coordinates[0]>maxRowsNumber)) && check) {
System.out.print("Please enter a valid row number:\t");
try {
coordinates[0]=scanner.nextInt();
}
catch (InputMismatchException e) {
System.out.println("That's not a valid number.");
scanner.nextLine();
}
}
while (((coordinates[1]<0)||(coordinates[1]>maxColsNumber)) && check) {
System.out.print("Please enter a valid col number:\t");
try {
coordinates[1]=scanner.nextInt();
}
catch (InputMismatchException e) {
System.out.println("That's not a valid number.");
scanner.nextLine();
}
}
System.out.println("Inserted RowsNumber: " + coordinates[0]);
System.out.println("Inserted RowsNumber: " + coordinates[1]);
}
Output:
Please enter a valid row number: 11
Please enter a valid row number: 22
Please enter a valid row number: 10
Please enter a valid col number: 11
Please enter a valid col number: 2
Inserted RowsNumber: 10
Inserted RowsNumber: 2
If by "not valid input" you mean "not any kind of integer", then your scanner will fail each time it tries to read another integer, so you'll hit your catch, and do nothing to stop the loop. Maybe you intended to set check to false in such circumstances? Or maybe you meant to put the break in each catch?
Using a break when a valid integer is read isn't right, because it might be a negative integer, which your loop guard says you don't want.
This is basically the same as what your doing, I just tried to improve it a little bit by removing hardcoded values, made variables more descriptive, and included input validations.
final int ROW = 0;
final int COL = 1;
int coordinates[] = new int[2];
coordinates[ROW] = -1;
coordinates[COL] = -1;
boolean isInputValid = true;
Scanner scanner = new Scanner(System.in);
do {
try {
System.out.print("Please enter a valid row number:\t");
coordinates[ROW] = Integer.parseInt(scanner.nextLine());
} catch (NumberFormatException nfe) {
isInputValid = false; //if the input is not int
}
} while (!isInputValid && (coordinates[ROW] < 0) //do this until the input is an int
|| (coordinates[ROW] > R)); //and it's also not less than 0 or greater than R
//same logic applies here
do {
try {
System.out.print("Please enter a valid col number:\t");
coordinates[COL] = Integer.parseInt(scanner.nextLine());
} catch (NumberFormatException nfe) {
isInputValid = false;
}
} while (!isInputValid && (coordinates[COL] < 0)
|| (coordinates[COL] > C));
Hope this helps.