Read Console String in Java

-1

I need to know how to get Strings being printed on the console to do some sort of processing on them.

    
asked by anonymous 17.10.2017 / 13:59

2 answers

3

You need to use the Scanner class and instantiate it passing System.in as a parameter.

Scanner scanner = new Scanner(System.in);
System.out.println("Entre com seu nome:");
String nome = scanner.nextLine();

Complete example

import java.util.Scanner;

class Main
{
    public static void main(String[] args)
    {
        Scanner scanner = new Scanner(System.in);
        System.out.println("Entre com seu nome:");
        String nome = scanner.nextLine();

        System.out.printf("Seu nome é %s", nome);
    }
}

See working at repl.it

    
17.10.2017 / 14:01
2
try (Scanner scanner = new Scanner(System.in)) {
      System.out.println("Entre com seu nome:");
      String nome = scanner.nextLine();
        System.out.printf("Seu nome é %s", nome);
} catch (Exception e) {
      e.printStackTrace();
}
    
17.10.2017 / 15:28