Doubt with While

Asked

Viewed 97 times

4

I’m a beginner and I’m having second thoughts While / Do…While, follows the doubt in which question.

I have an exercise to follow that the teacher solved with the command Do…While, I was trying to do with the while to exercise and found myself totally dead-end.

Create A program to validate the following information.

nome > 3 caracteres
idade > 0 e idade < 150
salario > 0
sexo ' f ' ou ' m '
estado civil 's' 'c' 'v' 'd'
    public class Exercicios3 {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        boolean validaCampo = true;

        System.out.println("Nome: ");
        String nome = sc.nextLine();

        System.out.println("Idade: ");
        int idade = sc.nextInt();

        System.out.println("Salário: ");
        double salario = sc.nextDouble();

        System.out.println("Sexo: ");
        char sexo = sc.next().charAt(0);

        System.out.println("Estado Civil: ");
        char estadoCivil = sc.next().charAt(0);

        while (!validaCampo) {
            if (nome.length() < 3) {
                validaCampo = false;
                System.out.println("Nome muito pequeno, digite novamente ");
                nome = sc.nextLine();
            } else if (idade <= 0 && idade > 150) {
                validaCampo = false;
                System.out.println("Idade maior que 0 e menor que 105, digite novamente ");
                idade = sc.nextInt();
            } else if (salario < 0) {
                validaCampo = false;
                System.out.println("Salario tem que ser maior que 0, digite novamente ");
                salario = sc.nextDouble();
            } else if (sexo != 'M' || sexo != 'F') {
                validaCampo = false;
                System.out.println("Caracteres têm que ser M - Masculino e F - Feminino, digite novamente ");
                sexo = sc.next().charAt(0);
            } else if ((estadoCivil != 's') || (estadoCivil != 'c') || (estadoCivil != 'v') || (estadoCivil != 'd')) {
                validaCampo = false;
                System.out.println("Caracteres têm que ser s , c , v ou d, digite novamente");
                estadoCivil = sc.next().charAt(0);
            }

            System.out.println("\nFlag ValidaCampo:" + validaCampo);
            System.out.println("\nNome:" + nome);
            System.out.println("Idade:" + idade);
            System.out.println("Salário:" + salario);
            System.out.println("Gênero:" + sexo);
            System.out.println("Estado Civil:" + estadoCivil);

            sc.close();
        }
    }
}
  • What was the expected output and which output you got?

1 answer

3

To explain what happened I’ll omit some parts of the code, let’s just focus on that part:

public class Exercicios3 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        boolean validaCampo = true;

        [...]

        while (!validaCampo) {
            if (nome.length() < 3) {
                validaCampo = false;
                System.out.println("Nome muito pequeno, digite novamente ");
                nome = sc.nextLine();
            } [...]
        }
    }
}

See that at the beginning of the program the variable validaCampo begins with true:

boolean validaCampo = true;

After this is made the condition no while:

while (!validaCampo){...}

this can be read as "While validaCampo is false do ...", but the valid field is true, so it will go straight through the while.

This problem does not occur with the do ... while because the check is done after each loop, ie the code will perform at least 1 time. And after each check the validaCampo is changed to false if the field does not meet the conditions:

if (nome.length() < 3) {
    validaCampo = false;
    [...]
}

Another problem with this code is that the validaCampo is only changed to false within the loop, but never to true, when it is time to exit the while?

Another problem in logic that I realized is the last line of while: sc.close(); If the Scanner is closed, the validaCampo is false and the loop starts again as you will read the next values typed by the user?

I believe that knowing this you can already change your code to work the way you expect.

Browser other questions tagged

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