Ridi
Ridi

Reputation: 3

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

Upvotes: 0

Views: 833

Answers (5)

KevinO
KevinO

Reputation: 4403

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

Upvotes: 1

Tomin
Tomin

Reputation: 2028

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

    }
}

Upvotes: 0

SmokedMeat
SmokedMeat

Reputation: 48

You should use a Stream of Integer

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

you can add .parallel if you want to.

Upvotes: 0

Drone6251
Drone6251

Reputation: 128

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.

Upvotes: 0

slal
slal

Reputation: 2867

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

Upvotes: 1

Related Questions