Come posso ottenere un semplice input da tastiera (un numero intero) dall’utente nella console in Java? Ho realizzato questo utilizzando il materiale java.io.*
, ma dice che è deprecato.
Come dovrei farlo ora?
È ansible utilizzare la class Scanner
Importa prima:
import java.util.Scanner;
Quindi usi in questo modo.
Scanner keyboard = new Scanner(System.in); System.out.println("enter an integer"); int myint = keyboard.nextInt();
Nota a nextInt()
: se stai usando nextInt()
con nextLine()
probabilmente potresti avere qualche problema perché nextInt()
non legge l’ultimo carattere newline di input e quindi nextLine()
non verrà eseguito con il comportamento desiderato. Per saperne di più su come risolverlo in questa domanda precedente Saltare nextLine usando nextInt .
Puoi usare la class Scanner in questo modo:
import java.util.Scanner; public class Main{ public static void main(String args[]){ Scanner scan= new Scanner(System.in); //For string String text= scan.nextLine(); System.out.println(text); //for int int num= scan.nextInt(); System.out.println(num); } }
Puoi anche farlo con BufferedReader se vuoi convalidare l’input dell’utente, come questo:
import java.io.BufferedReader; import java.io.InputStreamReader; class Areas { public static void main(String args[]){ float PI = 3.1416f; int r=0; String rad; //We're going to read all user's text into a String and we try to convert it later BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); //Here you declare your BufferedReader object and instance it. System.out.println("Radius?"); try{ rad = br.readLine(); //We read from user's input r = Integer.parseInt(rad); //We validate if "rad" is an integer (if so we skip catch call and continue on the next line, otherwise, we go to it (catch call)) System.out.println("Circle area is: " + PI*r*r + " Perimeter: " +PI*2*r); //If all was right, we print this } catch(Exception e){ System.out.println("Write an integer number"); //This is what user will see if he/she write other thing that is not an integer Areas a = new Areas(); //We call this class again, so user can try it again //You can also print exception in case you want to see it as follows: // e.printStackTrace(); } } }
Perché la class Scanner non ti permette di farlo, o non così facilmente …
E per convalidare usi chiamate “try-catch”.
È ansible utilizzare Scanner per ottenere la riga successiva e fare tutto ciò che è necessario fare con la linea inserita. Puoi anche usare JOptionPane per far apparire una finestra di dialogo che richiede input.
Esempio di scanner:
Scanner input = new Scanner(System.in); System.out.print("Enter something > "); String inputString = input.nextLine(); System.out.print("You entered : "); System.out.println(inputString);
Esempio di JOptionPane:
String input = JOptionPane.showInputDialog(null, "Enter some text:"); JOptionPane.showMessageDialog(null,"You entered "+ input);
Avrai bisogno di queste importazioni:
import java.util.Scanner; import javax.swing.JOptionPane;
Una class Java completa di quanto sopra
import java.util.Scanner; import javax.swing.JOptionPane; public class GetInputs{ public static void main(String args[]){ //Scanner example Scanner input = new Scanner(System.in); System.out.print("Enter something > "); String inputString = input.nextLine(); System.out.print("You entered : "); System.out.println(inputString); //JOptionPane example String input = JOptionPane.showInputDialog(null, "Enter some text:"); JOptionPane.showMessageDialog(null,"You entered "+ input); } }
Importazione: import java.util.Scanner;
Definisci le tue variabili: String name; int age;
String name; int age;
Definisci il tuo scanner: Scanner scan = new Scanner(System.in);
Se si desidera digitare:
name = scan.nextLine();
age = scan.nextInt();
Chiudere lo scanner se non è più necessario: scan.close();
import java.util.Scanner; //import the framework Scanner input = new Scanner(System.in); //opens a scanner, keyboard System.out.print("Enter a number: "); //prompt the user int myInt = input.nextInt(); //store the input from the user
Fatemi sapere se avete domande. Abbastanza auto-esplicativo. Ho commentato il codice in modo da poterlo leggere. 🙂
Aggiungi linea:
import java.util.Scanner;
Quindi creare un object della class Scanner
:
Scanner s = new Scanner(System.in);
Ora puoi chiamare in qualsiasi momento:
int a = Integer.parseInt(s.nextLine());
Questo memorizzerà il valore integer
dalla tua tastiera.
Se hai Java 6 (dovresti avere, btw) o superiore, allora fai semplicemente questo:
Console console = System.console(); String str = console.readLine("Please enter the xxxx : ");
Per favore ricordati di fare:
import java.io.Console;
Questo è tutto!
Leggere dalla tastiera ( input standard ) È ansible utilizzare Scanner è una class nel pacchetto java.util
.
Pacchetto Scanner
utilizzato per ottenere l’input dei tipi primitivi come int, double
ecc. E strings
. È il modo più semplice per leggere l’input in un programma Java, sebbene non molto efficiente.
object
della class Scanner
, di solito passiamo l’object predefinito System.in
, che rappresenta lo stream di input standard ( tastiera ). Ad esempio, questo codice consente a un utente di leggere un numero da System.in:
Scanner sc = new Scanner(System.in); int i = sc.nextInt();
Alcuni metodi pubblici nella class Scanner
.
hasNext()
Restituisce true se questo scanner ha un altro token nel suo input. nextInt()
Esegue la scansione del token successivo dell’input come int. nextFloat()
Analizza il token successivo dell’input come float. nextLine()
scanner oltre la riga corrente e restituisce l’input che è stato saltato. nextDouble()
Analizza il token successivo dell’input come un double. close()
Chiude questo scanner. Per ulteriori dettagli sui metodi pubblici nella class Scanner.
Exaple: –
import java.util.Scanner; //importing class class ScannerTest { public static void main(String args[]) { Scanner sc = new Scanner(System.in); // Scanner object System.out.println("Enter your rollno"); int rollno = sc.nextInt(); System.out.println("Enter your name"); String name = sc.next(); System.out.println("Enter your fee"); double fee = sc.nextDouble(); System.out.println("Rollno:" + rollno + " name:" + name + " fee:" + fee); sc.close(); // closing object } }