In questo tutorial, impareremo a conoscere Java Scanner e i suoi metodi con l'aiuto di esempi.
La Scanner
classe del java.util
pacchetto viene utilizzata per leggere i dati di input da diverse fonti come flussi di input, utenti, file, ecc. Facciamo un esempio.
Esempio 1: leggere una riga di testo utilizzando lo scanner
import java.util.Scanner; class Main ( public static void main(String() args) ( // creates an object of Scanner Scanner input = new Scanner(System.in); System.out.print("Enter your name: "); // takes input from the keyboard String name = input.nextLine(); // prints the name System.out.println("My name is " + name); // closes the scanner input.close(); ) )
Produzione
Inserisci il tuo nome: Kelvin Il mio nome è Kelvin
Nell'esempio sopra, notare la linea
Scanner input = new Scanner(System.in);
Qui, abbiamo creato un oggetto di Scanner
input denominato.
Il System.in
parametro viene utilizzato per ricevere input dallo standard input. Funziona proprio come prendere input dalla tastiera.
Abbiamo quindi utilizzato il nextLine()
metodo della Scanner
classe per leggere una riga di testo dall'utente.
Ora che hai qualche idea Scanner
, esploriamo di più al riguardo.
Importa classe scanner
Come possiamo vedere dall'esempio sopra, dobbiamo importare il java.util.Scanner
pacchetto prima di poter usare la Scanner
classe.
import java.util.Scanner;
Per ulteriori informazioni sull'importazione dei pacchetti, visitare Pacchetti Java.
Crea un oggetto scanner in Java
Una volta importato il pacchetto, ecco come possiamo creare Scanner
oggetti.
// read input from the input stream Scanner sc1 = new Scanner(InputStream input); // read input from files Scanner sc2 = new Scanner(File file); // read input from a string Scanner sc3 = new Scanner(String str);
Qui, abbiamo creato oggetti della Scanner
classe che leggeranno l'input rispettivamente da InputStream, File e String.
Metodi di Java Scanner per ricevere input
La Scanner
classe fornisce vari metodi che ci consentono di leggere input di diverso tipo.
Metodo | Descrizione |
---|---|
nextInt() | legge un int valore dall'utente |
nextFloat() | legge un float valore dall'utilizzatore |
nextBoolean() | legge un boolean valore dall'utente |
nextLine() | legge una riga di testo dall'utente |
next() | legge una parola dall'utente |
nextByte() | legge un byte valore dall'utente |
nextDouble() | legge un doubl valore e dall'utente |
nextShort() | legge un short valore dall'utente |
nextLong() | legge un long valore dall'utente |
Esempio 2: Java Scanner nextInt ()
import java.util.Scanner; class Main ( public static void main(String() args) ( // creates a Scanner object Scanner input = new Scanner(System.in); System.out.println("Enter an integer: "); // reads an int value int data1 = input.nextInt(); System.out.println("Using nextInt(): " + data1); input.close(); ) )
Produzione
Immettere un numero intero: 22 Utilizzando nextInt (): 22
Nell'esempio precedente, abbiamo utilizzato il nextInt()
metodo per leggere un valore intero.
Esempio 3: Java Scanner nextDouble ()
import java.util.Scanner; class Main ( public static void main(String() args) ( // creates an object of Scanner Scanner input = new Scanner(System.in); System.out.print("Enter Double value: "); // reads the double value double value = input.nextDouble(); System.out.println("Using nextDouble(): " + value); input.close(); ) )
Produzione
Immettere il valore Double: 33.33 Utilizzando nextDouble (): 33.33
Nell'esempio precedente, abbiamo utilizzato il nextDouble()
metodo per leggere un valore a virgola mobile.
Esempio 4: Java Scanner next ()
import java.util.Scanner; class Main ( public static void main(String() args) ( // creates an object of Scanner Scanner input = new Scanner(System.in); System.out.print("Enter your name: "); // reads the entire word String value = input.next(); System.out.println("Using next(): " + value); input.close(); ) )
Produzione
Inserisci il tuo nome: Jonny Walker Utilizzando next (): Jonny
Nell'esempio precedente, abbiamo utilizzato il next()
metodo per leggere una stringa dall'utente.
Qui abbiamo fornito il nome completo. Tuttavia, il next()
metodo legge solo il nome.
Questo perché il next()
metodo legge l'input fino al carattere di spazio bianco . Una volta rilevato lo spazio bianco , restituisce la stringa (escluso lo spazio bianco).
Esempio 5: Java Scanner nextLine ()
import java.util.Scanner; class Main ( public static void main(String() args) ( // creates an object of Scanner Scanner input = new Scanner(System.in); System.out.print("Enter your name: "); // reads the entire line String value = input.nextLine(); System.out.println("Using nextLine(): " + value); input.close(); ) )
Produzione
Immettere il nome: Jonny Walker Utilizzando nextLine (): Jonny Walker
Nel primo esempio, abbiamo utilizzato il nextLine()
metodo per leggere una stringa dall'utente.
Diversamente next()
, il nextLine()
metodo legge l'intera riga di input inclusi gli spazi. Il metodo termina quando incontra un carattere riga successiva, .
Recommended Reading: Java Scanner skipping the nextLine().
Java Scanner with BigInteger and BigDecimal
Java scanner can also be used to read the big integer and big decimal numbers.
- nextBigInteger() - reads the big integer value from the user
- nextBigDecimal() - reads the big decimal value from the user
Example 4: Read BigInteger and BigDecimal
import java.math.BigDecimal; import java.math.BigInteger; import java.util.Scanner; class Main ( public static void main(String() args) ( // creates an object of Scanner Scanner input = new Scanner(System.in); System.out.print("Enter a big integer: "); // reads the big integer BigInteger value1 = input.nextBigInteger(); System.out.println("Using nextBigInteger(): " + value1); System.out.print("Enter a big decimal: "); // reads the big decimal BigDecimal value2 = input.nextBigDecimal(); System.out.println("Using nextBigDecimal(): " + value2); input.close(); ) )
Output
Enter a big integer: 987654321 Using nextBigInteger(): 987654321 Enter a big decimal: 9.55555 Using nextBigDecimal(): 9.55555
In the above example, we have used the java.math.BigInteger
and java.math.BigDecimal
package to read BigInteger
and BigDecimal
respectively.
Working of Java Scanner
La Scanner
classe legge un'intera riga e la divide in gettoni. I token sono piccoli elementi che hanno un significato per il compilatore Java. Per esempio,
Supponiamo che ci sia una stringa di input:
He is 22
In questo caso, l'oggetto scanner leggerà l'intera riga e la divide in token: " He ", " is " e " 22 ". L'oggetto quindi itera su ogni token e legge ogni token usando i suoi diversi metodi.
Nota : per impostazione predefinita, gli spazi bianchi vengono utilizzati per dividere i token.