0

I'm new to Java and I need to create a method checking that byte stream contains even number. I've already written some code, but I think it's horrible, and don't know how to test it. It seems to me there is some short and efficient way to do that check...

public boolean isNumber(InputStream in) {
    boolean evenNum = false;
    BufferedReader reader = new BufferedReader(new InputStreamReader(in));
    String input;
    int num;
    try {
        input = reader.readLine();
        num = Integer.parseInt(input);
        if (num % 2 == 0) {
            evenNum = true;
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    return evenNum;
}
Nicolas Filotto
  • 43,537
  • 11
  • 94
  • 122
aLittleMind
  • 183
  • 2
  • 3
  • 12
  • This will check if the first line of the input stream matches with an even integer (using the default encoding while reading), is it what you want? – Nicolas Filotto Nov 15 '16 at 14:38
  • My task is "check that byte stream contains even number". But InputStream is abstract, I don't know that to do with it. – aLittleMind Nov 15 '16 at 14:43
  • I see no byte stream in this code - unless you mean the InputStream, in which case wrapping it with a `Reader` sort of hides the fact that it inputs bytes. Do you mean that you are looking for an even byte in an input stream, or do you mean a different kind of byte stream, or do you mean just textual input that has numbers made of digits? – RealSkeptic Nov 15 '16 at 14:44
  • Ah. It's a homework task. Why don't you ask your tutor exactly what he or she means? – RealSkeptic Nov 15 '16 at 14:45
  • I mean, that we have some input. It may be some text from keyboard or a file, and we have reference to it - in. (InputStream in). So, I need to check, that data contains even number. But InputStream is abstract. I dont know what to do with it – aLittleMind Nov 15 '16 at 14:52
  • The real question is: Is it working? – Nicolas Filotto Nov 15 '16 at 14:56
  • Because InputStream is abstract, when you call your `isNumber` method the actual Stream that you're capturing the input from will be cast to an InputStream, allowing you to work with `in` without having to worry about where it came from. – Graham Nicol Nov 15 '16 at 15:02
  • I think you need some clarification for this question. InputStream contains a stream of bytes. You can read those bytes and translate them to characters, or lines. Then, you can go over each word (word = chars with no space between them) and decide if any of them is even. If you find one, return true. But you need to know if you need to break the loop once you find one, otherwise, you can read the input forever, or at least you get EOF. – Elad Tabak Nov 15 '16 at 15:19

0 Answers0