Home > Mobile >  How To Scan an Integer and Count the Number of '0' Digits?
How To Scan an Integer and Count the Number of '0' Digits?

Time:12-21

I'm trying to write a small program that will accept an integer input and count the number of even, odd, and zero digits. I can get everything to work except counting how many times 0 occurs in the integer. If I write my conditional statement like:

if(inputString.charAt(index) == '0')

it works. But if I write:

if(test == 0)

It does not work. For some reason I can't query the existence of 0 directly as a number. I have to change it to a string and find it that way. Why can't I just query it directly like in my second example? Seems like it should be pretty straightforward.

import java.util.Scanner;

public class ParseInt {
    public static void main(String[] args) {
        
        //Declarations
        int index = 0, test, odd = 0, even = 0, zero = 0;
        String inputString;
        Scanner scan = new Scanner(System.in);
        
        //Inputs
        System.out.println("Input an integer");
        inputString = scan.nextLine();
        
        //Process
        while(index<= inputString.length()-1)
        {
            test = inputString.charAt(index);
            
            if(inputString.charAt(index) == '0') //this line here
                zero  ;
            if(test%2 == 0)
                even  ;
            if(test%2 != 0)
                odd  ;
            
            index  ;
        }
        
        System.out.println("The number of zero digits is "   zero   ".");
        System.out.println("The number of even digits is "   even   ".");
        System.out.println("The number of odd digits is "   odd   ".");
        
        scan.close();
    }
}

I tried changing the line in question to a string and querying that way. It works, but I want to try and query 0 as a number.

CodePudding user response:

When you use inputString.charAt(index) java get the ascii code of number 0 (that is 48).

When you compare it with char '0' Java compare ascii code 48 with 48 and it returns true, if you compare it with a integer Java try to do 0==48 and return false

You can examine this site to see every ascii code https://www.ascii-code.com/

CodePudding user response:

The reason why your second attempt is not working is that a char holds a ASCII reference with has it own integer number. If you want to compare a int to char, you have to convert it and then compare, that's why your first attempt work as both is chars.

  • Related