web-dev-qa-db-fra.com

Comment lire une valeur entière à partir de l'entrée standard dans Java

Quelle classe puis-je utiliser pour lire une variable entière en Java?

106
Nehil Verma

Vous pouvez utiliser Java.util.Scanner ( API ):

import Java.util.Scanner;

//...

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

Il peut également segmenter les entrées avec une expression régulière, etc. L'API a des exemples et il y en a beaucoup d'autres sur ce site (par exemple: Comment empêcher un scanner de générer des exceptions lorsque le type incorrect est entré? ).

135
polygenelubricants

Si vous utilisez Java 6, vous pouvez utiliser l'un des éléments suivants pour lire un entier à partir de la console:

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

Ici, je fournis 2 exemples pour lire une valeur entière à partir de l'entrée standard

Exemple 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);
   }
 }

Exemple 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);
     }
 }

Je préfère le premier exemple, c'est facile et assez compréhensible.
Vous pouvez compiler et exécuter les programmes Java en ligne sur ce site Web: http://ideone.com

17
Srivastav Reddy

Vérifier celui-ci:

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();
    }
}
11
thelost

vérifier celui-ci:

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());
    }
}
4
madhav

La deuxième réponse ci-dessus est la plus simple.

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

La question est "Comment lire depuis une entrée standard".

Une console est un périphérique généralement associé au clavier et à l'écran à partir duquel un programme est lancé.

Vous voudrez peut-être tester si aucun périphérique de console Java n'est disponible, par exemple. Java VM non démarré à partir d'une ligne de commande ou les flux d'entrée et de sortie standard sont redirigés.

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

Utiliser la console est un moyen simple de saisir des nombres. Combiné avec parseInt ()/Double () etc.

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

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

Cela a posé des problèmes. J'ai donc mis à jour une solution qui fonctionnera à l'aide des outils matériels et logiciels les plus courants disponibles pour les utilisateurs en décembre 2014. Veuillez noter que JDK/SDK/JRE/Netbeans et leurs classes, compilateurs de bibliothèques de modèles, éditeurs et débogueurs libre.

Ce programme a été testé avec Java v8 u25. Il a été écrit et construit en utilisant
Netbeans IDE 8.0.2, JDK 1.8, OS vaut Win8.1 (excuses) et le navigateur est Chrome (double excuses) - destiné à aider UNIX-cmd. -line OG a conclu un accord avec ZERO COST sur les IDE modernes basés sur une interface graphique pour le Web - car les informations (et les IDE) devraient toujours être gratuites. Par Tapper7. Pour tout le monde.

bloc de code:

    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
2
Tapper7