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");
}
Related
I'm confused while using an Java program I created.
public static void main(String[] args) {
Scanner scanner1 = new Scanner(System.in);
int input1 = 0;
boolean Input1Real = false;
System.out.print("Your first input integer? ");
while (!Input1Real) {
String line = scanner1.nextLine();
try {
input1 = Integer.parseInt(line);
Input1Real = true;
}
catch (NumberFormatException e) {
System.out.println("Use an integer! Try again!");
System.out.print("Your first input integer? ");
}
}
System.out.println("Your first input is " + input1);
}
Initially, when a user Ctrl+D during the input, it will promptly end the program and display an error in the form of this,
Your first input integer? ^D
Class transformation time: 0.0073103s for 244 classes or 2.9960245901639343E-5s per class
Exception in thread "main" java.util.NoSuchElementException: No line found
at java.base/java.util.Scanner.nextLine(Scanner.java:1651);
at Playground.Test1.main(Test1.java:13)
Doing a bit of research I note that Ctrl+D terminates the input of sort. Therefore, I tried add few more lines to my codes to prevent the error from appearing again and instead printing a simple "Console has been terminated successfully!" and as far as my skills can go.
public static void main(String[] args) {
Scanner scanner1 = new Scanner(System.in);
int input1 = 0;
boolean Input1Real = false;
System.out.print("Your first input integer? ");
while (!Input1Real) {
String line = scanner1.nextLine();
try {
try {
input1 = Integer.parseInt(line);
Input1Real = true;
}
catch (NumberFormatException e) {
System.out.println("Use an integer! Try again!");
System.out.print("Your first input integer? ");
}
}
catch (NoSuchElementException e) {
System.out.println("Console has been terminated successfully!");
}
}
System.out.println("Your first input is " + input1);
}
In the end, I still got the same error.
Got it!, the code hasNext() will ensure that the error will not appear. This method is to check whether there is another line in the input of the scanner and to check if its filled or empty. I am also using null to check my statement after passing the loop so the program stops if the input value is still null while keeping the function of Ctrl+D.
public static void main(String[] args) {
Integer input1 = null;
System.out.println("Your first input integer? ");
Scanner scanner1 = new Scanner(System.in);
while(scanner1.hasNextLine()) {
String line = scanner1.nextLine();
try {
input1 = Integer.parseInt(line);
break;
}
catch (NumberFormatException e) {
System.out.println("Use an integer! Try again!");
System.out.println("Your first input integer? ");
}
}
if (input1 == null) {
System.out.println("Console has been terminated successfully!");
System.exit(0);
}
System.out.println(input1);
}
This solution is not prefect of course but I would appreciate if there were much simpler options.
So, I've been stuck on this problem for a while and do not understand why my code is not working. I'm trying to teach myself Java and looking at conditionals and loops right now. So the program basically is just trying to read in an integer (int num), but if anything besides an int is entered have it ask for correct input and give a message describing what has been entered. I hope that makes sense. I'm not entirely sure if this is correct but I'm also very new to this and have been struggling to figure out what I'm missing.
Here's the code:
import java.util.Scanner;
public class LoopPrac{
public static void main (String [] args){
Scanner scan = new Scanner(System.in);
int num;
boolean bool = false;
System.out.println("Enter an Integer: ");
num = scan.nextInt();
scan.nextLine();
while(bool = false){
System.out.println("Enter an Integer: ");
num = scan.nextInt();
scan.nextLine();
if(scan.hasNextDouble()){
System.out.println("Error: Index is Double not Integer.");
}
if(scan.hasNext()){
System.out.println("Error: Index is String not Integer.");
}
if(scan.hasNextInt()){
bool = true;
}
}
System.out.println(num);
}
}
Your exception InputMismatchException is because you ask the scanner to scan the next integer scan.nextInt() but it found double or string or something else so it throws an exception that this input is not a integer.
So you can fix your code by first ask the scanner is next input is integer or not scan.hasNextInt(), it it int scan it, else check if it double or any type to print error message
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter an Integer: ");
if (scan.hasNextInt()) {
int Index = scan.nextInt();
System.out.println("Index = " + Index);
}
else if (scan.hasNextDouble()) {
System.out.println("Error: Index is Double not Integer.");
}
else {
System.out.println("Error: Index is not Integer.");
}
}
So I was using this code in my program and whenever I give input consisting of multiple words, the compiler executes the catch block that many times. I've also tried it with different methods & till now all efforts went to vain.
Method 1:
Scanner scanner = new Scanner(System.in);
int size = 0;
while (true)
{
try
{
size = scanner.nextInt();
break;
}
catch (InputMismatchException e)
{
System.out.println("Enter valid input (Digit Only)");
scanner.next();
continue;
}
}
Method 2:
Scanner scanner = new Scanner(System.in);
int size = 0;
boolean bError = true;
while (bError)
{
if (scanner.hasNextInt())
size = scanner.nextInt();
else
{
System.out.println("Enter valid input (Digit Only)");
scanner.next();
continue;
}
bError = false;
}
Method 3:
Scanner scanner = new Scanner(System.in);
int size = 0;
while (true)
{
if (scanner.hasNextInt())
size = scanner.nextInt();
else
{
scanner.next();
System.out.println("Enter valid input (Digit Only)");
continue;
}
String sizeStr = Integer.toString(size);
Pattern pattern = Pattern.compile(new String ("^[0-9]*$"));
Matcher matcher = pattern.matcher(sizeStr);
if(matcher.matches())
{
break;
}
else
{
System.out.println("Enter valid input (Digit Only)");
continue;
}
}
Method 4:
Scanner scanner = new Scanner(System.in);
int size = 0;
while (scanner.hasNext())
{
if (scanner.hasNextInt())
{
size = scanner.nextInt();
System.out.println(size);
break;
}
else
{
System.out.println("Enter valid input (Digit Only)");
scanner.next();
}
}
I'm now able to do the task via taking a String input and then parsing it to int. But the initial doubt still remains that why that was not working properly. The code below is working fine.
Scanner scanner = new Scanner(System.in);
int size = 0;
while (true)
{
try
{
String sizeStr = scanner.nextLine();
size = Integer.parseInt(sizeStr);
break;
}
catch (NumberFormatException e)
{
System.out.println("Enter valid input (Digit Only)");
scanner.next();
continue;
}
}
According to the official Java Doc (https://docs.oracle.com/javase/8/docs/api/java/util/Scanner.html):
A Scanner breaks its input into tokens using a delimiter pattern,
which by default matches whitespace. The resulting tokens may then be
converted into values of different types using the various next
methods.
The scanner can also use delimiters other than whitespace.
By default, all the next*() functions of scanner class other than nextLine() read the next token, not the next line. This means it reads until it finds a whitespace. If you want to read all the tokens in a line, you need to use nextLine() and then format the input explicitly as you want.
Consider this input:
abcd xyz
When you do scanner.nextInt() or any of scanner.next*() functions other than scanner.nextLine(), only "abcd" is read because it is the next token. When you do scanner.nextLine(), the complete string in the current line "abcd xyz" is read and the scanner advances to the next line.
However, if you want the nextInt() function to read the whole line, then you can set the delimiter to be new line '\n'.
Scanner scan = new Scanner(System.in).useDelimiter("\n");
Using this, you can get the behaviour that you want.
Following is the piece of code i have used in c/c++ which is fairly simple:
while ((scanf_s("%d", &num) == 1)&&num>0)
Below is the usual java code to read input:
try(Scanner n1 = new Scanner(System.in))
{
System.out.println("Enter the number of days");
while(n1.hasNextInt())
{
days = n1.nextInt();
//some stmts
n1.nextLine();
}
}
How can use this while to read the input as well as compare the value in a single "while" like i can do in c and c++;
You could so something like this:
int num;
final Scanner scanner = new Scanner(System.in);
while (scanner.hasNextInt() && (num = scanner.nextInt()) > 0) {
// do something with num
}
Alternatively, you could do something like this:
int input;
final Scanner scanner = new Scanner(System.in);
System.out.print("Type anything: ");
try
{
input = scanner.nextInt();
System.out.println("You typed: " + input);
}
catch (InputMismatchException e)
{
System.out.println("You typed a non-numeric value or the value entered is out of range.");
}
You can handle the exception for cases where the input is not a number or out of range.
Goal:
If the user enters a non-numeric number, make the loop run again.
Also is there another (more efficient) way of writing the numeric inputs?
public static void user_input (){
int input;
input = fgetc (System.in);
while (input != '\n'){
System.out.println("Please enter a number: ");
if (input == '0' == '1' ..... '9'){
//Execute some code
}
else {
System.out.println("Error Please Try Again");
//Repeat While loop
}
}
}
EDIT
I need the while loop condition. Simply asking, how do you repeat the while loop? Also no scanner methods.
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:
public static void user_input() {
Scanner sc = new Scanner(System.in);
while (true) {
System.out.println("Enter a 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");
}
}
}
Output
Enter a number.
w
Input is not a number, continue
Enter a number.
3
Correct input, exit
Try this one
System.out.println("Please enter a number: ");
Scanner userInput = new Scanner(System.in);
while(!userInput.hasNextInt()) {
System.out.println("Invalid input. Please enter again");
userInput = new Scanner(System.in);
}
System.out.println("Input is correct : " + userInput.nextInt());
How about this
public static void processInput() {
System.out.println("Enter only numeric: ");
Scanner scannerInput;
while (true) {
scannerInput = new Scanner(System.in);
if (scannerInput.hasNextInt()) {
System.out.println("Entered numeric is " + scannerInput.nextInt());
break;
} else {
System.out.println("Error Please Try Again");
}
}
}