How to fix this issue?
java.lang.NumberFormatException: at java.lang.NumberFormatException.forInputString(Unknown Source)
I am doing some example problem and my code is working fine for the first string and digit. (Commented one)
But when change the new string and digit (Current one) I am getting this error :
java.lang.NumberFormatException: For input string: "299858953917872714814599237991174513476623756395992135212546127959342974628712329595771672911914471"
at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Long.parseLong(Unknown Source)
at java.lang.Long.parseLong(Unknown Source)
at com.codejam.q1.problems.maxResult.removeDigit(maxResult.java:21)
at com.codejam.q1.problems.maxResult.main(maxResult.java:10)
Here is my code. Anywhere I am missing something ?
public class maxResult {
public static void main(String[] args) {
//String str = "1231";
String str = "2998589353917872714814599237991174513476623756395992135212546127959342974628712329595771672911914471";
//char digit = '1';
char digit = '3';
System.out.println(removeDigit(str,digit));
}
public static String removeDigit(String number, char digit) {
long result = 0;
for(int i = 0; i<number.length(); i++) {
char num = number.charAt(i);
if(num == digit) {
String myStr = number.substring(0, i) + number.substring(i + 1);
try{
long myNum = Long.parseLong(myStr);
if(myNum > result) {
result = myNum;
}
}
catch (NumberFormatException ex){
ex.printStackTrace();
}
}
}
String s = String.valueOf(result);
return s;
}
}
Even though I change int to long but no change in result.
Your number is too big for a long value. The maximum long value is 9,223,372,036,854,775,807. You can use BigInteger, which essentially has no limit.
Using long
long result = 0;
// ...
long myNum = Long.parseLong(myStr);
if(myNum > result) {
result = myNum;
}
// ...
String s = String.valueOf(result);
return s;
Using BigInteger
import java.math.BigInteger;
// ...
BigInteger result = BigInteger.ZERO;
// ...
BigInteger myNum = new BigInteger(myStr);
result = myNum.max(result);
// ...
return result.toString();
The number is too long for a long. Longs go from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,808.
Try doing this :
public static String removeDigit(String number, char digit) {
double temp = 0;
String result="";
for(int i = 0; i<number.length(); i++) {
char num = number.charAt(i);
if(num == digit) {
String myStr = number.substring(0, i) + number.substring(i + 1);
try{
double myNum = Double.parseDouble(myStr);
if(myNum > temp) {
temp = myNum;
result=myStr;
}
}
catch (NumberFormatException ex){
ex.printStackTrace();
}
}
}
return result;
}
The problem you get is that you are exceeding the limit of the int and the long. Let us see the limits of some number storing types and then use the best one:
Type
Size
Value
Exceeds
int
32 bit
-2,147,483,648 to 2,147,483,647
Yes
long
64 bit
-9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
Yes
float
32 bit
3.40282347 x 1038 to 1.40239846 x 10-45
Yes
double
64 bit
1.7976931348623157 x 10308 to 4.9406564584124654 x 10-324
Yes
BigInteger
32 bit
2^64billion
No
Here, we find that BigInteger is the class we need to use. So, instead of using a long or int for it, use BigInteger. To know more about BigInteger, visit here.
Also to know how to use a big integers refer to the answer here
You can use BigDecimal instead of long.
public class Application {
public static void main(String[] args) {
//String str = "1231";
String str = "2998589353917872714814599237991174513476623756395992135212546127959342974628712329595771672911914471";
//char digit = '1';
char digit = '3';
System.out.println(removeDigit(str,digit));
}
public static BigDecimal removeDigit(String number, char digit) {
BigDecimal result = BigDecimal.ZERO;
for(int i = 0; i<number.length(); i++) {
char num = number.charAt(i);
if(num == digit) {
String myStr = number.substring(0, i) + number.substring(i + 1);
try{
BigDecimal myNum = new BigDecimal(myStr);
if(myNum.compareTo(result)>0) {
result = myNum;
}
}
catch (NumberFormatException ex){
ex.printStackTrace();
}
}
}
return result;
}
}
Related
I try to convert numbers of a String in to an array with the datatyp char. My problem is, that the number in my array is everytime 48 to high. I also know that the problem has something to do with ASCII table. What can i do to solve this problem?
package Test;
public class Main {
public static void main(String[] args) {
int iNumber = 0; int indexNumber = 0;
String calculation = "5+8";
int lengthCalculation = calculation.length();
int[] number= new int[lengthCalculation/2+1];
while(iNumber < lengthCalculation) {
number[indexNumber] = calculation.charAt(iNumber);;
iNumber+=2;
indexNumber++;
}
for(int q : number) {
System.out.println(q); }
}
}
use
number[indexNumber] = calculation.charAt(iNumber) - '0';
Digit 0 has an ASCII value of 48. The range of ASCII value for 0-9 digits is from 48-57. So, whenever you extract a character, let's say '5', you store 53 instead of 5 in the array. So try to use the below code modification where you subtract character '0':
public static void main(String[] args) {
int iNumber = 0; int indexNumber = 0;
String calculation = "5+8";
int lengthCalculation = calculation.length();
int[] number= new int[lengthCalculation/2+1];
while(iNumber < lengthCalculation) {
number[indexNumber] = calculation.charAt(iNumber)-'0'; //modified
iNumber+=2;
indexNumber++;
}
for(int q : number) {
System.out.println(q); }
}
This is for a fraction class. When i test the fraction class with a string like "2/4" I get the following exception:
java.lang.NumberFormatException: For input string: "".
I think it has something to do with the sStringTo method when trying to replace spaces.
public class Util{
static int findGCF(int a, int b){
a = Math.abs(a);
b = Math.abs(b);
while(a != b){
if (a>b) a = a-b; else b = b-a;
}
return (a);
}
static Fraction sIntTo(String s){ //"2"
int n = Integer.parseInt(s);
return new Fraction(n);
}
static Fraction sFractionTo(String s){ //"2/3"
s = s.trim();
int posSlash = s.indexOf("/");
int n = Integer.parseInt(s.substring(0,posSlash));
int m = Integer.parseInt(s.substring(posSlash + 1));
return new Fraction(n,m);
}
static Fraction sMixTo(String s){
s =s.trim();
int posB = s.indexOf(" ");
int posSlash = s.indexOf("/");
int w = Integer.parseInt(s.substring(0,posB));
int t = Integer.parseInt(s.substring(posB+1, posSlash));
int b = Integer.parseInt(s.substring(posSlash+1));
return new Fraction(w*b+t,b);
}
static Fraction sDecTo(String s){
s = s.trim();
int i = s.indexOf(".");
String sub = s.substring(i+1);
String sNoPeriod = s.substring(0,i) + sub;
int top = Integer.parseInt(sNoPeriod);
int bot = 1;
for(int j = 0; j<sub.length(); j++) bot = bot*10;
return new Fraction(top,bot);
}
static Fraction divFraction(Fraction f, Fraction g){
return new Fraction (f.num * g.den, f.den * g.num);
}
static Fraction addFraction(Fraction f, Fraction g){
return new Fraction (f.num * g.den + f.den * g.num, f.den*g.den);
}
static Fraction sStringTo(String s){
s=s.trim();
s= s.replaceAll("\\s*/\\S*", "/");// remove 0 or more blanks before & after slash
s = s.replaceAll("\\s+", " "); // all blanks to be one blank: 2 1/2
int posB = s.indexOf(" ");
int posSlash = s.indexOf("/");
int posPed = s.indexOf(".");
Fraction ans = null;
if(posB>-1){
if (posSlash>posB) { ans = sMixTo(s);}
}else{
if (posPed == -1 && posSlash == -1) ans = sIntTo(s); //integer only
else{
if(posSlash == -1) ans = sDecTo(s);// decimal only
else{
//with slash "2.1/2 2.1/2.1
Fraction f = sStringTo(s.substring(0,posSlash));
Fraction g = sStringTo(s.substring(posSlash+1));
ans = divFraction(f,g);
}
}
}
return ans;
}//sStringTo()
The problematic stack trace is:
Exception in thread "main" java.lang.NumberFormatException: For input string: ""
at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.base/java.lang.Integer.parseInt(Integer.java:662)
at java.base/java.lang.Integer.parseInt(Integer.java:770)
at Util.sIntTo(Util.java:17)
at Util.sStringTo(Util.java:75)
at Util.sStringTo(Util.java:81)
at Fraction.<init>(Fraction.java:31)
at Test.main(Test.java:6)
It looks like you are passing a string containing only whitespace into sIntTo(). You should consider just removing all whitespace, rather than just reducing it to a single space. Consider changing s = s.replaceAll("\\s+", " "); to s = s.replaceAll("\\s+", "");.
I figured out the problem. It was a syntax error on my part.
I have this input like
String s = "6" , ss="99 , sss = "99999";
i need to store these values in an int reference variable ,
without using Integer.parseInt
any suggestion ? , no full code , just the hints ??
What about Scanner?
int a=new Scanner(s).nextInt();
Without util.
public static int parseInt(String s)
{
int ans=0;
for(int i=s.length()-1;i>=0;i--)
{
ans+=(s.charAt(i)-'0');
ans*=10;
}
return ans/10;
}
public class MyStringToNumber {
public static int convert_String_To_Number(String numStr){
char ch[] = numStr.toCharArray();
int sum = 0;
//get ascii value for zero
int zeroAscii = (int)'0';
for(char c:ch){
int tmpAscii = (int)c;
sum = (sum*10)+(tmpAscii-zeroAscii);
}
return sum;
}
public static void main(String a[]){
System.out.println("\"3256\" == "+convert_String_To_Number("3256"));
System.out.println("\"76289\" == "+convert_String_To_Number("76289"));
System.out.println("\"90087\" == "+convert_String_To_Number("90087"));
}
}
See more at this URL.
Try to get each char from the string and then the value of each char. 0 has a value of 48 so
char c = '9';
int i = c - 48;
Now i = 9. After that you only need to multiply this value with the appropriate power of 10 and add it to the total
public class ConvertIntoInt {
public static void main(String []args) {
String numStr = "3256";
char ch[] = numStr.toCharArray();
int sum = 0;
// Get ASCII value for zero
int zeroAscii = (int)'0';
for (char c:ch) {
int tmpAscii = (int)c;
System.out.println("Temp Ascii:" + tmpAscii);
sum = (sum * 10) + (tmpAscii - zeroAscii);
System.out.println(sum);
}
System.out.println(sum);
}
}
Is it possible in Java to efficiently read an integer from random position of the string? For instance, I have a
String s = "(34";
if (s.charAt(0) == '(')
{
// How to read a number from position = 1 to the end of the string?
// Of course, I can do something like
String s1 = s.substring(1);
int val = Integer.parseInt(s1);
}
but it dynamically creates a new instance of string and seems to be too slow and performance hitting.
UPDATE
Well, to be precise: I have an array of strings in form "(ddd" where d is a digit. So I do know that a number starts always from pos = 1. How do I efficently read these numbers?
Integer.parseInt(s1.replaceAll("[\\D]", ""))
Answered before the update:
I'm not an expert in regex, but hope this "\\d+" is useful to you. Invoke the below method with pattern: "\\d+".
public static int returnInt(String pattern,String inputString){
Pattern intPattern = Pattern.compile(pattern);
Matcher matcher = intPattern.matcher(inputString);
matcher.find();
String input = matcher.group();
return Integer.parseInt(input);
}
Answered after the update:
String is a final object, you cannot edit it, so if you want to get some digit value from it, you have the 2 ways:
1. Use your code, that will work fine, but if you care about performance, try 2nd way.
2. Divide your string on digits and add them to get the result:
public static void main(String[] args) {
String input = "(123456";
if(input.charAt(0) == '(') {
System.out.println(getDigit(input));
}
}
private static int getDigit(String s) {
int result = 0;
int increase = 10;
for(int i = 1; i < s.length(); i++) {
int digit = Character.getNumericValue(s.charAt(i));
result*=increase;
result += digit;
}
return result;
}
Output:
123456
If you don't want to allocate a new String then you can use the code in this other SO answer:
int charArrayToInt(char[] data, int start, int end) throws NumberFormatException {
int result = 0;
for (int i = start; i < end; i++) {
int digit = ((int)data[i] & 0xF);
if ((digit < 0) || (digit > 9)) throw new NumberFormatException();
result *= 10;
result += digit;
}
return result;
}
You can call it with charArrayToInt(s.toCharArray(), 1, s.length())
In this code fragment, I can't sum a and b:
String a = "10";
String b = "20";
JOptionPane.showMessageDialog(null,a+b);
Since a and b are defined as String, this code will concatenate the strings and output 10+20=1020.
How can I get it to instead sum a and b and output 10+20=30?
Java provides parse methods for Primitive Types. So depending on your input you can use Integer.parseInt, Double.parseDouble or others.
String result;
try{
int value = Integer.parseInt(a)+Integer.parseInt(b);
result = String. valueOf(value) ;
}catch(NumberFormatException ex){
//either a or b is not a number
result = "Invalid input";
}
JOptionPane.showMessageDialog(null,result);
Because you want to concat Strings they won't add up. You have to parse them to an Integer which works like:
Integer.parseInt(a) + Integer.parseInt(b)
To sum this up + concats Strings and doesn't add them up.
use BigInteger class to perform largely in length string addition operation.
BigInteger big = new BigInteger("77777777777777777777888888888888888888888888888856666666666666666666666666666666");
BigInteger big1 = new BigInteger("99999999999999995455555555555555556");
BigInteger big3 = big.add(big1);
try: Integer.parseInt(a)+Integer.parseInt(b)
String a= txtnum1.getText();
String b= txtnum2.getText();
JOptionPane.showMessageDialog(null,Integer.parseInt(a)+Integer.parseInt(b));
public void actionPerformed(ActionEvent arg0)
{
String a= txtnum1.getText();
String b= txtnum2.getText();
String result = "";
try{
int value = Integer.parseInt(a)+Integer.parseInt(b);
result = ""+value;
}catch(NumberFormatException ex){
result = "Invalid input";
}
JOptionPane.showMessageDialog(null,result);
}
it is work
Integer wrapper class has constructor which takes String parameter representing numbers.
String a= txtnum1.getText();//a="100"
String b= txtnum2.getText();//b="200"
Integer result;
int result_1;
String result_2;
try{
result = new Integer(a) + new Integer(b); // here variables a and b are Strings representing numbers. If not numbers, then new Integer(String) will throw number format exception.
int result_1=result.intValue();//convert to primitive datatype int if required.
result_2 = ""+result; //or result_2 = ""+result_1; both will work to convert in String format
}catch(NumberFormatException ex){
//if either a or b are Strings not representing numbers
result_2 = "Invalid input";
}
We can change string to BigInteger and then sum its values.
import java.util.*;
import java.math.*;
class stack
{
public static void main(String args[])
{
Scanner s=new Scanner(System.in);
String aa=s.next();
String bb=s.next();
BigInteger a=new BigInteger(aa);
BigInteger b=new BigInteger(bb);
System.out.println(a.add(b));
}
}
Since + is used to concat strings, you can't use it to add two strings containing number. But subtraction works perfectly fine with such strings. Hence, you can use this basic mathematical concept to make that possible:
a-(-b)
Integer.parseInt() is used to convert String to Integer.In order to perform sum of two strings first strings need to be converted to Integers and then need to perform sum otherwise it just concatenates two strings instead of performing sum.
String a = "10";
String b = "20";
JOptionPane.showMessageDialog(null,Integer.parseInt(a)+Integer.parseInt(b));
public String addTwoNumbers(final String n1, final String n2) {
StringBuilder sb = new StringBuilder();
int carry =0;
byte[] nb1; byte[] nb2;
if (n1.length() > n2.length()){
nb1 = n1.getBytes();
nb2 = n2.getBytes();
} else {
nb2 = n1.getBytes();
nb1 = n2.getBytes();
}
int maxLen=n1.length()>=n2.length()?n1.length():n2.length();
for (int i = 1; i <= maxLen ; i++) {
int a = nb1.length-i >= 0 ? nb1[nb1.length-i] - 48 : 0;
int b = nb2.length-i >= 0 ? nb2[nb2.length-i] - 48 : 0;
int result = a + b + carry;
if (result >= 10){
carry = 1;
result = result-10;
} else {
carry = 0;
}
sb.insert(0, result);
}
if(carry>0){
sb.insert(0, carry);
}
return sb.toString();
}