Search code examples
javastringparseint

Java parseInt from String, not able use array


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


Solution

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