Come leggere il valore intero dallo standard input in Java


109

Quale classe posso usare per leggere una variabile intera in Java?

Risposte:


141

Puoi usare java.util.Scanner( API ):

import java.util.Scanner;

//...

Scanner in = new Scanner(System.in);
int num = in.nextInt();

Può anche tokenizzare l'input con espressioni regolari, ecc. L'API ha esempi e ce ne sono molti altri in questo sito (ad esempio, come faccio a evitare che uno scanner generi eccezioni quando viene inserito il tipo sbagliato? ).


1
Sto cercando di eseguirlo nel mio ID eclipse senza errori di sintassi ma non mostra nulla nell'output della console quando provo a visualizzare i valori interi letti. Perché è così?
— rh979

@polygenelubricants: in.nextInt () accetta solo un valore int non un valore intero
— Ved Prakash

31

Se stai usando Java 6, puoi usare il seguente oneliner per leggere un numero intero dalla console:

int n = Integer.parseInt(System.console().readLine());

17
Vorrei commentare che nella maggior parte degli IDE System.console restituirà null quando l'applicazione viene invocata tramite un launcher rendendo difficile il debug. Questo sembra essere vero per IDEA, Eclipse e NetBeans.
— Andrew White,

1
Se inserisce una stringa o "Invio", verrà generata un'eccezione NumberFormatException. Quindi è meglio controllare la stringa prima di analizzarla su Integer
— Vasile Surdu

cosa succede se ci sono più numeri interi in quella riga separati da uno spazio?
— LostMohican

@LostMohican, ci sono modi per leggere i token delimitati da spazi bianchi utilizzando Scanner.
— Missingfaktor

17

Qui sto fornendo 2 esempi per leggere il valore intero dallo standard input

Esempio 1

import java.util.Scanner;
public class Maxof2
{ 
  public static void main(String args[])
  {
       //taking value as command line argument.
        Scanner in = new Scanner(System.in); 
       System.out.printf("Enter i Value:  ");
       int i = in.nextInt();
       System.out.printf("Enter j Value:  ");
       int j = in.nextInt();
       if(i > j)
           System.out.println(i+"i is greater than "+j);
       else
           System.out.println(j+" is greater than "+i);
   }
 }

Esempio 2

public class ReadandWritewhateveryoutype
{ 
  public static void main(String args[]) throws java.lang.Exception
  {
System.out.printf("This Program is used to Read and Write what ever you type \nType  quit  to Exit at any Moment\n\n");
    java.io.BufferedReader r = new java.io.BufferedReader (new java.io.InputStreamReader (System.in));
     String hi;
     while (!(hi=r.readLine()).startsWith("quit"))System.out.printf("\nYou have typed: %s \n",hi);
     }
 }

Preferisco il primo esempio, è facile e abbastanza comprensibile.
È possibile compilare ed eseguire i programmi JAVA in linea su questo sito Web: http://ideone.com


1
ex 2 potrebbe non essere il modo migliore per introdurre il flusso di input ... o immagino che gli "oggetti di input del sistema" a qualcuno che non conosce OOD, Java o codifica per quella materia - tutto quel codice descrittivo e tu chiami l'oggetto chiave " r ".... un saggio, eh? xD +1
— Tapper7

1
L'esempio 1 non è protetto contro input di formato falso
— Martin Meeser

11

Controlla questo:

public static void main(String[] args) {
    String input = null;
    int number = 0;
    try {
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
        input = bufferedReader.readLine();
        number = Integer.parseInt(input);
    } catch (NumberFormatException ex) {
       System.out.println("Not a number !");
    } catch (IOException e) {
        e.printStackTrace();
    }
}

Qual è il punto nel catturare NumberFormatExceptione poi stampare la traccia dello stack?
— missingfaktor

6

La seconda risposta sopra è la più semplice.

int n = Integer.parseInt(System.console().readLine());

La domanda è "Come leggere dallo standard input".

Una console è un dispositivo tipicamente associato alla tastiera e al display da cui viene avviato un programma.

È possibile verificare se non è disponibile alcun dispositivo della console Java, ad esempio Java VM non avviato da una riga di comando o se i flussi di input e output standard vengono reindirizzati.

Console cons;
if ((cons = System.console()) == null) {
    System.err.println("Unable to obtain console");
    ...
}

Usare la console è un modo semplice per inserire i numeri. Combinato con parseInt () / Double () ecc.

s = cons.readLine("Enter a int: ");
int i = Integer.parseInt(s);    

s = cons.readLine("Enter a double: ");
double d = Double.parseDouble(s);

2
-1 per non aver risposto alla domanda. Non vuole leggere da una console, ma piuttosto dallo standard input.
— Ingo

La domanda afferma chiaramente che non vuole leggere dalla console. comunque grazie per aver dato qualche info su come leggere da console.
— Srivastav

4

controlla questo:

import java.io.*;
public class UserInputInteger
{
        public static void main(String args[])throws IOException
        {
        InputStreamReader read = new InputStreamReader(System.in);
        BufferedReader in = new BufferedReader(read);
        int number;
                System.out.println("Enter the number");
                number = Integer.parseInt(in.readLine());
    }
}

3

Ciò causa mal di testa, quindi ho aggiornato una soluzione che verrà eseguita utilizzando gli strumenti hardware e software più comuni disponibili per gli utenti a dicembre 2014. Si noti che JDK / SDK / JRE / Netbeans e le classi successive, i compilatori di librerie di modelli, gli editor e il debuggerz sono gratuito.

Questo programma è stato testato con Java v8 u25. È stato scritto e costruito utilizzando
Netbeans IDE 8.0.2, JDK 1.8, il sistema operativo è win8.1 (scuse) e il browser è Chrome (doppie scuse) - pensato per assistere l'accordo di UNIX-cmd-line OG con la moderna GUI-Web-based IDE a COSTO ZERO - perché le informazioni (e gli IDE) dovrebbero essere sempre libere. Di Tapper7. Per tutti.

blocco di codice:

    package modchk; //Netbeans requirement.
    import java.util.Scanner;
    //import java.io.*; is not needed Netbeans automatically includes it.           
    public class Modchk {
        public static void main(String[] args){
            int input1;
            int input2;

            //Explicity define the purpose of the .exe to user:
            System.out.println("Modchk by Tapper7. Tests IOStream and basic bool modulo fxn.\n"
            + "Commented and coded for C/C++ programmers new to Java\n");

            //create an object that reads integers:
            Scanner Cin = new Scanner(System.in); 

            //the following will throw() if you don't do you what it tells you or if 
            //int entered == ArrayIndex-out-of-bounds for your system. +-~2.1e9
            System.out.println("Enter an integer wiseguy: ");
            input1 = Cin.nextInt(); //this command emulates "cin >> input1;"

            //I test like Ernie Banks played hardball: "Let's play two!"
            System.out.println("Enter another integer...anyday now: ");
            input2 = Cin.nextInt(); 

            //debug the scanner and istream:
            System.out.println("the 1st N entered by the user was " + input1);
            System.out.println("the 2nd N entered by the user was " + input2);

            //"do maths" on vars to make sure they are of use to me:
            System.out.println("modchk for " + input1);
            if(2 % input1 == 0){
                System.out.print(input1 + " is even\n"); //<---same output effect as *.println
                }else{
                System.out.println(input1 + " is odd");
            }//endif input1

            //one mo' 'gain (as in istream dbg chk above)
            System.out.println("modchk for " + input2);
            if(2 % input2 == 0){
                System.out.print(input2 + " is even\n");
                }else{
                System.out.println(input2 + " is odd");
            }//endif input2
        }//end main
    }//end Modchk
Utilizzando il nostro sito, riconosci di aver letto e compreso le nostre Informativa sui cookie e Informativa sulla privacy.
Licensed under cc by-sa 3.0 with attribution required.