How to throw an exception for large integer inputs in java? - java

I have a particular code in which I am inputting two integer numbers. However, I tried using try catch method with throws IOException but it doesn't help. What I want to do is throw an error if any of the input number very large like 12345678910 - a number greater than 10 digits, so that my code does not throw an error. Due to confidentiality I cannot disclose the code but I assume the code is not required for this. Any suggestions? Thanks in advance.

The largest value an int can hold is lesser than the largest 10 digit number.
It is 2,147,483,647. So, the input will be invalid as soon as it is stored in the int variable.
for integers lesser than that boundary, say 5 digits, you can use this.
Create a new Exception class :
public class CustomException extends Exception
{
public CustomException(String message)
{
super(message);
//handle the exception here.
}
}
then declare a throws CustomException from the method you are using.
public void myMethod(int a, int b) throws CustomException {
if(a > 99999 || b > 99999) {
throw new CustomException("write what message you want printed");
return;
}
//do your stuff here
}
OR if you want to check for the exception as soon as it is entered for very large numbers
Assuming you use Scanner to take in the number. take the input in the String form. and then try converting it to the integer form via a check.
Scanner sc = new Scanner(System.in);
String number = sc.nextLine();
int num;
double holder = String.valueOf(number);
if(holder>Integer.MAX_VALUE) {
throw new Exception();
} else
num = (int) holder;
This seems to be a very round about way, but it will work for numbers of any length.
You have to do the same for the other number too, so you can put the logic inside a method.

One way to do is to check the length by converting the integer to String, other way is to check the range and throw error message
Example:
Scanner in = new Scanner (System.in);
int input = nextInt();
String temp = Integer.toString(input);
if(temp.length > 5 )
throw new IllegalArgumentException ("The value is larger than 5 digits! ");

As to Sotirios Delimanolis, your question made me a lot of noise. If you mean you need to throw an error if the int is 6 digits, meaning million, then you are looking for somthing like this:
public void checkUnderMillion(int integer) throws IOException {
if (integer >= 1000000) {
throw new IOException("Invalid input");
}
}
That should help if I understood your question.

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);
}
}

taking even number from user and giving exception error if number is odd

I am a java student and I am writing a java program with exception handling. In this program, I am trying to write a program that gets 5 even number from user and if the user enter odd number then show an exception that the number is odd. I am using custom exception "oddexception" in this program.
Now let's talk about the issue. So I have an issue that this program isn't compiling. It show an error which is mentioned in the image below.
The answer to this question can be small and stupid for you but I am a beginner in java so this answer really matters for me. please help me.
Please help me to find a solution. The solution
import java.lang.Exception;
class oddexception extends Exception
{
oddexception(String message, int a)
{
System.out.println(message);
System.out.println("Invalid Number is/are "+a);
}
}
class program4
{
public static void main(String args[])
{
Integer n[] = new Integer[5];
int j=0;
for(int i=0; i<5; i++)
{
try
{
n[i] = Integer.valueOf(args[i]);
if(n[i]%2!=0)
{
j++;
throw new oddexception("Number is odd "+n[i]);
}
}
catch(oddexception e)
{
System.out.println("Caught my exception");
}
}
System.out.println("Invalid numbers are : "+j);
}
}
From the error message it quite clear that the constructor of your exception is expecting a String and an integer (oddexception(String message, int a)). Where as you just passing a String.
throw new oddexception("Number is odd "+n[i]); //results to String
So changing a bit of your code
throw new oddexception("Number is odd " , n[i]);
Your oddexception constructor has two arguments, so instead of
throw new oddexception("Number is odd "+n[i]);
you should write
throw new oddexception("Number is odd ",n[i]);
First of all, I wanted to ask to you follow Java coding convention and start your ClassNames with an uppercase character and then follow camel casing, by following these conventions your code will become more readable and understandable.
Now about your problem, you are accepting two arguments in your constructor oddexception(String message, int a), one String and one int.
But while calling it you are passing only one argument "Number is odd "+n[i], because n[i] will concatenate with the String and become a String.
So instead of throw new oddexception("Number is odd "+n[i]); you should write throw new oddexception("Number is odd ", n[i]);

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 Exception Handling - ID Number Machine

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");
}
///}
}
}

Parsing large int in Java

I have a JTextField object that a user can type in a number(or anything) into. I am trying to parse this textfield for a number and I do a validation check to see if the number is within a certain range (1-999).
String lowerLimit = this.lowerLimitTextField.getText().trim();
String upperLimit = this.upperLimitTextField.getText().trim();
if( Integer.parseInt(lowerLimit) < 1 || Integer.parseInt(upperLimit) > 999 )
{
return "The string must be in the range 0-999";
}
My issue is that, the user can specify any value into the textfield. When I try to input something like "61412356123125124", I get a NumberFormatException when parsing the string. What would be the simplest way to handle such a case? I do have a check that makes sure that the inputted string is all numbers, so thats fine.
I have tried changing the parseInt() into a parseLong() but I still get the same issue, since the number inputted is essentially unbounded. Can this be done with parsing the string (preferred), or is the simplest way to set some constraints on the JTextField itself?
Use NumberFormatto parse
import java.text.NumberFormat;
import java.text.ParseException;
public class MyVisitor {
public static void main(String[] args) throws ParseException {
System.out.println(NumberFormat.getNumberInstance().parse("61412356123125124"));
}
}
outputs
61412356123125124
Looks like you do not want to get the number, just check range (0-999). In this case just catch NumberFormatException and return same string:
try {
if( Integer.parseInt(lowerLimit) < 1 || Integer.parseInt(upperLimit) > 999 ) {
return "The string must be in the range 0-999";
}
} catch (NumberFormatException e) {
return "The string must be in the range 0-999";
//or more relevant message, like "Number to long" or something
}
The answer is that the Exception is your friend: It's telling you the number is too large... Put the error handling in the catch block or better yet declare throws NumberFormatException and catching calling block so that the method can be recalled
So you can use Integer.parseInt, Long.parseLong, or new BigInteger(String)... I would recommend Integer.parseInt in this case. Once you've got an int, you can do bounds checking. And if it's out of bounds, you might just want to throw an NumberFormatException :)

Categories