How to read a string using input in Java?

2

In case I know how to do with int it would look something like:

number1 = input.nextInt();

But I want my user to type a string, let's assume a month:

mes = input.????

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

switch (mes) {
  case "janeiro": System.out.println("Nesta data ocorre o evento chamado: Feriado de janeiro");
  break;
    
asked by anonymous 23.07.2014 / 00:17

3 answers

1

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

In this specific case you can use 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" (the enter key)

    
23.07.2014 / 00:24
1

Look, I recommend using the java.util library to use a Scanner. Here is 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

     }
}
    
23.07.2014 / 02:30
1

In addition to what has already been answered, it has JOptionPane.showInputDialog(); which creates an interface for the user to type.

    
25.11.2017 / 15:13