I have a task:

Implement service boolean isNumber (InputStream in); method should check. that an even number is written in the byte stream. All streams must be wrapped via try-resources. Even if it is a ByteArrayInputStream

Help solve.

Closed due to the fact that the essence of the question is not clear by the participants Alex , pavel , user194374, Nick Volynkin 5 Dec '16 at 5:59 .

Try to write more detailed questions. To get an answer, explain what exactly you see the problem, how to reproduce it, what you want to get as a result, etc. Give an example that clearly demonstrates the problem. If the question can be reformulated according to the rules set out in the certificate , edit it .

  • 2
    Have you ever tried to do something? We can prompt, help, suggest. And so it turns out that you came for a ready-made solution. - user3841429
  • Yes, unfortunately, they didn’t accept my version at all, so I didn’t even write it here so that they wouldn’t have any variations on the fact that it isn’t necessary at the base ... This is the answer for the code. 1. Delete all code for this task. You need to read the inputstream into a string. 2. Turn the string to Integer.parseInt 3. And check the parity. - Pavel

1 answer 1

So?

private boolean isNumber(InputStream inputStream) throws IOException { try { byte[] number = new byte[4];//Массив с размером 4 байта (т.к. int = 4 байта) inputStream.read(number);//Читаем 4 байта в массив ByteBuffer bb = ByteBuffer.wrap(number);//Врапаем в байт буффер int numberInIS = bb.getInt();//Получаем число if (numberInIS % 2 == 0)//проверяем на четность { System.out.println("[isNumber]: number = "+numberInIS+"; is true"); return true; } else { System.out.println("[isNumber]: number = "+numberInIS+"; is false"); return false; } } catch (IOException e) { e.printStackTrace();//не удалось считать из inputStream throw new IOException("Can't read from "+inputStream); } finally { inputStream.close();//закрываем поток } } 

If an even number arrives, for example, the number 128, then the output is true :

 [isNumber]: number = 128; is true 

If an odd number arrives, for example 821, it returns false :

 [isNumber]: number = 821; is false