How to read a string using input in Java?

Asked

Viewed 8,151 times

2

In case I know how to do with int which would be something like:

number1 = input.nextInt();

But I want my user to enter a string, let’s assume a month:

mes = input.????

I need to read the string in a switch, as in the example below:

switch (mes) {
  case "janeiro": System.out.println("Nesta data ocorre o evento chamado: Feriado de janeiro");
  break;
  • Try input.next().

3 answers

2

Look I recommend using the java.util library to use a Scanner. Follow the code below:

import java.util.Scanner;

class Leitura{
     public static void main(String[] args){
         Scanner s = new Scanner(System.in);

         //Aqui  você passa o valor para um string
         String valor_lido = s.nextLine();

         //Agora é fazer o que quiser com o valor dessa String

     }
}

1

In addition to what has already been answered, JOptionPane.showInputDialog(); that creates a interfacinho for the user to type.

1

Uses the input.nextLine(); to read the line entered by the user.

In that specific case you can use the input.next(); because you only want to read a word without spaces. The next() only reads the first word until a space appears. The nextLine(); reads the entire line you can enter until you enter "\n" (key enter)

  • if I want to read the string with the spaces, but without the n? If I type André Nascimento, I won’t read the 'birth' if I use obj.next()?

Browser other questions tagged

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