Scanner 类

发布: (2026年2月20日 GMT+8 21:53)
2 分钟阅读
原文: Dev.to

Source: Dev.to

Java 中的类

对 Java 中类概念的定义。

为什么使用 Scanner?

Scanner 类简化了从各种来源(例如键盘)读取输入的过程。

如何使用 Scanner

步骤 1:导入包

import java.util.Scanner;

步骤 2:创建 Scanner 对象

Scanner sc = new Scanner(System.in);

System.in → 从键盘获取输入。

步骤 3:读取输入

int age = sc.nextInt();
String name = sc.nextLine();
double salary = sc.nextDouble();

重要概念

如果你写:

int age = sc.nextInt();

随后调用的 nextLine() 可能会被跳过,因为 nextInt() 不会 消耗换行符。

正确做法

int age = sc.nextInt();
sc.nextLine(); // 消耗剩余的换行符
String name = sc.nextLine();

常用 Scanner 方法

  • nextInt() – 读取整数
  • nextLine() – 读取一行文本
  • nextDouble() – 读取双精度数

始终关闭 Scanner

sc.close();

示例

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        System.out.println("Enter Tamil mark:");
        int tamil = sc.nextInt();

        System.out.println("Enter English mark:");
        int english = sc.nextInt();

        System.out.println("Enter Maths mark:");
        int maths = sc.nextInt();

        System.out.println("Enter Science mark:");
        int science = sc.nextInt();

        System.out.println("Enter Social mark:");
        int social = sc.nextInt();
        sc.nextLine(); // consume newline

        System.out.println("Student name:");
        String name = sc.nextLine();

        int total = tamil + english + maths + science + social;
        System.out.println("Total Marks: " + total);
        System.out.println("Student name: " + name);

        sc.close(); // Good practice
    }
}
0 浏览
Back to Blog

相关文章

阅读更多 »

Java 中的接口

介绍 在 Java 中,接口用于实现抽象和多继承。它定义了类应该做什么,而不是如何去做。什么...