简体   繁体   中英

Figure out Odd Even or Zero by entering the value

My teacher asked me a question and I was really confused how to write it out as a code. I understood what I had to do, but just couldn't write in Java. So the question was that: Design and implement an application that determines and prints the number of odd even and zero digits. Input could be anything from the user/keyboard. I just don't know how to start. So can someone help me here with an answer and an explanation with that?(without using string) Thank you so much for your time.

Application? It's three lines:

int odds = str.replaceAll("[^13579]", "").length();
int evens = str.replaceAll("[^2468]", "").length();
int zeroes = str.replaceAll("[^0]", "").length();

If the input is not a string, make it one:

long number;
String str = number + "";

I would use a for loop to traverse the input string. Within the for loop would be a switch statement that increments either the 'odd' variable, the 'even' variable,' the 'zero' variable, or does nothing. This way the string is only traversed once instead of three times.

The code would look something like:

int numOdds = 0;
int numEvens = 0;
int numZeroes = 0;
for(int i = 0; i < inputString.length(); i++) {
    switch(inputString.charAt(i)) {
        case '1':
        case '3':
        case '5':
        case '7':
        case '9': numOdds++;
                  break;
        case '2':
        case '4':
        case '6':
        case '8': numEvens++;
                  break;
        case '0': numZeroes++;
        default: break;
    }
}

Looks like you have a couple answers. Here is another you may like more because you probably can understand it:

int odds, evens, zeroes;

public void setOddsEvensZereos(String str) {
 for(char c:str) {
  try {
   int i = Integer.parseInt(c + "");
   if(i == 0)
    zereos++;
   else if(i % 2 == 0)
    evens++;
   else
    odds++;
  } catch (Exception e){/*the character isn't a number*/}
 }
}

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM