Reputation: 49
What is wrong with this code? It says cannot convert from String to int
, but I have already converted it.
public static void main(String[] args) {
String x = JOptionPane.showInputDialog(null, "Hur många värden haver du?");
int i = Integer.parseInt(x);
for (int y = 0; i >= y; y++) {
String z = JOptionPane.showInputDialog(null, "Skriv in värdet");
int sum = Integer.parseInt(z);
sum = (sum + z);
}
}
Upvotes: 0
Views: 234
Reputation: 121
int sum = 0;
for (int y = 0; i >= y; y++) {
try{
String z = JOptionPane.showInputDialog(null, "Skriv in värdet");
sum = (sum + Integer.parseInt(z));
} catch (Exception e){
System.out.println("This was not an Integer: " + z);
}
}
The exception will prevent your program from crashing, but it will not screw up your 'sum'. So you can put an other value again, and go on...
Upvotes: 0
Reputation: 6887
No you have converted z
to int
and store the result in sum
so sum
is the int
value of z
but z
is still a variable of type String
. What you are trying to do here is the same as multiplying sum by two.
But i assum you want to sum all input values, so you can do sum = (sum + Integer.parseInt(z));
and put the declaration of sum
outside the loop, otherwise you initialize it on every iteration. Another bug is that if you input x
it will iterate x + 1
times because of i >= y
. Fixed version below.
String x = JOptionPane.showInputDialog(null, "Hur många värden haver du?");
int i = Integer.parseInt(x);
int sum = 0;
for (int y = 0; i > y; y++)
{
String z = JOptionPane.showInputDialog(null, "Skriv in värdet");
sum = (sum + Integer.parseInt(z));
}
System.out.println(sum);
Input: 3 (number of iterations)
Input: 7
Input: 5
Input: 6
Output: 18
Upvotes: 4
Reputation: 430
Java don't do automatic conversion between types. So you can't add Strings with numbers and expect it to do math.
What Java does do it auto boxing of primitive types to objects. And it will automatically attempt to call toString() on objects if you use it in a String concatenation.
So as Reimeus wrote. You need to convert the String to a number before you start using it in math
Upvotes: 1
Reputation: 6515
Cannot convert from String to int
sum=(sum+z) // int+string // this was the problem
change your z to int as:
int iz= Integer.parseInt(z);
sum = (sum + iz);
Upvotes: 0