I am trying to make sure my program does not count zero as an even and specifically wrote that it must fit these conditions. But it still counts it!??!?
import java.util.Scanner;
public class CountDigits
{
public static void main (String []Args)
{
Scanner keyboard = new Scanner (System.in);
System.out.println("Enter a number:");
long input = (keyboard.nextLong());
String inputString = Long.toString(input);
char [] inputChar = (inputString.toCharArray());
int numOdds = 0;
int numEvens = 0;
int numZeros = 0;
int i = 0;
while (i<inputString.length())
{
if (inputChar[i]!=0&&inputChar[i]%2==0)
{
numEvens++;
}
You are using a char[]
, rather than an int[]
. The char
0
is different from the char
'0'
. Your program will work if you do this:
if (inputChar[i]!='0' && inputChar[i]%2==0)
However it's probably less confusing if you use an int[]
instead.
Without trying to run your code I can see that you are doing inputChar[i]%2==0
inputChar[i]%2
will return the remainder of inputChar[i]/2
so where inputChar[i] has the value 0, 0 divide 2 will equal 0 so there will be a remainder of 0.
If you want to count 0 as odd you will also need to check for 0.
Please note that inputChar[i] is a char and not an int so you will need to check inputChar[i] != '0'
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.