While Not Condition - java

How can I say the following:
while(input is not an int){
do this
}
I tried this code but I know it's wrong:
int identificationnumber;
Scanner sc3 = new Scanner(System.in);
identificationnumber = sc3.nextInt();
while( identificationnumber != int){ // this line is wrong
Scanner sc4 = new Scanner(System.in);
identificationnumber = sc4.nextInt();
}
Any suggestions please.Thanks.

Javadocs are your friend: http://docs.oracle.com/javase/6/docs/api/java/util/Scanner.html
nextInt() throws an exception if the next token isn't an int. You're probably looking for hasNextInt()
Also, why are you creating a new Scanner every time you loop? (Or at all - you already have one before the loop)

try :
while (! scanner.hasNextInt()) { // while the next token is not an int...
scanner.next(); // just skip it
}
int i = scanner.nextInt(); // then read the int

Scanner throws an exception before getting to that line
http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Scanner.html#nextInt()
The following code will work:
int i = 0;
while(true){
Scanner scan = new Scanner(System.in);
try{
i = scan.nextInt();
}catch (Exception e) {
break;
}
}

You want this?
String identificationnumber;
Scanner scanner = new Scanner(System.in);//Only one Scanner is needed
while (scanner.hasNext()) { // Is there has next input?
identificationnumber = scanner.next();//Get next input
try {
Integer.parseInt(identificationnumber);//Try to parse to integer
System.out.println(identificationnumber + " is a number!");
} catch (NumberFormatException e) {
System.out.println(identificationnumber + " is not a number!");
}
}

By writing sc3.nextInt() I assume you always get an int back, so checking for a non int seems a bit strange.
Maybe its better to return a string with the number inside. If the string is empty stop (you can just check against "") and otherwise convert it to an integer.

Use nextInt() method of scanner class.
It throws,
InputMismatchException - if the next token does not match the
Integer regular expression, or is out of range

You should be doing this:
if (sc3.hasNextInt())
Check this out: How to use Scanner to accept only valid int as input
With regards to class/type comparison, read this: What is the difference between instanceof and Class.isAssignableFrom(...)?

Related

How to catch the error "InputMismatchException" in Java and print a personalized message , without using try and catch?

Scanner sc = new Scanner (System.in);
int source_radix = sc.nextInt();
String sr = source_radix+"";
if (!Pattern.matches("[0-9]+",sr) || source_radix <1 || source_radix >36)
{
System.out.print("error");
System.exit(0);
}
I want to print "error" when the input is not an integer.
The simplest way to prevent that exception being thrown from nextInt() is to call hasNextInt() first. In your specific example, we could do this:
Scanner sc = new Scanner (System.in);
int radix = 0;
if (sc.hasNextInt()) {
radix = sc.nextInt();
}
if (radix < 1 || radix > 36) {
System.out.print("error");
System.exit(0);
}
You could modify that to print different error messages to distinguish the cases where the user didn't enter a valid integer, and where they entered a integer that was outside of the required range.
In some situations, it may be necessary to call sc.nextLine() to discard something that isn't a valid number, or anything on the line after the number. (But it isn't necessary if the app is going to terminate on getting bad input.)
Finally, it is often a bad idea to call System.exit(0). If this is in your main method, return will work just as well. If it is not in main, then it probably should not be this code's responsibility to "pull the plug" on the application. But ... it is not clear cut.
You can do something this:
Scanner sc = new Scanner(file);
while(sc.hasNext()) {
String str =sc.nextLine();
if (!Pattern.matches("[0-9]+",str) ||( Pattern.matches("[0-9]+",str) && Integer.parseInt(str)) <1 )|| ( Pattern.matches("[0-9]+",str) && Integer.parseInt(str)) <1 ) >36) {
System.out.print("error");
System.exit(0);
}
}
You can check if input is number of range from 1 to 36 by only using Regex:
Scanner sc = new Scanner(System.in);
String sr = sc.nextLine();
if (!Pattern.matches("[1-9]|[12][0-9]|3[0-6]", sr)) {
System.out.print("error");
System.exit(0);
}
You may try this Java code:
Scanner sc = new Scanner (System.in);
String sr = sc.next(); // read a string
// check if we have all digits in input
boolean match = Pattern.matches("[0-9]+", sr);
// if yes then convert to int and do comparison
if (match) {
int source_radix = Integer.parseInt(sr);
if (source_radix <1 || source_radix >36) match = false;
}
// handle error if match is false
if (!match) {
System.out.print("error");
System.exit(0);
}

Java Continue---I don't understand how I get in an infinite loop [duplicate]

This question already has answers here:
How to handle infinite loop caused by invalid input (InputMismatchException) using Scanner
(5 answers)
Closed last month.
So I'm building a program which takes ints from user input. I have what seems to be a very straightforward try/catch block which, if the user doesn't enter an int, should repeat the block until they do. Here's the relevant part of the code:
import java.util.InputMismatchException;
import java.util.Scanner;
public class Except {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
boolean bError = true;
int n1 = 0, n2 = 0, nQuotient = 0;
do {
try {
System.out.println("Enter first num: ");
n1 = input.nextInt();
System.out.println("Enter second num: ");
n2 = input.nextInt();
nQuotient = n1/n2;
bError = false;
}
catch (Exception e) {
System.out.println("Error!");
}
} while (bError);
System.out.printf("%d/%d = %d",n1,n2, nQuotient);
}
}
If I enter a 0 for the second integer, then the try/catch does exactly what it's supposed to and makes me put it in again. But, if I have an InputMismatchException like by entering 5.5 for one of the numbers, it just shows my error message in an infinite loop. Why is this happening, and what can I do about it? (By the way, I have tried explicitly typing InputMismatchException as the argument to catch, but it didn't fix the problem.
You need to call next(); when you get the error. Also it is advisable to use hasNextInt()
catch (Exception e) {
System.out.println("Error!");
input.next();// Move to next other wise exception
}
Before reading integer value you need to make sure scanner has one. And you will not need exception handling like that.
Scanner scanner = new Scanner(System.in);
int n1 = 0, n2 = 0;
boolean bError = true;
while (bError) {
if (scanner.hasNextInt())
n1 = scanner.nextInt();
else {
scanner.next();
continue;
}
if (scanner.hasNextInt())
n2 = scanner.nextInt();
else {
scanner.next();
continue;
}
bError = false;
}
System.out.println(n1);
System.out.println(n2);
Javadoc of Scanner
When a scanner throws an InputMismatchException, the scanner will not pass the token that caused the exception, so that it may be retrieved or skipped via some other method.
YOu can also try the following
do {
try {
System.out.println("Enter first num: ");
n1 = Integer.parseInt(input.next());
System.out.println("Enter second num: ");
n2 = Integer.parseInt(input.next());
nQuotient = n1/n2;
bError = false;
}
catch (Exception e) {
System.out.println("Error!");
input.reset();
}
} while (bError);
another option is to define Scanner input = new Scanner(System.in); inside the try block, this will create a new object each time you need to re-enter the values.
To follow debobroto das's answer you can also put after
input.reset();
input.next();
I had the same problem and when I tried this. It completely fixed it.
As the bError = false statement is never reached in the try block, and the statement is struck to the input taken, it keeps printing the error in infinite loop.
Try using it this way by using hasNextInt()
catch (Exception e) {
System.out.println("Error!");
input.hasNextInt();
}
Or try using nextLine() coupled with Integer.parseInt() for taking input....
Scanner scan = new Scanner(System.in);
int num1 = Integer.parseInt(scan.nextLine());
int num2 = Integer.parseInt(scan.nextLine());
To complement the AmitD answer:
Just copy/pasted your program and had this output:
Error!
Enter first num:
.... infinite times ....
As you can see, the instruction:
n1 = input.nextInt();
Is continuously throwing the Exception when your double number is entered, and that's because your stream is not cleared. To fix it, follow the AmitD answer.
#Limp, your answer is right, just use .nextLine() while reading the input. Sample code:
do {
try {
System.out.println("Enter first num: ");
n1 = Integer.parseInt(input.nextLine());
System.out.println("Enter second num: ");
n2 = Integer.parseInt(input.nextLine());
nQuotient = n1 / n2;
bError = false;
} catch (Exception e) {
System.out.println("Error!");
}
} while (bError);
System.out.printf("%d/%d = %d", n1, n2, nQuotient);
Read the description of why this problem was caused in the link below. Look for the answer I posted for the detail in this thread.
Java Homework user input issue
Ok, I will briefly describe it. When you read input using nextInt(), you just read the number part but the ENDLINE character was still on the stream. That was the main cause. Now look at the code above, all I did is read the whole line and parse it , it still throws the exception and work the way you were expecting it to work. Rest of your code works fine.

How to repeat a question to a user until while loop condition is false?

I'm bulding a console application where I am trying to force a user to enter an int as a possible answer to a question otherwise the same question is repeated to the user.Thus, the user cannot move on without entering the proper data type.
below is my sample code.
Scanner scanner = new Scanner(System.in);
int userInput = 0;
do {
AskQuestion();
if(scanner.hasNextInt()) {
userInput = scanner.nextInt();
}
}
while(!scanner.hasNextInt()) ;
While I know this can be done in C#, I'm not exactly sure how to do it in java without getting stuck in an infinite loop. How do I get my code to do what I want to do? Please help!
You can use something like this. It'a a pretty simple flag combined with the use of the Scanner class.
boolean flag = false;
int val = 0;
while(!flag){
System.out.println("Something");
if(sc.hasNext()){
if(sc.hasNextInt()){
val = sc.nextInt();
flag = true;
}
else{
sc.next();
}
}
}
Try this:
Scanner scanner = new Scanner(System.in);
int userInput;
while(true) {
AskQuestion();
if (scanner.hasNextInt()) {
userInput = scanner.nextInt();
break;
}
scanner.next(); // consume non-int token
}
Another alternative which utilizes the Scanner#nextLine() method along with the String#matches() method and a small Regular Expression (RegEx) to ensure that the supplied string does indeed contain all numerical digits:
Scanner scanner = new Scanner(System.in);
String userInput = "";
int desiredINT = 0; // Default value.
while (desiredINT == 0) {
AskQuestion();
userInput = scanner.nextLine();
if (userInput.matches("\\d+")) {
desiredINT = Integer.parseInt(userInput);
if (desiredINT < 1 || desiredINT > 120) {
System.out.println("Invalid Input! The age supplied is not "
+ "likely! Enter a valid Age!");
desiredINT = 0;
}
}
else {
System.out.println("Invalid Input! You must supply an Integer "
+ "value! Try Again...");
}
}
System.out.println("Your age is: --> " + desiredINT);
And the AskQuestion() method:
private void AskQuestion() {
System.out.println("How old are you?");
}
This is nice and short one
Scanner scanner = new Scanner(System.in);
do askQuestion();
while(!scanner.nextLine().trim().matches("[\\d]+"));
Tell me if you like it
Note it just tell you if number was an int , and keeps repeating if not, but doesn't give you that int back , tell me if you need that, i shall find a way
My solution might be a bit bloated, but I hope it's nice and clear what's going on. Please do let me know how it can be simplified!
import java.util.Scanner; // Import the Scanner class
class Main {public static void main(String[] args) {
Scanner myObj = new Scanner(System.in); // Create a Scanner object
String unit;
// unit selector
while (true) {
System.out.println("Did you measure ion feet or meters? Type 'meters' or 'feet': ");
String isUnit = myObj.nextLine();
if (isUnit.equals("feet") || (isUnit.equals("meters"))) {
unit = isUnit;
break;
} else {
System.out.println("Please enter either 'meters' or 'feet'.");
}
}
System.out.println("Use selected " + unit);
}

Checking the user input (scanner) before assigning to an int variable

int i;
Scanner scan = new Scanner(System.in) {
i = scan.nextInt();
}
What I want to do is to catch the error in scanner when a user inputs a character instead of an integer. I tried the code below but ends up calling for another user input (bec. of calling another scan.nextInt() in assigning value to i after validating the first scan.nextInt() of numeric only):
int i;
Scanner scan = new Scanner(System.in) {
while (scan.hasNextInt()){
i = scan.nextInt();
} else {
System.out.println("Invalid input!");
}
}
Your logic seems a bit off, you have to consume an input if it isn't valid. Also, your anonymous block seems very odd. I think you wanted something like
int i = -1; // <-- give it a default value.
Scanner scan = new Scanner(System.in);
while (scan.hasNext()) { // <-- check for any input.
if (scan.hasNextInt()) { // <-- check if it is an int.
i = scan.nextInt(); // <-- get the int.
break; // <-- end the loop.
} else {
// Read the non int.
System.out.println("Invalid input! " + scan.next());
}
}

try/catch with InputMismatchException creates infinite loop [duplicate]

This question already has answers here:
How to handle infinite loop caused by invalid input (InputMismatchException) using Scanner
(5 answers)
Closed last month.
So I'm building a program which takes ints from user input. I have what seems to be a very straightforward try/catch block which, if the user doesn't enter an int, should repeat the block until they do. Here's the relevant part of the code:
import java.util.InputMismatchException;
import java.util.Scanner;
public class Except {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
boolean bError = true;
int n1 = 0, n2 = 0, nQuotient = 0;
do {
try {
System.out.println("Enter first num: ");
n1 = input.nextInt();
System.out.println("Enter second num: ");
n2 = input.nextInt();
nQuotient = n1/n2;
bError = false;
}
catch (Exception e) {
System.out.println("Error!");
}
} while (bError);
System.out.printf("%d/%d = %d",n1,n2, nQuotient);
}
}
If I enter a 0 for the second integer, then the try/catch does exactly what it's supposed to and makes me put it in again. But, if I have an InputMismatchException like by entering 5.5 for one of the numbers, it just shows my error message in an infinite loop. Why is this happening, and what can I do about it? (By the way, I have tried explicitly typing InputMismatchException as the argument to catch, but it didn't fix the problem.
You need to call next(); when you get the error. Also it is advisable to use hasNextInt()
catch (Exception e) {
System.out.println("Error!");
input.next();// Move to next other wise exception
}
Before reading integer value you need to make sure scanner has one. And you will not need exception handling like that.
Scanner scanner = new Scanner(System.in);
int n1 = 0, n2 = 0;
boolean bError = true;
while (bError) {
if (scanner.hasNextInt())
n1 = scanner.nextInt();
else {
scanner.next();
continue;
}
if (scanner.hasNextInt())
n2 = scanner.nextInt();
else {
scanner.next();
continue;
}
bError = false;
}
System.out.println(n1);
System.out.println(n2);
Javadoc of Scanner
When a scanner throws an InputMismatchException, the scanner will not pass the token that caused the exception, so that it may be retrieved or skipped via some other method.
YOu can also try the following
do {
try {
System.out.println("Enter first num: ");
n1 = Integer.parseInt(input.next());
System.out.println("Enter second num: ");
n2 = Integer.parseInt(input.next());
nQuotient = n1/n2;
bError = false;
}
catch (Exception e) {
System.out.println("Error!");
input.reset();
}
} while (bError);
another option is to define Scanner input = new Scanner(System.in); inside the try block, this will create a new object each time you need to re-enter the values.
To follow debobroto das's answer you can also put after
input.reset();
input.next();
I had the same problem and when I tried this. It completely fixed it.
As the bError = false statement is never reached in the try block, and the statement is struck to the input taken, it keeps printing the error in infinite loop.
Try using it this way by using hasNextInt()
catch (Exception e) {
System.out.println("Error!");
input.hasNextInt();
}
Or try using nextLine() coupled with Integer.parseInt() for taking input....
Scanner scan = new Scanner(System.in);
int num1 = Integer.parseInt(scan.nextLine());
int num2 = Integer.parseInt(scan.nextLine());
To complement the AmitD answer:
Just copy/pasted your program and had this output:
Error!
Enter first num:
.... infinite times ....
As you can see, the instruction:
n1 = input.nextInt();
Is continuously throwing the Exception when your double number is entered, and that's because your stream is not cleared. To fix it, follow the AmitD answer.
#Limp, your answer is right, just use .nextLine() while reading the input. Sample code:
do {
try {
System.out.println("Enter first num: ");
n1 = Integer.parseInt(input.nextLine());
System.out.println("Enter second num: ");
n2 = Integer.parseInt(input.nextLine());
nQuotient = n1 / n2;
bError = false;
} catch (Exception e) {
System.out.println("Error!");
}
} while (bError);
System.out.printf("%d/%d = %d", n1, n2, nQuotient);
Read the description of why this problem was caused in the link below. Look for the answer I posted for the detail in this thread.
Java Homework user input issue
Ok, I will briefly describe it. When you read input using nextInt(), you just read the number part but the ENDLINE character was still on the stream. That was the main cause. Now look at the code above, all I did is read the whole line and parse it , it still throws the exception and work the way you were expecting it to work. Rest of your code works fine.

Categories