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

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

Related

How to Check if String contains decimal and convert to nearest Integer?

How do I check if a String contains Integer or Decimal Numbers in Java?
Further I want to round off the number to the nearest integer if it's a decimal number and then convert it back to string.
Say,I have a string called "amount" whose value can be like "23" or "33.42", In this case I would like to convert "33.42" to "33"
Below is what I tried:
// Assume amount String has already been declared
try{
Double number = Double.parseDouble(amount);
logger.info("Double Detected");
int integer = (int) Math.round(number);
logger.info("Converting to String Integer");
amount = Integer.toString(integer);
}catch(NumberFormatException e){
logger.info("Double NOT Detected");
}
I am getting Null Pointer Exception in the above code when I am trying to parse "Double", please also let me know if there's any easier way to do this.
Initialize amount to something like "" so that it won't be null if your algorithm doesn't find an Integer to convert to a string.
Try this:
amount = new BigDecimal(amount).setScale(0, BigDecimal.ROUND_HALF_UP).toString();
This will give you the output you are looking for.
To avoid the null pointer you can do a multi-catch statement, like this:
public static void main(String args[]){
String amount = "3.14159265";
try {
Double number = Double.parseDouble(amount);
System.out.println("Double Detected");
System.out.println(number);
int integer = (int) Math.round(number);
System.out.println("Converting to String Integer");
System.out.println(integer);
amount = Integer.toString(integer);
} catch (NumberFormatException | NullPointerException e1) { //catches both exceptions
System.out.println("Double NOT Detected: ");
System.out.println(e1);
}
}
Try changing amount to null or letters to see how the exception is caught.
Make sure you initialize amount also.

Java dynamic var assigned to variable

I have a chicken and egg issue of sorts. I'm use to dynamic typing (python) so please be gentle on me if this is a basic thing.
I have a scanner, but I want to allow the user to enter either a string or an integer (1 or 'option1'). Because it's a user input, I don't know the resulting type (int or string). I need to get the user input from the scanner, assign it to a variable, and then pass that variable to an overloaded method.
The problem is that I need to declare the variable type. But, it can be either. How do I handle this?
EDIT
To clarify, I was thinking of doing something like this (Below is pseudo code):
public static float methodname(int choice){
//some logic here
}
public static float methodname(String choice){
//some logic here
}
Scanner input = new Scanner( System.in );
choice = input.nextLine();
System.out.println(methodname(choice));
The problem that i'm having is the declaration of 'choice'. What do i put for the type?
You can take it as a String and try to convert it to an int. If the conversion happens without problems you can use the int version, otherwise use the String version.
String stringValue = ...
try {
// try to convert stringValue to an int
int intValue = Integer.parseInt(stringValue);
// If conversion is possible you can call your method with the int
call(intValue);
} catch (NumberFormatException e) {
// If conversion can't happen call using the string
call(stringValue);
}
Take the input value as String, convert it to integer using
String number = "1";
int result = Integer.parseInt(number);
if it parses then you can continue using it as a number. And if it fails it will throw NumberFormatException. So you can catch the exception and proceed it with string.
try{
String number = "option1";
int result = Integer.parseInt(number);
// proceed with int logic
} catch(NumberFormatException e){
// handle error and proceed with string logic
}

How do I read input that could be an int or a double? [duplicate]

This question already has answers here:
How to test if a double is an integer
(18 answers)
Closed 7 years ago.
I'm writing a program in which I need to take input from the keyboard. I need to take a number in, yet I'm not sure if it's an int or a double. Here's the code that I have (for that specific part):
import java.io.*;
import java.util.*;
//...
Scanner input = new Scanner(System.in);
int choice = input.nextInt();
I know I can get a String and do parseInt() or parseDouble(), but I don't know which one it'll be.
Well, ints are also doubles so if you assume that everything is a double you will be OK with your logic. Like this:
import java.io.*;
import java.util.*;
Scanner input = new Scanner(System.in);
double choice = input.nextDouble();
It only get complex if you needed the input to be an integer for whatever reason. And then, parseInt() to test for int would be just fine.
Just use a double no matter what it is. There is no noticeable loss on using a double for integral values.
Scanner input = new Scanner(System.in);
double choice = input.nextDouble();
Then, if you need to know whether you've gotten a double or not, you can check it using Math.floor:
if (choice == Math.floor(choice)) {
int choiceInt = (int) choice);
// treat it as an int
}
Don't mess with catching NumberFormatException, don't search the string for a period (which might not even be correct, for example if the input is 1e-3 it's a double (0.001) but doesn't have a period. Just parse it as a double and move on.
Also, don't forget that both nextInt() and nextDouble() do not capture the newline, so you need to capture it with a nextLine() after using them.
What I would do is get String input, and parse it as either a double or an integer.
String str = input.next();
int i = 0;
double d = 0d;
boolean isInt = false, isDouble = false;
try {
// If the below method call doesn't throw an exception, we know that it's a valid integer
i = Integer.parseInt(str);
isInt = true
}catch(NumberFormatException e){
try {
// It wasn't in the right format for an integer, so let's try parsing it as a double
d = Double.parseDouble(str);
isDouble = true;
}catch(NumberFormatException e){
// An error was thrown when parsing it as a double, so it's neither an int or double
System.out.println(str + " is neither an int or a double");
}
}
// isInt and isDouble now store whether or not the input was an int or a double
// Both will be false if it wasn't a valid int or double
This way, you can ensure that you don't lose integer precision by just parsing a double (doubles have a different range of possible values than integers), and you can handle the cases where neither a valid integer or double was entered.
If an exception is thrown by the code inside the try block, the code in the catch block is executed. In our case, if an exception is thrown by the parseInt() method, we execute the code in the catch block, where the second try-block is. If an exception os thrown by the parseDouble() method, then we execute the code inside the second catch-block, which prints an error message.
You could try using the floor function to check if it is a double. In case you don't know, the floor function basically cuts off any decimal numbers. So you can compare the number with and without the decimal. If they are the same, then the number can be treated as an integer, otherwise a double (assuming you don't need to worry about large numbers like longs).
String choice = input.nextLine();
if (Double.parseDouble(choice) == Math.floor(Double.parseDouble(choice)) {
//choice is an int
} else {
//choice is a double
}

How to throw an exception for large integer inputs in 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.

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

Categories