Input utente Java (scanner)


Input utente Java

La Scannerclasse viene utilizzata per ottenere l'input dell'utente e si trova nel java.utilpacchetto.

Per utilizzare la Scannerclasse, crea un oggetto della classe e usa uno dei metodi disponibili trovati nella Scannerdocumentazione della classe. Nel nostro esempio useremo il nextLine()metodo, che viene utilizzato per leggere le stringhe:

Esempio

import java.util.Scanner;  // Import the Scanner class

class Main {
  public static void main(String[] args) {
    Scanner myObj = new Scanner(System.in);  // Create a Scanner object
    System.out.println("Enter username");

    String userName = myObj.nextLine();  // Read user input
    System.out.println("Username is: " + userName);  // Output user input
  }
}

Se non sai cos'è un pacchetto, leggi il nostro Tutorial sui pacchetti Java .


Tipi di input

Nell'esempio sopra, abbiamo usato il nextLine()metodo, che viene utilizzato per leggere le stringhe. Per leggere altri tipi, guarda la tabella seguente:

Method Description
nextBoolean() Reads a boolean value from the user
nextByte() Reads a byte value from the user
nextDouble() Reads a double value from the user
nextFloat() Reads a float value from the user
nextInt() Reads a int value from the user
nextLine() Reads a String value from the user
nextLong() Reads a long value from the user
nextShort() Reads a short value from the user

Nell'esempio seguente, utilizziamo diversi metodi per leggere dati di vario tipo:

Esempio

import java.util.Scanner;

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

    System.out.println("Enter name, age and salary:");

    // String input
    String name = myObj.nextLine();

    // Numerical input
    int age = myObj.nextInt();
    double salary = myObj.nextDouble();

    // Output input by user
    System.out.println("Name: " + name);
    System.out.println("Age: " + age);
    System.out.println("Salary: " + salary);
  }
}

Nota: se inserisci un input errato (ad es. testo in un input numerico), riceverai un messaggio di eccezione/errore (come "InputMismatchException").

Puoi leggere di più sulle eccezioni e su come gestire gli errori nel capitolo Eccezioni .