Read Java console string

Asked

Viewed 369 times

-1

I need to know how to receive Strings that are being printed on the console to do some kind of treatment on them.

2 answers

3

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

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

Full 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 on repl.it

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();
}

Browser other questions tagged

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