This question already has answers here:
How to do an Integer.parseInt() for a decimal number?
(10 answers)
Closed 4 years ago.
System.out.println("Enter a number: ");
String in1 = input.nextLine();
Integer input1 = Integer.valueOf(in1);
Float input2 = Float.parseFloat(in1);
Double input3 = Double.valueOf(in1).doubleValue();
System.out.println();
System.out.println("Enter another number: ");
String in2 = input.nextLine();
Integer input21 = Integer.valueOf(in2);
Float input22 = Float.parseFloat(in2);
Double input23 = Double.valueOf(in2).doubleValue();
FloatN fco = new FloatN();
System.out.println();
System.out.println("The sum of both of your numbers is: " + fco.add(input2, input22));
done = true;
I'm well aware that this program is completely impractical, I only wrote it to practice parsing, generics, and interfaces. I tried Integer, which worked fine, but upon trying the Float and Double.add() functions, I get 3 errors:
at java.lang.NumberFormatException.forInputString
at java.lang.Integer.parseInt
at java.lang.Integer.valueOf
I removed the Integer parsers, and the program worked fine. I'm confused as to why I get the errors only when I enter Decimal values and would like someone to help point out what exactly is causing the exception so I can avoid any errors like this in the future, and since removing the Integer parser removes any functionality from the IntegerN class.
Also, if anyone needs the FloatN class for whatever reason:
public static class FloatN implements Summization<Float>{
public FloatN(){}
public Float add(Float a, Float b)
{
return a + b;
}
}
Summization is a generic interface with an add() method.
Thanks in advance.
If you enter a decimal value as input, Integer.parseInt() method won't be able to parse it. If you still want to have them all in your code, you have to get int value of that Float value. You can use intValue() method:
Float input2 = Float.parseFloat(in1);
Integer input1 = Integer.valueOf(input2.intValue());
Maybe add string which is not contain a parsable float or it is null.
From javadoc:
NullPointerException - if the string is null
NumberFormatException - if the string does not contain a parsable float.
becuase Integer.valueOf(in2); this line will give NumberFormatException with float and double you can use
Number num = NumberFormat.getInstance().parse(myNumber);
see # http://docs.oracle.com/javase/7/docs/api/java/text/NumberFormat.html
The NumberFormatException comes in the Integer parser, and not in the Double and Float parsers if input contains decimal.
In such situations, you can get the the integer part of the decimal number using split and parse:
String[] s = in1.split("\\.");
Integer input1 = Integer.valueOf(s[0]);
Float input2 = Float.parseFloat(in1);
Double input3 = Double.valueOf(in1).doubleValue();
Related
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.
I'm a beginner in java. And I don't have ability of complex coding in java.
I want to make a program to solve mathematical expression given in string form which must contain only numbers and four basic arithmetic operators.
I have written the below code with the little basics that I know. But when i run the code, it shows error. It says i can't parse object into double and so on...
I have tried to give precedence for four basic operators according to BODMAS rule.
But i don't know how to give precedence for brackets if the user encloses the expression within brackets.
the below code might seem funny for experts those who can make it with just a few lines, but I am really a beginner.
Here is the code that i made:
(comments are not written as this code is simple and anyone can understand)
import java.util.*;
import java.util.concurrent.TimeUnit;
class Calculator
{
public static void main(String[] args)
throws Exception
{
int aaa =0;
while(aaa==0){
Scanner sc = new Scanner(System.in);
System.out.println("\nEnter expression to solve : ");
String expression = sc.nextLine();
if(!expression.isEmpty()){
int charlength = expression.length();
String charat0 = ""+expression.charAt(0);
String charatlast = ""+expression.charAt(charlength-1);
ArrayList forops = new ArrayList();
ArrayList forchars = new ArrayList();
if(expression.contains(" ")){
pWD("\nSpaces are not allowed",TimeUnit.MILLISECONDS,30);
}else if(!expression.matches("[-+/*0-9]+")){
pWD("\nEnter only numbers and operators",TimeUnit.MILLISECONDS,30);
}else if(!charat0.matches("[0-9]+")||!charatlast.matches("[0-9]+")){
pWD("first and last characters must be\nnumbers",TimeUnit.MILLISECONDS,30);
}else if(expression.contains("//")||expression.contains("**")||expression.contains("--")||expression.contains("++")||
expression.contains("/+")||expression.contains("*/")||expression.contains("-*")||expression.contains("+-")||
expression.contains("/-")||expression.contains("*+")||expression.contains("-/")||expression.contains("+*")||
expression.contains("/*")||expression.contains("*-")||expression.contains("-+")||expression.contains("+/")){
pWD("There must be SINGLE operator between\ntwo adjacent numbers",TimeUnit.MILLISECONDS,30);
}else{
String[] chararr = expression.split("(?<=[-+*/])|(?=[-+*/])");
int chararrl =chararr.length;
for(int nn=0;nn<chararrl;nn++){
forchars.add(chararr[nn]);
}for(int mn=0;mn<chararrl;mn+=2){
String willparse = ""+forchars.get(mn);
double parseint= Double.parseDouble(willparse);
forchars.set(mn,parseint);
}while(forchars.contains("/")){
int divindex = forchars.indexOf("/");
double prediv = forchars.get(divindex-1);
double nexdiv = forchars.get(divindex+1);
forchars.set(divindex,(prediv/nexdiv));
forchars.remove(forchars.indexOf(prediv));
forchars.remove(forchars.indexOf(nexdiv));
}while(forchars.contains("*")){
int mulindex = forchars.indexOf("*");
double premul = forchars.get(mulindex-1);
double nexmul = forchars.get(mulindex+1);
forchars.set(mulindex,(premul*nexmul));
forchars.remove(forchars.indexOf(premul));
forchars.remove(forchars.indexOf(nexmul));
}while(forchars.contains("-")){
int subindex = forchars.indexOf("-");
double presub = forchars.get(subindex-1);
double nexsub = forchars.get(subindex+1);
forchars.set(subindex,(presub-nexsub));
forchars.remove(forchars.indexOf(presub));
forchars.remove(forchars.indexOf(nexsub));
}while(forchars.contains("+")){
int addindex = forchars.indexOf("+");
double preadd = forchars.get(addindex-1);
double nexadd = forchars.get(addindex+1);
forchars.set(addindex,(preadd+nexadd));
forchars.remove(forchars.indexOf(preadd));
forchars.remove(forchars.indexOf(nexadd));}
double answer1 = forchars.get(0);
String answer = Double.toString(answer1);
pWD("\nFinal answer is : "+answer,TimeUnit.MILLISECONDS,80);
}}else{
pWD("Please enter something",TimeUnit.MILLISECONDS,30);
}}
}public static void pWD(String data, TimeUnit unit, long delay)
throws InterruptedException {
for (char ch:data.toCharArray()) {
System.out.print(ch);
unit.sleep(delay);
}
}
}
Please help me how to fix the error of parsing into double.
And explain me in a little detail on how to solve expression if user encloses the expression in brackets.
Thank You.
Since you are declaring a double variable, you cannot assign an int value to it. So I assume the best option you should have is to:
cast your int to double
double prediv = (double) forchars.get(divindex - 1);
It is just the type mismatch which you should take into account.
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();
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
}
I'm having a problem when trying to run my program. What my program is supposed to do is to receive a number and compare it to an int. I understand that the program thinks that I'm trying to compare String with an int and not happy about it. What can I do?
import java.util.Scanner;
public class C {
public static void main(String args[]) {
Scanner input = new Scanner (System.in);
String age = input.nextLine();
if (age < 50){
System.out.println("You are young");
}else{
System.out.println("You are old");
}
}
}
You cannot compare a String to an int using a numerical comparison-operator. §15.20.1 of the Java Language Specification describes exactly what you are seeing:
The type of each of the operands of a numerical comparison operator must be a type that is convertible (§5.1.8) to a primitive numeric type, or a compile-time error occurs.
Since String is not convertible to a primitive numeric-type, you cannot compare it against an integer. Therefore you have two options:
You can convert the String into an int using Integer#parseInt:
int age = Integer.parseInt(ageString);
But in your case, since you are already reading in input, it would be better to bypass the whole parseInt bit and read in an int directly:
int age = input.nextInt();
Keep in mind though that you still have to deal with the possibility of invalid input.
You need age to be an integer in order to compare it to 50.
You have two options :
int age = input.nextInt();
or
int age = Integer.parseInt(input.nextLine());
Note that both options would throw exceptions if the input you enter is not an integer.
Before comparing you need to convert it to integer using parseInt().
You need to parse the String as an Integer.
String age = input.nextLine();
if (Integer.parseInt(age) < 50) {
System.out.println("You are young");
}
The scanner class actually has an input method called nextInt() that you can use:
Scanner input = new Scanner(System.in);
int age = input.nextInt();
// Comparisons
You cannot compare a String and a int values using "<",">","<=",">=" operators. That is the problem with your code. to fix that you can either,
take input from the user as int by replacing the line 5 as int age = input.nextInt();
or you can convert your age String to integer after taking inputs from the user using something like this int intage=Integer.parseInt(age);. Then you can replace your age variable with intage variable