Traverse array and locate a character other than a number

Asked

Viewed 812 times

0

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

Not using any methods.

I cannot perform the following code:

Receive an example entry: 3?56

  • Store {3, ? , 5 ,6} in an array without knowing which is the input.

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

In this case ? is not a number so print.

I wanted to save 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);
  • What have you tried? What language are you using?

  • Java language.

  • That’s it, I’m sorry

  • Anyone can help?

1 answer

3


There are several problems in the code snippet. Come on:

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

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

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

That one ; makes i 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);

There are two problems here. The first is that the character comparison condition is incorrect because the casting will not result in a valid check of the character’s digit nature. Here you should compare char with char, because doing this casting you are comparing ascii code with char. The second problem is that your Exit is out of the if, so the program closes right after the first iteration.

So, based on the problems presented, the final solution would be 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);
        }
    }
  • I can’t use methods. The question is how to: ?

  • 1

    @BFR this information should be in the question, so it is important to add as much information as possible, otherwise this happens.

  • @diegofm I have corrected. I will be more attentive to this kind of situations. Thank you

  • 1

    Okay, I edited the answer. Use the scanner to read and then convert to the chars-a-string array. There corrects the comparison of the chars without using methods.

  • Thank you very much.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.