Domanda

I have written a small piece of code where you enter a 3 digit number via the command line, and then it detects how many 5's are in the code.

public class fivedet {

     public static void main (String[] args) {
        String input = args[0];
    int[] a = {0,0,0};
    int x = 0;
    int y = 0;
    int z = 0;
    for(int i = 0; i<input.length();i++) {
        a[i] = input.charAt(i) - 48;
    }
    if(a[0]==5) {
        x=5;
    }

    if(a[1]==5) {
        y=5;
    }

    if(a[2]==5) {
        z=5;
    }

    System.out.println("5 digits here:" + x + y + z);
}
}

My main question is why I require the -48 term after the input.charAt(i) method in order for each value in a[] to be equal to the actual number I input.

For example I enter java fivedet 505 and without the -48 the array a[]={53,48,53} instead of a[]={5,0,5} and I unfortunately am not experienced enough with coding java (began learning 3 months ago) to understand why this is happening.

I also do want to develop it to be able to detect different digits and for different lengths of input numbers.

I would appreciate any insight as to why this happens.

È stato utile?

Soluzione

Subtracting 48 is a quick but slightly confusing way of converting from a character to an integer. It so happens that the character code for each digit is 48 away from its numeric value.

See this table of ASCII values. (Java uses unicode, not ascii - strings are UTF-16 internally - but the values are valid in this specific case). So the character '0' has the value 48; the character '9' has the value 57.

Another way of doing this would be to take 1-character substrings of input, then call Integer.parseInt() on that string, converting "1" to 1, "2" to 2, etc.

Altri suggerimenti

You don’t need to convert to int in order to detect character 5. Just count them as chars.

for (char i : args[0].toCharArray()) {
        System.out.print(i == '5' ? i : '0');

    }

Also this question has good answers to count occurrences of a char in string

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top