0

I'm writing a programm which finds the largest number in a .txt file and outputs it. I'm trying to solve it myself but end up back at the same problem "The type of the expression must be an array type but it resolved to String"... For less confusion I'm using class files (Input/Output) from my school.

public class Zahlenstatistik {

        public static void main (String[] args) {

                    In.open("test.txt"); 
    String numbers = In.readFile();
    Integer max = Integer.MIN_VALUE;
    int i = 0;
    String[] alle_zahlen = numbers.split("\n");

    for(i = 0; i < alle_zahlen.length; i++)
        if (max < Integer.parseInt(alle_zahlen[i]))
            max = Integer.parseInt(alle_zahlen[i]);

    System.out.println("Die groeste Zahl ist: " + max);

        }

     }

Error:

Exception in thread "main" java.lang.NumberFormatException: For input string: "33"
at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at Zahlenstatistik.main(Zahlenstatistik.java:12)

test.txt file: 33 123 0 55 800 -55 -1 777

8
  • 5
    numbers[i] is wrong it is an string, you should use array[i] instead Commented May 16, 2017 at 1:07
  • Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 6 at Zahlenstatistik.main(Zahlenstatistik.java:12) when i replace it with array[i] Commented May 16, 2017 at 1:10
  • make it array.length - 1 instead of array.length, Because array.length property starts from 1 and your iteration starts from 0 Commented May 16, 2017 at 1:11
  • @user7790438 if you mean in loop limit, then no, i < array.length is correct; using i < array.length-1 would miss the last element. Commented May 16, 2017 at 1:55
  • 1
    The semicolon at the end of the for statement is wrong. It means the loop does nothing. The following if is not part of the loop and it should be. Removing the semicolon will make it so. Commented May 16, 2017 at 2:04

5 Answers 5

1

You have used numbers instead of array, where numbers is a String. Also, I would suggest using a better name than array for naming an array

Sign up to request clarification or add additional context in comments.

3 Comments

One should choose names for one's variables as carefully as if one were naming a first born child (Coplien, foreword to Clean Code)
@KevinO I like that analogy. Mind if I borrow it?
@KevinAnderson, the concept is in the foreword to the book Clean Code, but I think the actual words are just slightly different. So, go for it!
1

The question has mutated a bit, but here is a potential suggestion to resolve the invalid number format. Please note that file encoding may also play a role. It is also possible to strip other characters from the input via something like

String rawValue = alle_zahlen[i].replaceAll("[^-?\\d]+", "");

Also, good practice is to always use braces, so I've added them

for(i = 0; i < alle_zahlen.length; i++) {
  String rawValue = alle_zahlen[i].trim();
  try {
    int value = Integer.parseInt(rawValue);
    max = Math.max(max, value);
    // NOTE: instead of Math.max, can also do (which is essentially what
    //        Math.max() does)
    // max = max > value ? max : value;
  } //try
  catch (NumberFormatException e) {
    e.printStackTrace();
  }
} //for
System.out.println("Die groeste Zahl ist: " + max);

If you'd like to use Java 8 Streams, you could also do:

System.out.println("Die groeste Zahl ist: " +
      Arrays.stream(alle_zahlen)
        .mapToInt(s -> Integer.parseInt(s.replaceAll("[^-?\\d]+", "")))
        .max()
        .getAsInt());

Both approaches tested against a mock input of:

final String numbers = "33 \n123\n0\n55\n800\n-55\n-1\n777\n";
final String[] alle_zahlen = numbers.split("\\n");

Comments

0

This will work in Java 8:

    package com.sial.workarounds;
    import java.io.BufferedReader;
    import java.io.File;
    import java.io.FileReader;
    import java.io.IOException;
    import java.util.stream.Collectors;
    public class Zahlenstatistik {

    public static void main(String[] args) throws IOException {
        File f = new File("test.txt");
        BufferedReader reader = new BufferedReader(new FileReader(f));
        String numbers = String.join("\n", reader.lines().collect(Collectors.toList()));
        reader.close();
        Integer max = Integer.MIN_VALUE;
        int i = 0;
        String[] alle_zahlen = numbers.split("\n");

        for (i = 0; i < alle_zahlen.length; i++)
            if (max < Integer.parseInt(alle_zahlen[i]))
                max = Integer.parseInt(alle_zahlen[i]);

        System.out.println("Die groeste Zahl ist: " + max);

    }
}

1 Comment

this worked, now I need to know where the problem was :) thank you mate!
0

Since the compiler returns the error: The type of the expression must be an array type but it resolved to String, it is telling you that you are doing an action that expects an array but is getting a string. In this case, you are using a string in place of an array.

For instance, you are using numbers as an array when you write: max = Integer.parseInt(numbers[i]); and if (max < Integer.parseInt(numbers[i]));.

Instead, you should be using array.

Thus, you should change your code to max = Integer.parseInt(array[i]); and if (max < Integer.parseInt(array[i]));

Additionally, you should not have ; after your for loops or if statements. This changes how the statement is used, and it will just sit there and increment your variable without actually repeating anything. This ultimately caused your out of bounds exception.

2 Comments

thank you for your help :) ! but one thing is missing thank you @user7790438 "array.length -1" did the trick, holy shit finally :D. thank you very much everybody!
Thanks! I updated it. I didn't check myself to ensure that the fix was proper.
0

You should use a Stream of Integer

s.stream().reduce(Integer::max).get());

you can add .parallel if you want to.

1 Comment

Except that the original was O(n). This is less efficient.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.