0

I am new to java programming. My question is this I have a String array but when I want to use the contents in a calculation I keep getting the error:

Type mismatch: cannot convert from String to int

My code is:

    public void process(String data) {
        int i, x, length,avg;
        String[] parts = data.split("\r");
        for (i = 0; i < data.length(); i++) {
            x = parts[i];
            avg = avg+x;
            length = length + i;
        }
        averageRate = avg / (length+1);
    }
0

1 Answer 1

4

Using Integer.parseInt() should solve it.

public void process(String data) {
    int length = 0, avg = 0; // These need initialization
    String[] parts = data.split("\\r");
    for (int i = 0; i < data.length(); i++) {
        int x = Integer.parseInt(parts[i]); // Change is here
        avg = avg + x;
        length = length + i;
    }
    averageRate = x / (length + 1);
}
Sign up to request clarification or add additional context in comments.

2 Comments

Once I add Integer.parseInt() a new error appears: Exception in thread "main" java.lang.NumberFormatException: For input string: "1.29\r1.31\r1.30\r1.29\r1.30\r1.30\r1.31\r1.27\r1.28\r1.27\r1.25\r1.29\r" at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:67) at java.base/java.lang.Integer.parseInt(Integer.java:668) at java.base/java.lang.Integer.parseInt(Integer.java:786) at ERDataProcessor.process(ERDataProcessor.java:21) at CW1_3.main(CW1_3.java:58)
Then your String is not the proper format to be able to convert it to an Integer. Try formatting it first. Also, it looks to me that Double.parseDouble should be used, since the numbers in your String have decimals in them.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.