0

I am unsure of how this code works with the (count % 2 == 1) and what the output is supposed to be according to it. Any clarification would be great!

Scanner s = new Scanner("d 1 o 2 g 3 c 7 t");
int count = 0;
while(s.hasNext())
{
if (count % 2 == 1)
System.out.print(s.next() + " ");
else
s.next();
count++;
}
Robert Bruce
  • 1,048
  • 1
  • 12
  • 14

2 Answers2

1

The "%" is the remainder (aka modulo) operator, which gives the remainder of a division. It returns 0 when the number is exactly divisible by 2 (an even number) and 1 when not (an odd number).

So, with your code using "if (count % 2 == 1)...", it is looking for odd numbers (your "count" variable) and therefore the output would be: "1 2 3 7 ".

You can verify the output using an online Java compiler: https://www.tutorialspoint.com/compile_java_online.php (if you use it, make sure you add "import java.util.Scanner;" at the top of the code)

I know it may be confusing as you might think "d" should be an odd number as it's the first item in the string, but your count variable starts at 0 (which is the "d" position), and also because spaces are effectively disregarded due to the Scanner.next() method. So, really, you can think of the string as "d1o2g3c7t", and now you can more easily see the "1237" as being the odd positions.

Hope this helps!

Robert Bruce
  • 1,048
  • 1
  • 12
  • 14
0

count % 2 is essentially long division and yields the remainder. 5 % 2 is 1. 6 % 3 is 0. So whatever the remainder would be of the first number divided by the second number.

Matthew Gaiser
  • 3,740
  • 1
  • 10
  • 24