nextLine() problem inside the loop

Asked

Viewed 77 times

0

The user must enter different name and password, while they are equal will stay in the loop

...

Scanner teclado = new Scanner(System.in);

String nome, senha;

do{

System.out.println("Digite nome:");
nome = teclado.nextLine();

System.out.println("Digite senha:");
senha = teclado.next();

if(nome.equals(senha)){

System.out.println("Nome deve ser diferente de senha, Digite novamente");
}

} while(nome.equals(senha));

...

When name and password are equal he should return and ask to enter only the name, only then ask for the password, but he asks for the 2 name and password, wanted to understand nextLine does this and how should you use it in this case. Obs: I know next() resolves

2 answers

1


Not everything on the Internet is true or real.

Despite being quite widespread on the internet the use of class instances java.util.Scanner as a substitute for the use of the method java.io.Console.readLine() it’s not like that.

The class java.util.Scanner is a text scanner that can parse primitive types and strings using regular expressions.
java.util.Scanner divides your input into tokens using a standard delimiter, which initially corresponds to blanks.

To documentation says:

For simple line-oriented read-only applications, use java.io.Console.readLine()

That is to say java.util.Scanner is a tool used to perform lexical analysis of a text coming from an object in the classes File, InputStream, Readable, String, ReadableByteChannel or Path.

In case the console read is passed System.in an instance of InputStream.

I wanted to understand why java.util.Scanner.nextLine() does this and how to use it in this case?

The method nextLine() is not a proper method for reading a character line. It is method for reading surplus characters, whether characters do not form tokens or characters discarded during lexical analysis. nextLine() from the last token read and returns the remainder of the input that was ignored. As during the first run of the loop still no token was read by the scanner, nextLine() blocks the program while waiting for entry, but in the second iteration of the loop a token had been read by java.util.Scanner.next() and then nextLine() from the last token only reads an empty line. A repair possibility for your code is to use precedes the use nextLine() with the method java.util.Scanner.hasNextLine() true return if there is a line in the scanner entry, block and wait while waiting for an entry.

import java.util.*;

class Main {
  public static void main(String args[]) {
    Scanner teclado = new Scanner(System.in);    
    String nome="", senha="";    
    do {    
      System.out.println("Digite nome:");
      if(teclado.hasNextLine()){
        nome = teclado.nextLine();
      }
      System.out.println("Digite senha:");
      if(teclado.hasNextLine()){
        senha = teclado.nextLine();
      }
      if (nome.equals(senha)) {    
        System.out.println("Nome deve ser diferente de senha, Digite novamente");
      }
    } while (nome.equals(senha));
  }
}

A proportional alternative task would be to use java.util.Console.readLine()

import java.io.*;

class Main {
  public static void main(String args[]) {
    Console teclado = System.console();
    String nome="", senha="";
    do {
      System.out.println("Digite nome:");
      nome = teclado.readLine();
      System.out.println("Digite senha:");
      senha = teclado.readLine();
      if (nome.equals(senha)) {
        System.out.println("Nome deve ser diferente de senha, Digite novamente");
      }
    } while (nome.equals(senha));
  }
}
  • 1

    See if I got it, so if I envy password = keyboard.next(); put password = keyboard.nextLine(); it’s going right?

  • 1

    It’ll only work if you put if(teclado.hasNextLine()){nome = teclado.nextLine();} and if(teclado.hasNextLine()){senha = teclado.nextLine();}. The key to correct operation is the use of teclado.hasNextLine() that prepares the scanner to consume a line with teclado.nextLine().

  • 1

    As to the teclado.next() if for example the user enters with a b c, teclado.next() will only read a

1

Using the do-while This way, you will always ask to reset both the name and password, as they are in the same scope. I took the liberty of rewriting your code:

Scanner teclado = new Scanner(System.in);

    System.out.println("Digite nome:");
    String nome = teclado.nextLine();

    System.out.println("Digite senha:");
    String senha = teclado.next();

    while(nome.equals(senha)){
        System.out.println("Nome deve ser diferente de senha, digite novamente a senha: ");

        System.out.println("Digite senha: ");
        senha = teclado.next();
        if(nome.equals(senha)) //opcional
            System.out.println("Nome e senha ainda continuam iguais...");
    }
    //só para você ver que deu certo
    System.out.println("nome = " + nome);
    System.out.println("senha = " + senha);
}

Browser other questions tagged

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