Go through array and find a character other than a number

0

The idea is to receive a 4-digit number and then perform a variety of accounts but there is an entry condition: If in the middle of the 4 digits is a character other than a number then I need to print it.

No use of methods.

I can not make the following code:

Receive an example entry: 3? 56

  • Save {3,?, 5, 6} into an array without knowing what the entry is.

  • Check if any of the array positions are not between 0 and 9.

In this case? it is not a number then prints.

I wanted to store in the 4 positions of the array.

    int i;
    char [] digitos = new char[3];
    digitos [0] = 
    digitos [1] = 
    digitos [2] = 
    digitos [3] = 
    for(i=0; i<digitos.length; i++);{
        if(digitos[i]<(char)0||digitos[i]>(char)9) System.out.println("Digito "+digitos[i]+" invalido");
        System.exit(0);
    
asked by anonymous 20.11.2016 / 22:31

1 answer

3

You have several problems in the code snippet. Come on:

1 - char [] digitos = new char[3];

If you want an array with 4 elements, its size must be four, its maximum index is 3, since it starts from index 0.

2 - for(i=0; i<digitos.length; i++);{

This ; causes i to extrapolate the size of the vector, so you should remove it.

3 - if(digitos[i]<(char)0||digitos[i]>(char)9) System.out.println("Digito "+digitos[i]+" invalido"); System.exit(0);

Here are 2 problems. The first is that the character comparison condition is incorrect because the casting will not result in a valid verification of the character's character digit. Here you should compare char with char, for doing this casting you are comparing the ascii code with the char. The second problem is that your exit is outside the if, causing the program to terminate immediately after the first iteration.

Then, based on the problems presented, the final solution would look something like:

int i;
    Scanner scanner = new Scanner(System.in);
    String numero = scanner.nextLine();
    char [] digitos = numero.toCharArray();
    for(i=0; i<digitos.length; i++){
        if(digitos[i]<'0' || digitos[i]>'9') { 
            System.out.println("Digito "+digitos[i]+" invalido");
            System.exit(0);
        }
    }
    
20.11.2016 / 23:59