mercredi 29 juillet 2020

Java wrong value when reading from website

I'm trying to make a programm, wich gets a word from a website, wich always gives you a random (german) word and count how frequently a character is in the word. When I try my programm with a stream from a list it works fine. If I read from the website, the word is displayed fine with System.out, but counting the letters does not work as intended. Here is my code:

public class WordCount {

  public static String charStat(String urlString) throws IOException {

/*    List<String> list = new ArrayList<>();
    list.add("word");
    Stream<String> characterStream = list.stream();*/ //works totaly fine every time

    URL url = new URL(urlString);
    Stream<String> characterStream = new BufferedReader(new InputStreamReader(url.openStream())).lines();

    BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream()));
    System.out.println(br.readLine());//BufferedReader only used to print the word so I can controll
                                      //if everything is working

    int[] charNumber = new int[26];//size is 26 cause the alphabet has 26 characters

    Runnable func = () -> {
      characterStream
          .map(String::toLowerCase)
          .flatMapToInt(CharSequence::chars)
          .filter(c -> c != ' ')
          .map(c -> c - (int) 'a')//subtracting 'a'(95 in ascii) so a is in position 0 of the array
          .forEach(i -> {charNumber[i]++;});
    };

    func.run();
    characterStream.close();
    return "a: " + charNumber[0];//returning how many times the letter a is present, could be any letter
  }

  public static void main(String[] args) throws IOException {//Ik that main shouldn't throw an exception
    System.out.println(charStat("https://randomeword.azurewebsites.net/api/word"));//the website im
                                                                                   //getting the word from
  }
}

Example from a fail:

word:

Klavierkonzert

the array:

[1, 0, 0, 0, 3, 0, 2, 0, 1, 0, 0, 0, 0, 3, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 1]

the should be:

[1, 0, 0, 0, 2, 0, 0, 0, 1, 0, 2, 1, 0, 1, 1, 0, 0, 2, 0, 1, 0, 1, 0, 0, 0, 1]

I don't know why this is happening as the word gets shown correctly with System.out.println();. So if I've done anything wrong let me know.




Aucun commentaire:

Enregistrer un commentaire