Parsing large int in Java - 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 :)

Related

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

How to verify textField input?

I know this shouldn't be too difficult but my searching hasn't led to anything useful yet. All I want to do is make sure the user inputs a positive integer into a textField. I've tried:
public class myInputVerifier extends InputVerifier {
#Override
public boolean verify(JComponent jc) {
String text = ((jTextFieldMTU) jc).getText();
//Validate input here, like check int by try to parse it using Integer.parseInt(text), and return true or false
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
}
So in my main code I want to use this to display "OK" if successful and "Enter a positive number" if not successful.
Can someone point me in the right direction please? Thanks!
You could use a try-catch block to check if the input is an integer:
try {
int i = Integer.parseInt(input);
// input is a valid integer
}
catch (NumberFormatException e) {
// input is not a valid integer
}
String has a matches method you can use with regular expressions to see if the contents match a particular pattern. The regular expression for positive integers is ^[1-9]\d*$ so you can use it like this...
boolean matches = text.matches("^[1-9]\d*$");
if(matches){
//Do something if it is valid
}else{
//Do something if it is not
}
I suggest you use try catch.
Catch the NumberFormatException.
In this way you check if the text can be parsed to an integer. If not you can display an error message to the user.
After that you can us an if else statement to check if the number is positive if not positive you can give the user an error message. I suggest you research try catch if you don't know it.

Number format exception for large inputs

This code works fine for some inputs.
but I get a NumberFormatError for higher values of inputs such as 1000000.
The input (taken for s[]) ranges from values 1-2000000
What could be the reason?
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
public static void main(String[] args) {
/* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
try
{
BufferedReader read = new BufferedReader(new InputStreamReader(System.in));
int no=Integer.parseInt(read.readLine());
String s[]=read.readLine().split(" ");
int result=0;
for(int i=0; i<no; i++)
{
result+= Integer.parseInt(s[i]);
if(result<0)
result=0;
}
System.out.println(result);
}
catch(IOException e)
{
System.out.println(e.getMessage());
}
}
}
Inside your for-loop, your first entered digit is the size of the array. That's how your logic is so far. Unless you're actually loading in 2,000,000 numbers manually (or copy/pasting), this would throw an ArrayIndexOutOfBoundsException.
You would get a NumberFormatException if you were to type in non-digits as the second input, or a number larger than Integer.MAX_VALUE (2147483647) or less than Integer.MIN_VALUE (-2147483648).
Entering something like:
1000000
2 1 2 1 2 1 /*... 999990 digits later ...*/ 2 1 2 1
makes the program terminate correctly. Here's the input file I used, if anyone wants it: http://ge.tt/95Lr2Kw/v/0
The program was compiles and run manually from a command promt like so: java Solution < in.txt.
Edit: I just remembered that the input values in the array could be as large as 2000000. You would have to use a BigInteger to hold a result value as large as 2000000^2.
I am agree with #lzmaki.
I don't get any NumberFormatException for your value.
But, I get ArrayIndexOutofBoundException which actually caused from StackOverFlow when I tried like this:
1000000
1 2 3
then enter
as in that time, the system recognize that it have not enough memory in its stack for hold such huge number of data.
I got NumberFormatException for the following case:
1000000
enter twice
becuase not system get a non-number format to convert integer format which is "".
I hope my analysis help you to find your bug :)
Assuming it's not a buffer overflow, any non-numeric character passed to Integer.parseInt will throw a NumberFormatException. This includes whitespace and non-printable characters like newlines as well as decimal points (Since floating point numbers are not integers).
You can try validating your inputs by using .trim() when you call read.readLine(), as well as checking for null or empty string before passing to Integer.parseInt(). Something like:
String input = read.readLine();
if ( input != null )
input = input.trim();
if ( input.equals("") )
throw new IllegalArgumentException("Input must be a number");
int no=Integer.parseInt( input );
However you decide to validate input for the first line, also do for the second readLine() call. Hopefully you can narrow down exactly what's causing the problem.

Comparison problems [.equals()] in java

I am trying to determine whether a string contains a positive int or not. My code is:
public void isInt(String str) throws NotIntException{
String integer=str.replaceAll("\\d","");
System.out.println(integer);
if (!integer.equals("")){
throw new NotIntException("Wrong data type-check fields where an integer"+
" should be.");
}//end if
if (integer.equals("-")){
System.out.println(integer);
throw new NotIntException("Error-Can't have a negative count.");
}//end if
}//end method
I am testing this with a string "-1", which should, after the replaceAll(), become "-". This should enter both if-statements. But it only enters the first. I tried it with the == comparison too, just in case, but it didn't work either. What's odd to me is that whether I look to fulfill the second if-statement's condition or to fulfill its negation [i.e., !integer.equals("-")], the program still doesn't enter the if....
Thanks, usually my comparison issues are just me missing something basic, but I really don't see anything here...
Since you are throwing an Exception in your first if, so, your 2nd if will not even be tested.
if (!integer.equals("")){
throw new NotIntException("Wrong data type-check fields where an integer"+
" should be.");
}
if (integer.equals("-")){
System.out.println(integer);
throw new NotIntException("Error-Can't have a negative count.");
}
If your code enters the first if, it will not execute further.
But, why are you using this approach for your problem.
You can easily use Integer.parseInt to check for valid integer. And then if it is valid, then test whether its less than 0. It would be far easier and readable.
My solution:
public static boolean isPositiveInt(String str) {
try {
int number = Integer.parseInt(str.trim());
return number >= 0;
} catch (NumberFormatException e) {
return false;
}
}
If you want to simply read an int from a String, use Integer.parseInt(), although that would only work if you want to see if a string "is" an int, not contains one.
You could use a combination of Integer.parseInt() and a loop strategy to see if it contains an int fairly easily though, then just check if that is positive or not.
You approach is too complicated. I would keep it simple:
if (integer.startsWith("-")) {
// it's a negative number
}
if (!integer.matches("^\\d+$")) {
// it's not all-numbers
}
and forget the call to replaceAll()

check the input null

i've found this line of code got error if the input not an number
int sum = Integer.parseInt(request.getParameter("sum"));
the error message is
type Exception report
message
descriptionThe server encountered an internal error () that prevented it from fulfilling this request.
exception
org.apache.jasper.JasperException: java.lang.NumberFormatException: For input string: "a"
root cause
java.lang.NumberFormatException: For input string: "a"
how to handle the input if the input is a string or null?
thanks
You should first make sure request parameter is not null and contains numbers only using:
if (request.getParameter("sum") != null &&
request.getParameter("sum").matches("^\\d+$"))
int sum = Integer.parseInt(request.getParameter("sum"));
Try:
int sum = 0;
try {
sum = Integer.parseInt(request.getParameter("sum"));
}
catch (NumberFormatException e) {
// sum = 0. If you needed to do anything else for invalid input
// put it here.
}
It really depends on what should be done if sum is not a number.
try{
int sum = Integer.parseInt(request.getParameter("sum"));
}
catch(Exception e)
{
//how do you want to handle it? like ask the user to re-enter the values
}
Just catch the exception and handle it accordingly:
int sum;
try {
sum = Integer.parseInt(request.getParameter("sum"));
}
catch {
//do something if invalid sum
}
Check manually (loop over the characters)
Catch the exception
Try this:
try {
sum = Integer.parseInt(request.getParameter("sum"));
} catch (NumberFormatException e) {
... // handle if the string isn't a number
} catch (NullPointerException e) {
... // handle if it's null
}
Check for null before Using Intefer.parseInt and also you can check whether input contains other than numeric value
Here's a different approach that doesn't involve throwing and catching exceptions:
String input = request.getParameter("sum");
// Validate the input using regex
if (input == null || !input.matches("^-?\\d{1,8}$")) {
// handle bad input, eg throw exception or whatever you like
}
int sum = Integer.parseInt(input);
Note that this regex doesn't allow numbers too large, and allows negative numbers
I see the org.apache.jasper.JasperException Which means this is in a JSP? If you're adding code like that to a JSP, you might want to reconsider what you're doing. Ideally, you should handle things like input validation in a controller of some sort, and then pass off results to a template of JSP for rendering.
There are many frameworks out there to help with this sort of thing, and in general they're worth using because your web application will benefit from all of the work that the framework authors have already done in the realm of security etc...
Pretty much any of the half a dozen code answers already posted will work for you though if you just want to hack it out.

Categories