My while isn’t stopping when the condition is true.. I type "VITOR" but can’t exit the WHILE

Asked

Viewed 54 times

2

import java.util.Scanner;

public class RepeticaoWhile {

    public static void main(String[] args) {
        
        String nome;
        
        System.out.println("Digite o nome VITOR ");
        
        Scanner teclado = new Scanner(System.in);
        
        nome = teclado.nextLine();
        
        while(nome!="VITOR"){
            
            System.out.println("Não entendi..digite novamente");
            nome = teclado.nextLine();
            
            }
        
        teclado.close();
    }

}

2 answers

1

For logical comparisons of String in if and while structures the syntax is different from primitive types (int, float, char...). You could do it quietly:

while(1 != ValorDigitado) {
        System.out.println("DIGITE NOVAMENTE");
        ValorDigitado = teclado.nextLine();

But for String it is almost always necessary to use this syntax:

x.equals("valor desejado")

And as quoted in the example you put, to put the logical operator of difference (!=) in the while structure with String, it is necessary to just put a "!" before syntax:

while(! nome.equals(nome2)) {

            System.out.println("DIGITE NOVAMENTE");
            nome = teclado.nextLine();

PS: Remembering that String IS NOT a primitive type, but a class, so it has this syntax that differs from the types int, float, double and char within a logical structure.

0

I got it this way

    String nome2 = "VITOR";
    
nome = teclado.nextLine();
        while(! nome.equals(nome2)) {
                System.out.println("DIGITE NOVAMENTE");
                
                nome = teclado.nextLine();

But if anyone knows why it doesn’t work " != "I’d appreciate it :)

Browser other questions tagged

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