java program outputting even/odd numbers -
java program outputting even/odd numbers -
my task write java programme first asks user how many numbers inputted, outputs how many odd , numbers entered. restricted ints 0-100. question is: missing in code?
import java.util.scanner; public class clancy_lab_06_03 { public static void main(string[] args) { scanner input = new scanner(system.in); int n; system.out.println("how many numbers entered?"); n = input.nextint(); while (n < 0 || n > 100) { system.out.println("error! valid range 0-100. re-enter:"); n = input.nextint(); n++; } int odd = 0; int = 0; while (n >= 0 || n <= 100) { n = input.nextint(); if (n % 2 == 0) { even++; } else { odd++; } } system.out.println(even + "even" + odd + "odd"); } }
second while loop infinite. relplace this:
for (int = 0; < n; i++) { int b = input.nextint(); if (b % 2 == 0) { even++; } else { odd++; } }
also don't understand why incrementing n
in first loop. illustration when first give -5
, asked re-enter number. type -1
, gets incremented , in fact programme processes 0
, altough user typed -1
. in sentiment not how suppose work , should remove n++
.
as asked in comment - same using while
loop:
while(n > 0) { n--; int b = input.nextint(); if (b % 2 == 0) { even++; } else { odd++; } }
also thought close input
when no longer need (for illustration @ end of main method)
input.close();
java
Comments
Post a Comment