Ottenere l'input da tastiera


Come faccio a ottenere un semplice input da tastiera (un numero intero) dall'utente nella console in Java? Ho realizzato questo usando la roba java.io.*, ma dice che è deprecata.

Come dovrei farlo ora?

Author: Anthony E, 2013-07-09

9 answers

È possibile utilizzare Scanner classe

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 margine : se stai usando nextInt() con nextLine() probabilmente potresti avere qualche problema perché nextInt() non legge l'ultimo carattere di nuova riga di input e quindi nextLine() non verrà eseguito con il comportamento desiderato. Leggi di più su come risolverlo in questa domanda precedente Saltando nextLine usando nextInt.

 55
Author: nachokk, 2017-05-23 11:55:10

Puoi usare la classe Scanner come questa:

  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);
    }
}
 16
Author: Mike B, 2013-07-09 00:52:08

Puoi anche farlo con BufferedReader se vuoi convalidare l'input dell'utente, in questo modo:

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 classe Scanner non ti permetterà di farlo, o non così facile...

E per convalidare si utilizzano le chiamate "try-catch".

 12
Author: Frakcool, 2015-09-02 18:14:58

È possibile utilizzare Scanner per ottenere la riga successiva e fare tutto ciò che è necessario fare con la riga inserita. Puoi anche usare JOptionPane per aprire 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 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 classe 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);
    }
}
 3
Author: s-hunter, 2014-01-31 18:42:46

Importa: import java.util.Scanner;

Definire le variabili: String name; int age;

Definire lo scanner: Scanner scan = new Scanner(System.in);

Se si desidera digitare:

  • Testo: name = scan.nextLine();
  • Intero: age = scan.nextInt();

Chiudere lo scanner se non è più necessario: scan.close();

 2
Author: Bishop, 2017-01-14 18:09:56
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. :)

 1
Author: Dummy Code, 2013-07-09 00:48:31

Aggiungi riga:

import java.util.Scanner;

Quindi creare un oggetto di Scanner classe:

Scanner s = new Scanner(System.in);

Ora puoi chiamare in qualsiasi momento:

int a = Integer.parseInt(s.nextLine());

Questo memorizzerà il valore integer dalla tastiera.

 1
Author: Yeshdeep Kumar, 2014-11-03 13:50:18

Se hai Java 6 (dovresti avere, btw) o superiore, fai semplicemente questo:

 Console console = System.console();
 String str = console.readLine("Please enter the xxxx : ");

Ricordati di fare:

 import java.io.Console;

Questo è tutto!

 1
Author: M-D, 2015-01-06 15:26:29

È possibile utilizzare la classe Scanner

Per leggere da Tastiera (Standard Input ) È possibile utilizzare Scanner è una classe in java.util pacchetto.

Scanner pacchetto 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, anche se non molto efficiente.

  1. Per creare una object di Scanner classe, di solito passiamo il oggetto predefinito System.in, che rappresenta lo standard input flusso ( Tastiera ).

Ad esempio, questo codice consente all'utente di leggere un numero da System.in:

Scanner sc = new Scanner(System.in);
     int i = sc.nextInt();

Alcuni metodi pubblici nella classe Scanner.

  • hasNext() Restituisce true se lo scanner ha un altro token nel suo input.
  • nextInt() Esegue la scansione del token successivo dell'input come int.
  • nextFloat() Esegue la scansione del token successivo dell'input come float.
  • nextLine() Fa avanzare lo scanner oltre la riga corrente e restituisce l'input saltare.
  • nextDouble() Esegue la scansione del token successivo dell'input come doppio.
  • close() Chiude lo scanner.

Per maggiori dettagli su Metodi pubblici nella classe 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
  }
}
 0
Author: anoopknr, 2018-06-07 20:31:13