how to make it count the even digits. and am I doing anything wrong ?
Scanner input = new Scanner (System.in);
int n; int even = 0;
System.out.print(" Enter a number with four digits: ");
n = input.nextInt();
if (n < 1000 ) {
System.out.print("number is less than 4 digits");}
else if (n > 9999){
System.out.print(" number is more than 4 digits");
}
else {
for(int i = 0; i < n ; i++) {
if((n%10)%2==0)
even++;
System.out.print("There’s" + even + "even number (s).");
}
}
and am I doing anything wrong ?
like posting java code in c++ forums? :P You may get some help anyway, but you would do better in ... a java forum...
also that for loop is checking N%10 every time.
I think you want to change that 10.
something like
for(stuff)
{
even+= 1 - n%2; //even, n%2 is 0, adds 1. odd, n%2 is 1, adds 0.
n = n%2; //if you need n later, this should be a copy of n...
}
or alternately try /1, 10,100 (start at 1, multiply by 10 each time).
I am not a chemist. Yet I constantly have to deal with elements and solutions. Does that seem right to you?
#include <iostream>
usingnamespace std;
int countEven( int n ) { return ( n >= 10 ? countEven( n / 10 ) : 0 ) + 1 - n % 2; }
int main()
{
int n = 0;
while ( n < 1000 || n > 9999 ) { cout << "Input n: "; cin >> n; }
cout << "Number of even digits = " << countEven( n );
}
another topic can you give me head start to this one
Write a program that count until we got 5 numbers multiple of 3 (the program should ask the user to enter integer until we got 5 integers that are multiple of 3):
import java.util.Scanner;
publicclass Main
{
publicstaticvoid main(String[] args)
{
Scanner input = new Scanner (System.in);
int num, num_even = 0;
System.out.print(" Enter a number with four digits: ");
num = input.nextInt();
if (num < 1000 )
{
System.out.print("number is less than 4 digits");
return;
}
elseif (num > 9999)
{
System.out.print(" number is more than 4 digits");
return;
}
while (num > 0)
{
int last_digit = num % 10;
if (last_digit % 2 == 0)
num_even++;
num = num / 10;
}
System.out.printf("There’s %d even number(s).", num_even);
}
}
Write a program that count until we got 5 numbers multiple of 3 (the program should ask the user to enter integer until we got 5 integers that are multiple of 3)
Forget about Java coding for a minute and concentrate on the process, using pseudocode
1. set a counter to zero loop:
2. Enter a number
3. If the number is divisible by 3? (i.e. n%3 is zero), then add 1 to the counter
5. If the counter is < 5 loop back for another number, otherwise ...
...
6. ... THE END