I’m trying to build a calculator without any operators that relate to the opration itself I try to solve (comparison operators and loops with operators are fine).
problem is, Eclipse is showing this in the console:
Exception in thread "main" java.lang.NumberFormatException: For input string: ""
at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at Calculator.addOne(Calculator.java:22)
at Calculator.add(Calculator.java:78)
at Program.main(Program.java:8)
And this is my code – Calculator class: http://pastebin.com/jLGe6atB
And my main() method:
public class Program {
public static void main(String[] args) {
Calculator calculator1 = new Calculator(8135, 6);
calculator1.add();
}
}
Can someone tell me what is the problem? (Please don’t ask why am I doing this, it’s just for fun)
Thanks and sorry for your time.
REQUEST: “post add() and addOne() here please:
public int addOne(int DigitArray)
{
String stringNum1 = Integer.toString(DigitArray);
String[] arrNum1 = stringNum1.split("");
int[] newArrNum1 = new int[arrNum1.length];
for (int i = 0; i < arrNum1.length; i++) {
newArrNum1[i] = Integer.parseInt(arrNum1[i]);
}
int lastDigit = newArrNum1[newArrNum1.length-1];
switch(lastDigit)
{
case 0:
lastDigit = 1;
System.out.println(lastDigit);
return lastDigit;
case 1:
lastDigit = 2;
System.out.println(lastDigit);
return lastDigit;
case 2:
lastDigit = 3;
System.out.println(lastDigit);
return lastDigit;
case 3:
lastDigit = 4;
System.out.println(lastDigit);
return lastDigit;
case 4:
lastDigit = 5;
System.out.println(lastDigit);
return lastDigit;
case 5:
lastDigit = 6;
System.out.println(lastDigit);
return lastDigit;
case 6:
lastDigit = 7;
System.out.println(lastDigit);
return lastDigit;
case 7:
lastDigit = 8;
System.out.println(lastDigit);
return lastDigit;
case 8:
lastDigit = 9;
System.out.println(lastDigit);
return lastDigit;
case 9:
lastDigit = 0;
updateNumberPlus(lastDigit, arrNum1, newArrNum1);
System.out.println(lastDigit);
return lastDigit;
default:
return lastDigit;
}
}
public int add()
{
int i = 0;
while(i <= num2)
{
i++;
this.addOne(num1);
if(i == num2)
{
result = 0;
System.out.print(result);
return result;
}
}
return result;
}
When you do a
String.split("")you will get an emptyStringelement as the first and last elements of yourArray.You then iterate over the array, calling
Integer.parseInt()on each element, which fails on the empty string elements.A simple hack would be to change your
forloop to look like;It’s a little ugly though 😛