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);
    }
Ethan Fish
  • 19
  • 2

1 Answers1

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);
}
Robert
  • 7,394
  • 40
  • 45
  • 64
niklasenberg
  • 61
  • 1
  • 6
  • 1
    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) – Ethan Fish Feb 20 '22 at 21:10
  • 1
    Then your String is not the proper format to be able to convert it to an Integer. Try [formatting](https://stackoverflow.com/questions/10372862/java-string-remove-all-non-numeric-characters-but-keep-the-decimal-separator) it first. Also, it looks to me that Double.parseDouble should be used, since the numbers in your String have decimals in them. – niklasenberg Feb 20 '22 at 21:25