I have a programming question that I need a little help with This is what I need
ID: 3821630 • Letter: I
Question
I have a programming question that I need a little help with
This is what I need to do:
Write a Java program that first asks the user how many numbers will be entered - let's call this positive integer n. Then the program takes input n integers (not ordered) and outputs how many even values and how many odd values have been entered. Input control: the input should be restricted to only integers between 0 and 100.
This is what I currently have:
public static void main(String[] args)
{
Scanner console = new Scanner(System.in);
int n = 1;
System.out.print("How many numbers will be entered? ");
n = console.nextInt();
int odd = 0;
int even = 0;
int num;
System.out.println("Enter " + n + " integers: ");
num = console.nextInt();
for(int i = 0; i < n; i++)
{
int b = console.nextInt();
if (b % 2 == 0)
{
even++;
}
else
{
odd++;
}
}
System.out.println("You entered " + even + " even numbers and " + odd + " odd numbers");
}
When I enter how many numbers to input, it allows the user to input 1 more than what was entered. I'm also not sure where I should put the "error" for when the number entered is less than 0 or greater than 100
Explanation / Answer
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
System.out.print("How many numbers will be entered? ");
int n = console.nextInt();
int odd = 0;
int even = 0;
System.out.println("Enter " + n + " integers: ");
for (int i = 0; i < n; i++) {
int b = console.nextInt();
if(b < 0 || b > 100) { // Input checking for positive lnteger less than or equal to 100
System.out.println("Please enter a positive integer less than 100");
i--; // decrementing 'i' for extra iteration when user gives wrong input
continue;
}
if (b % 2 == 0) {
even++;
} else {
odd++;
}
}
System.out.println("You entered " + even + " even numbers and " + odd + " odd numbers");
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.