Java Exception Handling - ID Number Machine - java

I'm in the process of improvement my skills in Java, now I am doing some exercises of exceptions, but I am stuck in this exercise:
ID Number Machine: Ask a user for a ID number. The correct input for a
id number is 10 in length and they must all be numbers.
Input: 123456790 Output: correct
Input: 12eer12345 Output: incorrect
Input: 12345678901 Output: incorrect
I don’t know what exception use to make the program work, i know the NumberFormatException can be use to check if the string is numeric, but in general im stuck, thanks is anybody can help me.
I’m trying to make it work with the great help you give me guys, in the page where the exercises are they give you the problem some code and you have to complete that code, so far I make this code with the code they give you:
import java.util.Scanner;
class Challenge{
public static void main(String args[]){
Scanner scanner=new Scanner(System.in);
String input;
int num;
System.out.println("Enter the ID number:");
input = scanner.next();
///{Write your code here
try
{
num = Integer.parseInt(input);
}
catch(NumberFormatException nfe)
{
System.out.println("incorrect");
}
if(input.length()==10)
System.out.println("correct");
///}
}
}
I’m trying to run that and when I use the number 1234567890 the output is "correct", and if I use the string 123qwerqw the output is "incorrect" and this is correct behaviour. But when I use 1234 the program sticks and does not show anything.

The NumberFormatException is the exception that is thrown if an operation is attempted using an input value that does not match the expected form.
To see if a string is actually a number, the logic is to try to parse it to an integer.
If it throws a number format exception, it cannot be converted.
If you want to be able to deal with decimal numbers, you would need to parse to a Double using Double.ParseDouble.
Using Integer.ParseInt will fail if you enter any number that is not whole.
public boolean isValidNumber(String val) throws NumberFormatException {
try {
int i = Integer.ParseInt(val);
} catch (NumberFormatException nfe) {
//you know here that you have non numeric chars
return false;
}
//To check the length...
if (val.length > 10) {
return false;
}
return true;
}
To use the isValidNumber method....
String myNumber = "123456";
String myNotNumber = "a small town with views of the sea";
if (isValidNumber(myNumber)) {
System.out.Println(String.format("The number {0} is valid", myNumber).toString());
} else {
System.out.Println(String.format("The number {0} is not valid", myNumber).toString());
}
The logic of this is that if the number does contain any non-numeric values, the error is thrown when we try to convert the string to an int.
We catch the error, and return false from the method.
If the string does parse to an int, we know it's all numeric (and as we're using an integer, we know it's not a decimal).
The second test deals with the length - again, we return a false if the value does not match the criteria specified. Anything longer than 10 chars is invalid, so return a false.
The final return statement can only be reached if all the preceding checks have passed.
I'm not certain this will compile straight off (I'm writing it from memory having not used Java for about 2 years), but that is the basic logic for it.

Here is the code working for my problem:
import java.util.Scanner;
class Challenge{
public static void main(String args[]){
Scanner scanner=new Scanner(System.in);
String input;
int num;
System.out.println("Enter the ID number:");
input = scanner.next();
///{Write your code here
try
{
num = Integer.parseInt(input);
System.out.println(input.length()==10?"correct":"incorrect");
}
catch(NumberFormatException nfe)
{
System.out.println("incorrect");
}
///}
}
}

Related

Take input as a string in Java and limit the user to not enter integer

I want to take input as a string in Java and limit the user to not enter integer by using try catch.
import java.util.*;
public class trycatch {
public static void main(String args[]) {
Scanner sc=new Scanner(System.in);
String a;
System.out.println("\n\nEnter the name");
try {
a=sc.nextLine();
System.out.println("You name is "+a);
}
catch(InputMismatchException b) {
System.out.println("There is problem with your input");
}
}
}
Test to see if it is an int and if not a Exception is thrown
a=sc.nextLine();
Integer.valueOf(a); // throws NumberFormatException
// this is number so go to top of loop
continue;
} catch(NumberFormatException b) {
System.out.println("There is NO problem with your input");
// we can use `a` out side the loop
}
Take a look at this:
Does java have a int.tryparse that doesn't throw an exception for bad data?
Use that technique to try to parse what the user entered as an int. If the conversion succeeds, it means they entered an int, and you should throw an exception because you said you don't want them to enter an int (which I understood to mean you don't want them to enter a sequence of numbers only)
I haven't given you the exact answer/written your code for you because you're clearly learning java and this is an academic exercise. Your university/school isn't interested in teaching/assessing my programming ability, they're interested in yours, so there isn't any value to you in me doing your work for you :)
If you get stuck implementing what I suggest, edit your question to include your improved code and we can help again
As a side note, I suggest you make your error messages better that "there was a problem"
Nothing is more frustrating to a user than being told there was a problem but not what it was or how to fix it.
You should check you string for numbers like this:
a=sc.nextLine();
if (a.matches(".*\\d+.*")) {
throw new InputMismatchException();
}
This problem can be solved best with using Regular expression but since your requirement is to use try catch so you can you use below approach
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String a = null;
System.out.println("\n\nEnter the name");
try {
// try to get Integer if it is number print invalid input(because we
// don't want number)
sc.nextInt();
System.out.println("There is problem with your input");
}
//getting exception means input was not an integer
// if input was not an Integer then try to read that as string and print
// the name
catch (InputMismatchException b) {
a = sc.next();
System.out.println("You name is " + a);
}
}

unable to convert string to integer using parseInt() [duplicate]

This question already has answers here:
What is a NumberFormatException and how can I fix it?
(9 answers)
Closed 6 years ago.
As a beginner I know that Integer.parseInt() is used to convert strings to integers but here I tried a program but its not working
Public static void main(String args[])
{
Scanner sr=new Scanner(System.in);
String s=sr.nextLine();
int i=Integer.parseInt(s);
System.out.println(i);
}
I want to take a line as input and convert it into integers and print but while executing it show NumberFormatException
Not all strings can be converted to integers.
For example, how should "xyz" be converted to an integer? There's simply no way. Java notifies the programmer of such situations with an NumberFormatExcpetion. And we programmers should handle such exception properly.
try {
Integer.parseInt(s);
} catch (NumberFormatException e) {
// s cannot be converted to int, do sth.
e.printStackTrace();
}
Scanner.nextInt() will throw a different exception (InputMismatchException) for invalid inputs. Nothing is changed in terms of handling inputs that simply cannot be converted to int.
Your code is correct and works fine.
Make sure that the number you are entering is within the limits of Integer [-2147483648,2147483647] as if the number is out of range then too it throws a NumberFormatException.
Although the preffered way to do this is to use sr.nextInt();
But what you have done also works just make sure that the number you are entering is actually int.
Use try and catch block .If you are giving string in place of integer , it will print "Please enter a number not string.Code is given below
Public static void main(String args[])
{
Scanner sr=new Scanner(System.in);
String s=sr.nextLine();
try{
int i=Integer.parseInt(s);
}catch(Exception e){
System.out.println(Please enter a number not string );
}
}
You are using a line of numbers which may contain space(449 003), so
it may result in exception.
So you can remove the white spaces before parsing it to an integer.
As #luke lee mentioned alphabets and special characters can not
converted to integers, so use try catch blocks to handle those
exceptions.
try{
Scanner sr=new Scanner(System.in);
String s=sr.nextLine().replaceAll("\\s+", "");
int i=Integer.parseInt(s);
System.out.println(i);
}catch (NumberFormatException e) {
e.printStackTrace();
}
You should use sr.nextInt(). And if you are planning on looping the entier thing, you should use sr.nextLine() right after sr.nextInt(). Otherwise the enter key you press will be taken as input resulting in unpredictable outputs.
1.Convert using Integer.parseInt()
Syntax
public static int parseInt(String s) throws NumberFormatException
The parameter s will be converted to a primitive int value. Note that the method will throw a NumberFormatException if the parameter is not a valid int.
Example
String numberAsString = "1234";
int number = Integer.parseInt(numberAsString);
System.out.println("The number is: " + number);
2.Convert using Integer.valueOf()
Example
String numberAsString = "1234";
Integer intObject = new Integer(numberAsString);
int number = intObject.intValue();
you can shorten to:
String numberAsString = "1234";
int number = new Integer(numberAsString).intValue();
or just:
int number = new Integer("1234").intValue();

Java Scanner keep asking for input until variable is a double or int, or empty, at which point is given default value

here is the pseudo for what im asking
1. Take value
2. is value double or int?
3. if so, continue in program
4. else
5. is value empty?
6. if value empty; value=0.08
7. else
8. at this stage, value is not an empty valid, or a valid double or valid int
9. user did it wrong, prompt error
10. jump to step one take value
So to me this is pretty complicated, im new to this.
Ive been trying to impliment it like so;
while ( costscan.hasNext() )
{
double costperkm = costscan.nextDouble();
if (costperkm=double){
System.out.println("Value is double");
System.out.println("FUEL COST SAVED ");
}
else {
if(costperkm=null){
costperkm=0.08;
}
else{
}
System.out.println("FUEL COST SAVED ");
}
System.out.print("\n");
System.out.print("\n");
}
My code above is the result of just playing about so at this stage it may not even make sense anymore. Hope someone can help, thanks.
The problem with hasNextDouble and nextDouble is that as long as the user just presses enter, they will both keep asking for input.
If you want to use a default value when the user simply presses enter, you should rather use Scanner.nextLine combined with Double.parseDouble, since nextLine is the only next-method that accepts empty input.
Here's a possible solution:
String input;
while(true) {
input = costscan.nextLine();
if(input.isEmpty()) {
input = "0.08";
break;
}
if(isParseable(input)) {
break;
}
System.out.println("ENTER ONLY NUMBERS [DEFAULT 0.08]");
}
double costperkm = Double.parseDouble(input);
The method isParseable looks like this:
private static boolean isParseable(String str) {
try {
Double.parseDouble(str);
return true;
} catch(NumberFormatException e) {
return false;
}
}

scanner.nextInt(), out of range avoidance?

I've finished a simple program that converts a decimal number to binary (32bit). I would like to implement some type of error message should the user enter in an overflow number (anything over 2147483647). I tried a if_else , loop, but quickly found out I couldn't even do that. So I messed with taking the input as a string, and then using some things like .valueOF() etc, and still can't seem to get around to the solution.
I don't see how I can compare any value to a >2147483648 if I can't store the value in the first place.
Here's the bare code I have for the getDecimal() method:
numberIn = scan.nextInt();
Edit:: After trying the try / catch method, running into a compile error of
"non-static method nextInt() cannot be referenced from a static context".
My code is below.
public void getDec()
{
System.out.println("\nPlease enter the number to wish to convert: ");
try{
numberIn = Scanner.nextInt();
}
catch (InputMismatchException e){
System.out.println("Invalid Input for a Decimal Value");
}
}
You can use Scanner.hasNextInt() method, which returns false, if the next token cannot be converted to an int. Then in the else block, you can read the input as string using Scanner.nextLine() and print it with an appropriate error message. Personally, I prefer this method :
if (scanner.hasNextInt()) {
a = scanner.nextInt();
} else {
// Can't read the input as int.
// Read it rather as String, and display the error message
String str = scanner.nextLine();
System.out.println(String.format("Invalid input: %s cannot be converted to an int.", str));
}
Another way to achieve this is of course, using try-catch block. Scanner#nextInt() method throws an InputMismatchException, when it can't convert the given input into an integer. So, you just need to handle InputMismatchException: -
try {
int a = scan.nextInt();
} catch (InputMismatchException e) {
System.out.println("Invalid argument for an int");
}
I suggest you surround that statement with a try/catch block for NumberFormatException.
Like so:
try {
numberIn = Integer.valueOf(scan.next());
}catch(NumberFormatException ex) {
System.out.println("Could not parse integer or integer out of range!");
}
use exceptions.. whenever a number is entered more than its storing capacity then exception will be raised
Refer docs.oracle.com/javase/tutorial/essential/exceptions/
You can user hasNextInt() method to make sure that there is an integer ready to be read.
try this :
long num=(long)scan.nextLong();
if (num > Integer.MAX_VALUE){
print error.
}
else
int x=(int)num;
or try catch:
try{
int number=scan.nextInt()
}
}catch(Exception ex){
print the error
}

How to insist that a users input is an int?

Basic problem here.. I will start off by asking that you please not respond with any code, as that likely will only confuse me further (programming noob). I am looking for a clear explanation on how to solve this issue that I'm having.
I have a scanner that reads input from the user. The user is prompted to enter an int value between 1 to 150 (whole numbers only). I obtain the value as follows:
Scanner scan = new Scanner(System.in);
int input = scan.nextInt();
And continue on with my program, and everything works fine.
Unfortunately, the code isn't exactly bulletproof, since any input that is not an integer can break it (letters, symbols, etc).
How can I make the code more robust, where it would verify that only an int was entered?
These are the results I'm hoping for:
Lets say the input was:
23 -> valid
fx -> display an error message, ask the user for input again (a while loop would do..)
7w -> error, again
3.7 -> error
$$ -> error
etc
Scanner.hasNextInt() returns true if the next token is a number, returns false otherwise.
In this example, I call hasNextInt(). If it returns true, I go past the while and set the input; if it returns false, then I discard the input (scanner.next();) and repeat.
Scanner scan = new Scanner(System.in);
while(!scan.hasNextInt()) {
scan.next();
}
int input = scan.nextInt();
Here's a simple example with prompts and comments.
Scanner scan = new Scanner(System.in);
System.out.print("Enter an integer: "); // Initial prompt for input
// Repeat until next item is an integer
while (!scan.hasNextInt())
{
scan.next(); // Read and discard offending non-int input
System.out.print("Please enter an integer: "); // Re-prompt
}
// At this point in the code, the user has entered an integer
int input = scan.nextInt(); // Get the integer
// And now you can use the input variable.
Use scan.hasNextInt() to make sure the next input is an int.
I have written an example that ensures that the program will continue only if a number and not an invalid value is entered. Do not worry, I added the desired explanation.
The program asks the user to input a number. A loop ensures that the processing will not go on until a valid number is entered. Before that I have defined a variable "inputAccepted" that has false as default value. If he enters a number, the variable "inputAccepted" is set to true and the program leaves the loop. But if he enters something else than a number, an exception is thrown right in this moment, and the line that sets the variable "inputAccepted" to true will not be executed. Instead a message will be printed out that tells the user that his input is not valid. Since "inputAccepted" could not be set to true, the loop will do the same stuff again until the string can be converted to a number.
You can test the program here.
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
boolean inputAccepted = false;
while (!inputAccepted) {
try {
System.out.print("Please enter a number: ");
Integer.valueOf(input.nextLine());
inputAccepted = true;
} catch (NumberFormatException e) {
System.out.println("Not a valid number.");
}
}
System.out.println("Thank you!");
}
}
Just get "anything" and parse it:
Scanner scan = new Scanner(System.in);
Integer number = null;
while (number == null) {
try {
number = Integer.parseInt(scan.next());
} catch (NumberParseException e) {
System.out.println("bad input: " + input);
}
}
Without any code and just in English, I'd say there's two things you have to test or look out for. First that the input is an int, second that the int is within the correct range.
In terms of pseudocode, the first thing to do is make sure it's an int. Declaring an int named "input", I would put a try / catch block, where you try to scan in the user input as an int, with parseInt(). If the try part fails, you know it's not an int and can return an error message.
Then, now that you know that "input" is an int, you can test whether it is less than 1 or more than 150, and return an error message if so!
public class Sample {
/**
* author CLRZ
*/
public static void main(String[] args) {
int a; // variable
Scanner in = new Scanner(System.in); // scans your input
System.out.println("Enter your number's choice:");
int sem1 = in.nextInt(); // reads next integer
if (sem1 == 1) // conditioned if your choice number is equal to 1
System.out.println("Hello World1"); // output wil be Hello World
int b;
System.out.println("Enter your number's choice:");
int sem2 = in.nextInt();
if (sem2 == 2)
System.out.println("Hello World2");
int c;
System.out.println("Enter your number's choice:");
int sem3 = in.nextInt();
if (sem3 == 3)
System.out.println("Hello World3");
}
}

Categories