探索Java Scanner类

在Java编程中,处理用户输入和文件读取是常见的任务。Scanner类是Java提供的一个强大的工具类,用于简化这些操作。本文将详细介绍Scanner类的基本用法、常见应用场景和高级功能,并提供代码示例帮助理解。

一、什么是Scanner类

Scanner类属于java.util包,用于解析基本类型和字符串类型的输入。它可以从控制台、文件、字符串等不同的数据源读取数据,并将其解析为适当的类型。

1.1 基本构造方法

  • 从控制台输入读取:

    Scanner scanner = new Scanner(System.in);
    
  • 从文件读取:

    File file = new File("input.txt");
    Scanner scanner = new Scanner(file);
    
  • 从字符串读取:

    String input = "Hello World!";
    Scanner scanner = new Scanner(input);
    

二、基本用法

2.1 读取基本类型

Scanner类可以读取多种基本数据类型,如intdoubleboolean等。

  • 读取整数:

    Scanner scanner = new Scanner(System.in);
    System.out.print("Enter an integer: ");
    int number = scanner.nextInt();
    System.out.println("You entered: " + number);
    
  • 读取浮点数:

    Scanner scanner = new Scanner(System.in);
    System.out.print("Enter a double: ");
    double number = scanner.nextDouble();
    System.out.println("You entered: " + number);
    
  • 读取布尔值:

    Scanner scanner = new Scanner(System.in);
    System.out.print("Enter true or false: ");
    boolean bool = scanner.nextBoolean();
    System.out.println("You entered: " + bool);
    

2.2 读取字符串

  • 读取单个单词:

    Scanner scanner = new Scanner(System.in);
    System.out.print("Enter a word: ");
    String word = scanner.next();
    System.out.println("You entered: " + word);
    
  • 读取整行文本:

    Scanner scanner = new Scanner(System.in);
    System.out.print("Enter a line: ");
    String line = scanner.nextLine();
    System.out.println("You entered: " + line);
    

2.3 判断输入是否有下一个元素

Scanner类提供了多种方法来检查输入中是否有下一个元素:

  • hasNext():检查是否有下一个字符串
  • hasNextInt():检查是否有下一个整数
  • hasNextDouble():检查是否有下一个浮点数
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
if (scanner.hasNextInt()) {
    int number = scanner.nextInt();
    System.out.println("You entered: " + number);
} else {
    System.out.println("That's not an integer.");
}

三、从文件读取数据

Scanner类可以方便地从文件中读取数据。需要注意的是,在使用Scanner类读取文件时,需要处理可能的FileNotFoundException异常。

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class FileReadExample {
    public static void main(String[] args) {
        try {
            File file = new File("input.txt");
            Scanner scanner = new Scanner(file);

            while (scanner.hasNextLine()) {
                String line = scanner.nextLine();
                System.out.println(line);
            }

            scanner.close();
        } catch (FileNotFoundException e) {
            System.out.println("File not found.");
            e.printStackTrace();
        }
    }
}

四、使用正则表达式分割输入

Scanner类可以使用正则表达式来分割输入数据。例如,可以使用空格、逗号或其他符号作为分隔符。

import java.util.Scanner;

public class RegexExample {
    public static void main(String[] args) {
        String input = "apple,banana,orange";
        Scanner scanner = new Scanner(input);
        scanner.useDelimiter(",");

        while (scanner.hasNext()) {
            String fruit = scanner.next();
            System.out.println(fruit);
        }

        scanner.close();
    }
}

五、高级用法

5.1 设置输入的分隔符

Scanner类默认使用空白字符(空格、制表符、换行符等)作为分隔符,但可以自定义分隔符。

Scanner scanner = new Scanner(System.in);
scanner.useDelimiter(","); // 使用逗号作为分隔符
System.out.print("Enter comma-separated values: ");
while (scanner.hasNext()) {
    String value = scanner.next();
    System.out.println("Value: " + value);
}

5.2 处理不同的字符编码

读取文件时,可以指定字符编码。

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class EncodingExample {
    public static void main(String[] args) {
        try {
            File file = new File("input.txt");
            Scanner scanner = new Scanner(file, "UTF-8");

            while (scanner.hasNextLine()) {
                String line = scanner.nextLine();
                System.out.println(line);
            }

            scanner.close();
        } catch (FileNotFoundException e) {
            System.out.println("File not found.");
            e.printStackTrace();
        }
    }
}

六、总结

Scanner类是Java中处理输入的强大工具,不仅能够从控制台读取数据,还能从文件、字符串中提取信息。通过对Scanner类的灵活运用,开发者可以高效地完成各种输入输出任务。本文介绍了Scanner类的基本用法、常见应用场景和高级功能,并提供了丰富的代码示例,帮助你全面掌握Scanner类的使用。

希望本文能为你提供一个清晰的Scanner类入门指南。如果有任何问题或需要进一步的说明,请随时联系我。

  • 16
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
好的,下面是一个用Java编写的简单文本游戏,其中包含文本存储选择过程。 在这个游戏中,玩家将扮演一个勇敢的冒险家,他需要通过与NPC交互和找到物品来探索迷失之地,并最终找到宝藏。游戏将在控制台上运行,并使用Java的文件I / O来存储游戏进度。 ``` import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.Scanner; public class TextAdventureGame { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); boolean gameInProgress = true; String playerName = ""; int playerHealth = 100; int playerScore = 0; String playerInventory = ""; int currentRoom = 1; // 欢迎玩家 System.out.println("欢迎来到迷失之地!"); System.out.println("请问您的名字是什么?"); playerName = scanner.nextLine(); System.out.println("欢迎 " + playerName + "!"); // 加载玩家进度 File saveFile = new File(playerName + ".txt"); if (saveFile.exists()) { try { Scanner fileScanner = new Scanner(saveFile); playerHealth = fileScanner.nextInt(); playerScore = fileScanner.nextInt(); playerInventory = fileScanner.next(); currentRoom = fileScanner.nextInt(); System.out.println("您已经有了进度,要继续之前的游戏吗?(Y / N)"); String continueGame = scanner.nextLine(); if (continueGame.equalsIgnoreCase("Y")) { System.out.println("继续上次游戏..."); } else { System.out.println("重新开始游戏..."); saveFile.delete(); } } catch (IOException e) { System.out.println("读取进度文件出错!"); } } // 游戏循环 while (gameInProgress) { System.out.println("您现在在房间 " + currentRoom); System.out.println("请选择您要执行的操作:"); System.out.println("1. 探索房间"); System.out.println("2. 与NPC交互"); System.out.println("3. 查看背包"); System.out.println("4. 保存并退出游戏"); String choice = scanner.nextLine(); switch (choice) { case "1": System.out.println("您在房间内寻找物品..."); // 在这里添加探索房间的逻辑,例如查找物品并将其添加到玩家库存中 break; case "2": System.out.println("您与NPC交谈..."); // 在这里添加与NPC交互的逻辑,例如接受任务或获得提示 break; case "3": System.out.println("您查看您的背包..."); System.out.println("您的库存是:" + playerInventory); break; case "4": System.out.println("正在保存并退出游戏..."); try { FileWriter writer = new FileWriter(saveFile); writer.write(playerHealth + " " + playerScore + " " + playerInventory + " " + currentRoom); writer.close(); } catch (IOException e) { System.out.println("保存进度文件出错!"); } gameInProgress = false; break; default: System.out.println("无效的选择!"); break; } } System.out.println("谢谢游玩!"); } } ``` 注意:这个游戏只是一个简单的示例。您可以根据自己的喜好和需求来扩展和修改代码。同时,这种方式存储文本进度可能不是最优解,您可以使用其他方法来存储游戏进度,例如使用数据库或云存储。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值