English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Java Base Tutorial

Contrôle de flux Java

Java Tableau

Java Orienté Objet (I)

Java Orienté Objet (II)

Java Orienté Objet (III)

Java Exception Handling

Java Liste (List)

Java Queue (filet)

Java Map collectif

Java Set collectif

Java Entrée Sortie (I/O)

Java Reader/Writer

Autres sujets Java

Java Scanner class

Dans ce tutoriel, nous allons apprendre Java Scanner et ses méthodes à l'aide d'exemples.

La classe PrintWriter du paquet java.io peut être utilisée pour écrire des données de sortie sous une forme lisible (texte).

La classe Scanner du paquet java.util est utilisée pour lire des données d'entrée à partir de différentes sources (par exemple, flux d'entrée, utilisateurs, fichiers, etc.). Laissons-nous donner un exemple.

Exemple1:Lire une ligne de texte avec le scanner

import java.util.Scanner;
class Main {
    public static void main(String[] args) {
        //Créer un objet Scanner
        Scanner input = new Scanner(System.in);
        System.out.print("Entrer le nom: ");
        // Recevoir l'entrée du clavier
        String name = input.nextLine();
        // Affichez le nom
        System.out.println("Mon nom est " + name);
        // Ferme le scanner
        input.close();
    }
}

Output result

Entrer le nom: Jack
Mon nom est  Jack

Dans l'exemple ci-dessus, veuillez noter les lignes suivantes

Scanner input = new Scanner(System.in);

Ici, nous créons un objet Scanner nommé input.

Le paramètre System.in est utilisé pour obtenir l'entrée à partir de l'entrée standard. C'est comme obtenir une entrée à partir du clavier.

Ensuite, nous utilisons la méthode nextLine() de la classe Scanner pour lire une ligne de texte de l'utilisateur.

Maintenant que vous avez quelques connaissances sur Scanner, explorons-le plus en détail.

Importer la classe scanner

Comme vous pouvez le voir dans l'exemple ci-dessus, nous devons d'abord importer le paquet java.util.Scanner, puis nous pouvons utiliser la classe Scanner.

import java.util.Scanner;

Créer un objet scanner en Java

Comme mentionné précédemment, après avoir importé le paquet, vous pouvez créer un objet Scanner.

//从输入流中读取输入
Scanner sc1 = new Scanner(InputStream input);
//从文件读取输入
Scanner sc2 = new Scanner(File file);
//从字符串中读取输入
Scanner sc3 = new Scanner(String str);

在这里,我们创建了Scanner类的对象,这些对象将分别从InputStream,文件和字符串读取输入。

Java扫描器输入方法

Scanner类提供各种方法,使我们能够读出不同类型的输入。

方法描述
nextInt()从用户读取int值
nextFloat()从用户读取float值
nextBoolean()从用户读取boolean值
nextLine()从用户读取一行文本
next()从用户那里读取一个单词
nextByte()从用户读取byte值
nextDouble()从用户读取double值
nextShort()从用户读取short值
nextLong()从用户读取long值

Exemple2:Java扫描器nextInt()

import java.util.Scanner;
class Main {
    public static void main(String[] args) {
        //创建扫描器对象
        Scanner input = new Scanner(System.in);
        System.out.println("输入一个整数: ")
        //读取一个int值
        int data1 = input.nextInt();
        System.out.println("使用 nextInt(): ") + data1);
        input.close();
    }
}

Output result

输入一个整数:
22
使用 nextInt(): 22

在上面的示例中,我们使用了nextInt()方法来读取整数值。

Exemple3:Java 扫描器nextDouble()方法

import java.util.Scanner;
class Main {
   public static void main(String[] args) {
      //Créer un objet Scanner
      Scanner input = new Scanner(System.in);
      System.out.print("输入双精度值: ")
      //读取双精度值
      double value = input.nextDouble();
      System.out.println("使用 nextDouble(): ") + value);
      input.close();
   }
}

Output result

输入双精度值: 33.33
使用 nextDouble(): 33.33

在上面的示例中,我们使用了nextDouble()方法来读取浮点值。

Exemple4:Java扫描器next()方法

import java.util.Scanner;
class Main {
   public static void main(String[] args) {
      //Créer un objet Scanner
      Scanner input = new Scanner(System.in);
      System.out.print("Enter your name: ");
      //读取整个单词
      String value = input.next();
      System.out.println("Using next(): ") + value);
      input.close();
   }
}

Output result

Enter your name: Jonny Walker
Using next(): Jonny

Dans l'exemple précédent, nous avons utilisé la méthode next() pour lire une chaîne de l'utilisateur.

ici, nous avons fourni le nom complet. Mais la méthode next() ne lit que le nom.

c'est parce que la méthode next() lit l'entrée jusqu'àespacecaractères. Une fois qu'il rencontre un espace, il retourne une chaîne (sans espace).

Exemple5:Méthode nextLine() du scanner Java

import java.util.Scanner;
class Main {
   public static void main(String[] args) {
      //Créer un objet Scanner
      Scanner input = new Scanner(System.in);
      System.out.print("Enter your name: ");
      //Lire une ligne entière
      String value = input.nextLine();
      System.out.println("Using nextLine(): "); + value);
      input.close();
   }
}

Output result

Enter your name: Jonny Walker
Using nextLine(): Jonny Walker

Dans le premier exemple, nous avons utilisé la méthode nextLine() pour lire une chaîne de l'utilisateur.

Contrairement à next(), la méthode nextLine() lit toute la ligne d'entrée, y compris les espaces. La méthode se termine lorsque cette méthode rencontre le caractère de fin de ligne \n.

Scanner Java BigInteger et BigDecimal

Le programmeur Java peut également être utilisé pour lire des grands entiers et des nombres décimaux.

  • nextBigInteger() - Lire la valeur grand entier de l'utilisateur

  • nextBigDecimal() - Lire la valeur grand nombre décimal de l'utilisateur

Exemple4:Lire BigInteger et BigDecimal

import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.Scanner;
class Main {
   public static void main(String[] args) {
      //Créer un objet Scanner
      Scanner input = new Scanner(System.in);
      System.out.print("Entrez un grand entier: ");
      //Lire un grand entier
      BigInteger value1 input.nextBigInteger();
      System.out.println("Using nextBigInteger(): "); + value1);
      System.out.print("Entrez un grand nombre décimal: ");
      //Lire un grand nombre décimal
      BigDecimal value2 input.nextBigDecimal();
      System.out.println("Using nextBigDecimal(): ") + value2);
      input.close();
   }
}

Output result

Enter a large integer: 987654321
Use nextBigInteger(): 987654321
Enter a large decimal: 9.55555
Use nextBigDecimal(): 9.55555

In the above example, we use the java.math.BigInteger and java.math.BigDecimal packages to read BigInteger and BigDecimal respectively.

How Java scanner works

The scanner class reads the entire line and splits the line into tokens. Tokens are small elements that have meaning to the Java compiler. For example

Suppose there is an input string:

He is 22

In this case, the scanner object will read the entire line and split the string into tokens: “ He ”,“ is ” and “ 22 ». Then, the object traverses each token and uses its different methods to read each token.

NoteBy default, spaces are used to delimit tokens.