0

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);
    }
}
0

4 Answers 4

4

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
Sign up to request clarification or add additional context in comments.

2 Comments

shouldn't this i > y be y < i.
@Karan Mer It does not make a difference if you write i > y or y < i. Is it a typo of you? The code does definitly work correct.
1

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

Comments

0

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

Comments

0
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...

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.