Java控制台输入输出

控制台输入输出 (Scanner和print,比较好)

BufferedReader 是支持同步的,而 Scanner 不支持。如果我们处理多线程程序,BufferedReader 应当使用。

BufferedReader 相对于 Scanner 有足够大的缓冲区内存。

Scanner 有很少的缓冲区(1KB 字符缓冲)相对于 BufferedReader(8KB字节缓冲),但是这是绰绰有余的。

BufferedReader 相对于 Scanner 来说要快一点,因为 Scanner 对输入数据进行类解析,而 BufferedReader 只是简单地读取字符序列。

 

读取控制台输入

Java 的控制台输入由 System.in 完成。把 System.in 包装在一个 BufferedReader 对象中来创建一个字符流。

  • Standard Input     - 用于将数据发送到用户的程序,通常使用键盘作为标准输入流并表示为system.in。

  • Standard Output  -用于输出用户程序产生的数据,通常计算机屏幕用于标准输出流并表示为System.out。

  • Standard Error     -用于输出用户程序产生的错误数据,通常计算机屏幕用于标准错误流并表示为System.err

下面是创建 BufferedReader 的基本语法:

BufferedReader br = new BufferedReader(new 
                      InputStreamReader(System.in));

BufferedReader 对象创建后,我们便可以使用 read() 方法从控制台读取一个字符,或者用 readLine() 方法读取一个字符串。

int read( ) throws IOException
//从 BufferedReader 对象读取一个字符要使用 read() 方法
//使用 BufferedReader 在控制台读取字符
 
import java.io.*;
 
public class BRRead {
    public static void main(String[] args) throws IOException {
        char c = 'a';
        // 使用 System.in 创建 BufferedReader
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        System.out.println("输入字符, 按下 'q' 键退出。");
        // 读取字符
        do {
            c = (char) br.read();
            System.out.println(c);
        } while (c != 'q');
    }
}

 

String readLine( ) throws IOException
//从控制台读取字符串
//使用 BufferedReader 在控制台读取字符
import java.io.*;
 
public class BRReadLines {
    public static void main(String[] args) throws IOException {
        // 使用 System.in 创建 BufferedReader
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String str = "aa";
        System.out.println("Enter lines of text.");
        System.out.println("Enter 'end' to quit.");
        do {
            str = br.readLine();
            System.out.println(str);
        } while (!str.equals("end"));
    }
}

JDK 5 后的版本我们也可以使用 Java Scanner 类来获取控制台的输入

 

控制台输出

控制台的输出由 print( ) 和 println() 完成。这些方法都由类 PrintStream 定义,System.out 是该类对象的一个引用。

PrintStream 继承了 OutputStream类,并且实现了方法 write()。这样,write() 也可以用来往控制台写操作。

import java.io.*;
 
//演示 System.out.write().
//单字符输出char,输出字符串还是用print吧。鸡肋
public class WriteDemo { public static void main(String[] args) { int b; b = 'A'; System.out.write(b); System.out.write('\n'); } }

 

Scanner 类

通过 Scanner 类来获取用户的输入,创建 Scanner 对象的基本语法:

Scanner s = new Scanner(System.in);

演示一个最简单的数据输入,并通过 Scanner 类的 next() 与 nextLine() 方法获取输入的字符串,在读取前我们一般需要 使用 hasNext 与 hasNextLine 判断是否还有输入的数据:

使用 next 方法:

import java.util.Scanner; 
 
public class ScannerDemo {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        // 从键盘接收数据
 
        // next方式接收字符串
        System.out.println("next方式接收:");
        // 判断是否还有输入
        if (scan.hasNext()) {
            String str1 = scan.next();
            System.out.println("输入的数据为:" + str1);
        }
        scan.close();
    }
}
$ javac ScannerDemo.java
$ java ScannerDemo
next方式接收:
runoob com
输入的数据为:runoob

 

使用 nextLine 方法:

import java.util.Scanner;
 
public class ScannerDemo {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        // 从键盘接收数据
 
        // nextLine方式接收字符串
        System.out.println("nextLine方式接收:");
        // 判断是否还有输入
        if (scan.hasNextLine()) {
            String str2 = scan.nextLine();
            System.out.println("输入的数据为:" + str2);
        }
        scan.close();
    }
}
$ javac ScannerDemo.java
$ java ScannerDemo
nextLine方式接收:
runoob com
输入的数据为:runoob com

 

next() 与 nextLine() 区别

next():

  • 1、一定要读取到有效字符后才可以结束输入。
  • 2、对输入有效字符之前遇到的空白,next() 方法会自动将其去掉。
  • 3、只有输入有效字符后才将其后面输入的空白作为分隔符或者结束符。
  • next() 不能得到带有空格的字符串。

nextLine():

  • 1、以Enter为结束符,也就是说 nextLine()方法返回的是输入回车之前的所有字符。
  • 2、可以获得空白。

 

判断输入的是 int 或 float 类型的数据

import java.util.Scanner;
 
public class ScannerDemo {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        // 从键盘接收数据
        int i = 0;
        float f = 0.0f;
        System.out.print("输入整数:");
        if (scan.hasNextInt()) {
            // 判断输入的是否是整数
            i = scan.nextInt();
            // 接收整数
            System.out.println("整数数据:" + i);
        } else {
            // 输入错误的信息
            System.out.println("输入的不是整数!");
        }
        System.out.print("输入小数:");
        if (scan.hasNextFloat()) {
            // 判断输入的是否是小数
            f = scan.nextFloat();
            // 接收小数
            System.out.println("小数数据:" + f);
        } else {
            // 输入错误的信息
            System.out.println("输入的不是小数!");
        }
        scan.close();
    }
}

 

更多内容可以参考 API 文档:https://www.runoob.com/manual/jdk11api/java.base/java/util/Scanner.html

构造方法
构造器描述
Scanner​(File source)
构造一个新的 Scanner ,它生成从指定文件扫描的值。
Scanner​(File source, String charsetName)
构造一个新的 Scanner ,它生成从指定文件扫描的值。
Scanner​(File source, Charset charset)
构造一个新的 Scanner ,它生成从指定文件扫描的值。
Scanner​(InputStream source)
构造一个新的 Scanner ,它生成从指定输入流扫描的值。
Scanner​(InputStream source, String charsetName)
构造一个新的 Scanner ,它生成从指定输入流扫描的值。
Scanner​(InputStream source, Charset charset)
构造一个新的 Scanner ,它生成从指定输入流扫描的值。
Scanner​(Readable source)
构造一个新的 Scanner ,它生成从指定源扫描的值。
Scanner​(String source)
构造一个新的 Scanner ,它生成从指定字符串扫描的值。
Scanner​(ReadableByteChannel source)
构造一个新的 Scanner ,它可以生成从指定通道扫描的值。
Scanner​(ReadableByteChannel source, String charsetName)
构造一个新的 Scanner ,它可以生成从指定通道扫描的值。
Scanner​(ReadableByteChannel source, Charset charset)
构造一个新的 Scanner ,它可以生成从指定通道扫描的值。
Scanner​(Path source)
构造一个新的 Scanner ,它生成从指定文件扫描的值。
Scanner​(Path source, String charsetName)
构造一个新的 Scanner ,它生成从指定文件扫描的值。
Scanner​(Path source, Charset charset)
构造一个新的 Scanner ,它生成从指定文件扫描的值。

 

方法摘要

All MethodsInstance MethodsConcrete Methods
变量和类型方法描述
void close()
关闭此扫描仪。
Pattern delimiter()
返回 Pattern这 Scanner目前用于匹配分隔符。
Stream<MatchResult> findAll​(String patString)
返回与提供的模式字符串匹配的匹配结果流。
Stream<MatchResult> findAll​(Pattern pattern)
返回此扫描程序的匹配结果流。
String findInLine​(String pattern)
尝试查找从指定字符串构造的下一个模式,忽略分隔符。
String findInLine​(Pattern pattern)
尝试查找指定模式的下一个匹配项,忽略分隔符。
String findWithinHorizon​(String pattern, int horizon)
尝试查找从指定字符串构造的下一个模式,忽略分隔符。
String findWithinHorizon​(Pattern pattern, int horizon)
尝试查找指定模式的下一个匹配项。
boolean hasNext()
如果此扫描器的输入中有另一个标记,则返回true。
boolean hasNext​(String pattern)
如果下一个标记与从指定字符串构造的模式匹配,则返回true。
boolean hasNext​(Pattern pattern)
如果下一个完整标记与指定模式匹配,则返回true。
boolean hasNextBigDecimal()
如果此扫描器输入中的下一个标记可以使用 nextBigDecimal()方法解释为 BigDecimal则返回true。
boolean hasNextBigInteger()
如果此扫描器输入中的下一个标记可以使用 nextBigInteger()方法在默认基数中解释为 BigInteger ,则返回true。
boolean hasNextBigInteger​(int radix)
如果此扫描器输入中的下一个标记可以使用 nextBigInteger()方法在指定的基数中解释为 BigInteger ,则返回true。
boolean hasNextBoolean()
如果使用从字符串“true | false”创建的不区分大小写的模式,可以将此扫描器输入中的下一个标记解释为布尔值,则返回true。
boolean hasNextByte()
如果使用 nextByte()方法将此扫描器输入中的下一个标记解释为默认基数中的字节值,则返回true。
boolean hasNextByte​(int radix)
如果使用 nextByte()方法将此扫描器输入中的下一个标记解释为指定基数中的字节值,则返回true。
boolean hasNextDouble()
如果使用 nextDouble()方法将此扫描仪输入中的下一个标记解释为double值,则返回true。
boolean hasNextFloat()
如果使用 nextFloat()方法将此扫描器输入中的下一个标记解释为浮点值,则返回true。
boolean hasNextInt()
如果使用 nextInt()方法将此扫描器输入中的下一个标记解释为默认基数中的int值,则返回true。
boolean hasNextInt​(int radix)
如果此扫描器输入中的下一个标记可以使用 nextInt()方法解释为指定基数中的int值,则返回true。
boolean hasNextLine()
如果此扫描器的输入中有另一行,则返回true。
boolean hasNextLong()
如果使用 nextLong()方法将此扫描器输入中的下一个标记解释为默认基数中的长值,则返回true。
boolean hasNextLong​(int radix)
如果使用 nextLong()方法可以将此扫描器输入中的下一个标记解释为指定基数中的长值,则返回true。
boolean hasNextShort()
如果使用 nextShort()方法可以将此扫描器输入中的下一个标记解释为默认基数中的短值,则返回true。
boolean hasNextShort​(int radix)
如果此扫描器输入中的下一个标记可以使用 nextShort()方法解释为指定基数中的短值,则返回true。
IOException ioException()
返回 IOException最后通过此抛出 Scanner的基本 Readable 。
Locale locale()
返回此扫描程序的语言环境。
MatchResult match()
返回此扫描程序执行的上次扫描操作的匹配结果。
String next()
从此扫描仪查找并返回下一个完整令牌。
String next​(String pattern)
如果它与从指定字符串构造的模式匹配,则返回下一个标记。
String next​(Pattern pattern)
如果匹配指定的模式,则返回下一个标记。
BigDecimal nextBigDecimal()
将输入的下一个标记扫描为BigDecimal 。
BigInteger nextBigInteger()
将输入的下一个标记扫描为BigInteger 。
BigInteger nextBigInteger​(int radix)
将输入的下一个标记扫描为BigInteger 。
boolean nextBoolean()
将输入的下一个标记扫描为布尔值并返回该值。
byte nextByte()
将输入的下一个标记扫描为 byte 。
byte nextByte​(int radix)
将输入的下一个标记扫描为 byte 。
double nextDouble()
将输入的下一个标记扫描为 double 。
float nextFloat()
将输入的下一个标记扫描为 float 。
int nextInt()
将输入的下一个标记扫描为 int 。
int nextInt​(int radix)
将输入的下一个标记扫描为 int 。
String nextLine()
使此扫描器前进超过当前行并返回跳过的输入。
long nextLong()
将输入的下一个标记扫描为 long 。
long nextLong​(int radix)
将输入的下一个标记扫描为 long 。
short nextShort()
将输入的下一个标记扫描为 short 。
short nextShort​(int radix)
将输入的下一个标记扫描为 short 。
int radix()
返回此扫描器的默认基数。
void remove()
Iterator的此实现不支持删除操作。
Scanner reset()
重置此扫描仪。
Scanner skip​(String pattern)
跳过与指定字符串构造的模式匹配的输入。
Scanner skip​(Pattern pattern)
跳过与指定模式匹配的输入,忽略分隔符。
Stream<String> tokens()
从此扫描程序返回分隔符分隔的标记流。
String toString()
返回此 Scanner的字符串表示 Scanner 。
Scanner useDelimiter​(String pattern)
将此扫描仪的分隔模式设置为从指定的 String构造的模式。
Scanner useDelimiter​(Pattern pattern)
将此扫描仪的分隔模式设置为指定的模式。
Scanner useLocale​(Locale locale)
将此扫描程序的语言环境设置为指定的语言环境。
Scanner useRadix​(int radix)
将此扫描仪的默认基数设置为指定的基数。

 

具体的看API。

转自:https://www.runoob.com/java/java-scanner-class.html

posted @ 2022-09-21 11:36  云long  阅读(1585)  评论(0编辑  收藏  举报