I want to put if () condition to length, So that the user can enter numbers only, if he enters string or char, an error appears.
System.out.print("Determine the length of array> ");
int length = input.nextInt();
You can use Scanner#hasNextInt to guard against invalid input.
if(input.hasNextInt()){
int length = input.nextInt();
System.out.println(length);
} else System.out.println("Invalid input");
One of the ways you could achieve it is as below:
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
Integer val = null;
try {
val = scan.nextInt();
System.out.println(val);
// do whatever you want to do with your input value
} catch (Exception exception) {
System.out.println("you can enter integer only");
// exit program or log error message
}
}
You can use java regex,which is only looking numbers
^[0-9]*$
So let's check if this is valid,
public static void main(String[] args) {
boolean valid = false;
String regexForNumbers = "^[0-9]*$";
Scanner scanner = new Scanner(System.in);
while (!valid) {
System.out.print("Input Value:");
String s = scanner.nextLine();
if(!s.matches(regexForNumbers)){
valid= false;
System.out.println("Not only Numbers, try again\n");
}else{
valid = true;
System.out.println("Only Numbers:"+ s);
}
}
}
So what happens is if the user input contains only numbers the execution will end, otherwise, it will keep asking the user to input, and the output of this simple logic will be.
Input Value:maneesha
Not only Numbers, try again
Input Value:maneesha123
Not only Numbers, try again
Input Value:123
Only Numbers:123
Related
I need the user to enter an integer input, check whether it starts by 0 and tell the user to enter another integer if that is the case
I tried parsing the integer input to a string, that works but only once. The string cannot be edited when program loops
I think the solution should not at all involve strings because i need the program to loop and check over and over until the input is valid (ie has no leading zeroes)
Splitting each digit of the int into an array does not work also because the ways i found pass by string.
public static void main(String[] args){
Scanner key = new Scanner(System.in);
int in= 0;
boolean looper=true;
while (looper == true) {
System.out.println("Enter an integer");
in = key.nextInt();
/* check whether in has any leading zeroes, example of
wrong input: 09999, 0099*/
if (/*in has no leading zeroes*/)
looper = false;
}
key.close();
}
Maybe another answer would be to have a method that creates a brand new string every time the program loops, so maybe like a recursion that automatically creates strings, not sure if that's even a thing though.
You can make it cleaner by using a do-while loop instead of while(true). Note that an integer starting with 0 is an octal number e.g.
public class Main {
public static void main(String[] args) {
int x = 06;
System.out.println(x);
// x = 09; // Compilation error - out of range
}
}
Thus, 06 is a valid integer. For your requirement, you can input to a String variable and prompt the user to again if it starts with a zero. If the input does not start with a zero, try parsing it to an int and process it if it succeeds; otherwise, loopback e.g.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner key = new Scanner(System.in);
String input = "";
int in = 0;
boolean valid = true;
do {
System.out.print("Enter an integer: ");
input = key.nextLine();
if (input.startsWith("0")) {
System.out.println("Invalid input");
valid = false;
} else {
try {
in = Integer.parseInt(input);
System.out.println("You entered " + in);
// ... process it
valid = true;
} catch (NumberFormatException e) {
System.out.println("Invalid input");
valid = false;
}
}
} while (!valid);
}
}
A sample run:
Enter an integer: 09999
Invalid input
Enter an integer: xyz
Invalid input
Enter an integer: 123
You entered 123
As an aside, never close a Scanner(System.in) because it also closes System.in and there is no way to open it without rebooting the JVM.
I want to validate user input using the exception handling mechanism.
For example, let's say that I ask the user to enter integer input and they enter a character. In that case, I'd like to tell them that they entered the incorrect input, and in addition to that, I want them to prompt them to read in an integer again, and keep doing that until they enter an acceptable input.
I have seen some similar questions, but they do not take in the user's input again, they just print out that the input is incorrect.
Using do-while, I'd do something like this:
Scanner reader = new Scanner(System.in);
System.out.println("Please enter an integer: ");
int i = 0;
do {
i = reader.nextInt();
} while ( ((Object) i).getClass().getName() != Integer ) {
System.out.println("You did not enter an int. Please enter an integer: ");
}
System.out.println("Input of type int: " + i);
PROBLEMS:
An InputMismatchException will be raised on the 5th line, before the statement checking the while condition is reached.
I do want to learn to do input validation using the exception handling idioms.
So when the user enters a wrong input, how do I (1) tell them that their input is incorrect and (2) read in their input again (and keep doing that until they enter a correct input), using the try-catch mechanism?
EDIT: #Italhouarne
import java.util.InputMismatchException;
import java.util.Scanner;
public class WhyThisInfiniteLoop {
public static void main (String [] args) {
Scanner reader = new Scanner(System.in);
int i = 0;
System.out.println("Please enter an integer: ");
while(true){
try{
i = reader.nextInt();
break;
}catch(InputMismatchException ex){
System.out.println("You did not enter an int. Please enter an integer:");
}
}
System.out.println("Input of type int: " + i);
}
}
In Java, it is best to use try/catch for only "exceptional" circumstances. I would use the Scanner class to detect if an int or some other invalid character is entered.
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
boolean gotInt = false;
while (!gotInt) {
System.out.print("Enter int: ");
if (scan.hasNextInt()){
gotInt = true;
}
else {
scan.next(); //clear current input
System.out.println("Not an integer");
}
}
int theInt = scan.nextInt();
}
}
Here you go :
Scanner sc = new Scanner(System.in);
boolean validInput = false;
int value;
do{
System.out.println("Please enter an integer");
try{
value = Integer.parseInt(sc.nextLine());
validInput = true;
}catch(IllegalArgumentException e){
System.out.println("Invalid value");
}
}while(!validInput);
You can try the following:
Scanner reader = new Scanner(System.in);
System.out.println("Please enter an integer: ");
int i = 0;
while(true){
try{
i = reader.nextInt();
break;
}catch(InputMismatchException ex){
System.out.println("You did not enter an int. Please enter an integer:");
}
}
System.out.println("Input of type int: " + i);
Here is my code that I have so far:
import java.util.Scanner;
public class Whatever{
public static void main(String[] args) {
Scanner keyboard = new Scanner (System.in);
System.out.println("How many pigs are there?");
int number = Integer.parseInt( keyboard.nextLine() );
int continueProgram = 0
while(continueProgram == 0)
{
if (number>= 0 && number <= 32767)
{ do this;
continueProgram++;
}else{
do this;
}
I have to use integer.parseInt for the rest of my code to work so I can't change that. Any ways to take only integers rather than letters? My code produces errors because if I input a letter, parseInt will produce red errors rather than output a string like "try again. input numbers please" or something like that.
You need to surround your parse.int with a try catch like this
int number = 0; // you need to initialize your variable first
while (true) {
try {
number = Integer.parseInt(keyboard.nextLine());
break; // this will escape the while loop
} catch (Exception e) {
System.out.println("That is not a number. Try again.");
}
}
Try this one :
Scanner keyboard = new Scanner (System.in);
System.out.println("How many pigs are there?");
if(keyboard.hasNextInt()) {
int number = keyboard.nextInt();
}else{
System.out.println("Not an integer number!");
keyboard.next();
}
I'm new to Java and I wanted to keep on asking for user input until the user enters an integer, so that there's no InputMismatchException. I've tried this code, but I still get the exception when I enter a non-integer value.
int getInt(String prompt){
System.out.print(prompt);
Scanner sc = new Scanner(System.in);
while(!sc.hasNextInt()){
System.out.println("Enter a whole number.");
sc.nextInt();
}
return sc.nextInt();
}
Thanks for your time!
Take the input using next instead of nextInt. Put a try catch to parse the input using parseInt method. If parsing is successful break the while loop, otherwise continue.
Try this:
System.out.print("input");
Scanner sc = new Scanner(System.in);
while (true) {
System.out.println("Enter a whole number.");
String input = sc.next();
int intInputValue = 0;
try {
intInputValue = Integer.parseInt(input);
System.out.println("Correct input, exit");
break;
} catch (NumberFormatException ne) {
System.out.println("Input is not a number, continue");
}
}
Shorter solution. Just take input in sc.next()
public int getInt(String prompt) {
Scanner sc = new Scanner(System.in);
System.out.print(prompt);
while (!sc.hasNextInt()) {
System.out.println("Enter a whole number");
sc.next();
}
return sc.nextInt();
}
Working on Juned's code, I was able to make it shorter.
int getInt(String prompt) {
System.out.print(prompt);
while(true){
try {
return Integer.parseInt(new Scanner(System.in).next());
} catch(NumberFormatException ne) {
System.out.print("That's not a whole number.\n"+prompt);
}
}
}
Keep gently scanning while you still have input, and check if it's indeed integer, as you need:
String s = "This is not yet number 10";
// create a new scanner
// with the specified String Object
Scanner scanner = new Scanner(s);
while (scanner.hasNext()) {
// if the next is a Int,
// print found and the Int
if (scanner.hasNextInt()) {
System.out.println("Found Int value :"
+ scanner.nextInt());
}
// if no Int is found,
// print "Not Found:" and the token
else {
System.out.println("Not found Int value :"
+ scanner.next());
}
}
scanner.close();
As an alternative, if it is just a single digit integer [0-9], then you can check its ASCII code. It should be between 48-57 to be an integer.
Building up on Juned's code, you can replace try block with an if condition:
System.out.print("input");
Scanner sc = new Scanner(System.in);
while (true) {
System.out.println("Enter a whole number.");
String input = sc.next();
int intInputValue = 0;
if(input.charAt(0) >= 48 && input.charAt(0) <= 57){
System.out.println("Correct input, exit");
break;
}
System.out.println("Input is not a number, continue");
}
I want my program to tell the user that if (s)he enters a non-integer he should try again, instead of just terminating the whole main method like it does now. Pseudo code of problem part:
int integer = input.nextInt();
If (user types in a non-integer) {
("you have entered a false value, please retry");
then let's user enter int value
else {
assign nextint() to integer and continue
}
You can use a while loop to re-execute that portion of code until the user enters a proper integer value.
do {
input = read user input
} while(input is not an integer)
It seems you are using a Scanner, so you could use the hasNextInt method:
while (!input.hasNextInt()) {
let user know that you are unhappy
input.next(); //consume the non integer entry
}
//once here, you know that you have an int, so read it
int number = input.nextInt();
This is assuming that you are worried about the user entering in something other than an integer on input:
public static void main(String[] args) {
Integer integer = 0;
Scanner sc = new Scanner(System.in);
System.out.println("Enter an integer:");
String line = sc.next();
integer = tryParse(line);
while(integer == null){
System.out.print("The input format was incorrect, enter again:");
integer = tryParse(sc.next());
}
int value = integer.intValue();
}
public static Integer tryParse(String text){
try{
return new Integer(text);
} catch
(NumberFormatException e){
return null;
}
}