Java控制台接收\输出数据

读取控制台输入

Java 的控制台输入由 System.in 完成。

为了获得一个绑定到控制台的字符流,你可以把 System.in 包装在一个 BufferedReader 对象中来创建一个字符流。

下面是创建 BufferedReader 的基本语法

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

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

从控制台读取多字符输入

从 BufferedReader 对象读取一个字符要使用 read() 方法,它的语法如下:

int read( ) throws IOException

每次调用 read() 方法,它从输入流读取一个字符并把该字符作为整数值返回。 当流结束的时候返回 -1。该方法抛出 IOException。

下面的程序示范了用 read() 方法从控制台不断读取字符直到用户输入 “q”。

//使用 BufferedReader 在控制台读取字符
import java.io.*;
public class BRRead {
public static void main(String args[]) throws IOException {
char c;
// 使用 System.in 创建 BufferedReader
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println(“输入字符, 按下 ‘q’ 键退出。”);
// 读取字符
do {
c = (char) br.read();
System.out.println©;
} while (c != ‘q’);
}
}

以上实例编译运行结果如下:

输入字符, 按下 ‘q’ 键退出。
runoob
r
u
n
o
o
b
q
q

从控制台读取多字符输入

从标准输入读取一个字符串需要使用 BufferedReader 的 readLine() 方法。

它的一般格式是:

String readLine( ) throws IOException

下面的程序读取和显示字符行直到你输入了单词"end"。

//使用 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;
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”));
}
}

以上实例编译运行结果如下:

Enter lines of text.
Enter ‘end’ to quit.
This is line one
This is line one
This is line two
This is line two
end
end

从控制台读取多字符输入

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

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

PrintStream 定义 write() 的最简单格式如下所示:

void write(int byteval)

该方法将 byteval 的低八位字节写到流中。

实例

下面的例子用 write() 把字符 “A” 和紧跟着的换行符输出到屏幕:

import java.io.*;
//演示 System.out.write().
public class WriteDemo {
public static void main(String args[]) {
int b;
b = ‘A’;
System.out.write(b);
System.out.write(’\n’);
}
}

运行以上实例在输出窗口输出 “A” 字符

A

我的笔记

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String str;
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”));

package text;
import java.io.*;
public class triangle {
public static void main(String[] args)throws IOException{
System.out.println(“Please enter the height of an isosceles triangle!”);
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String str = br.readLine();
int hight = Integer.parseInt(str);
System.out.println(hight);
}
}

猜你喜欢

转载自blog.csdn.net/qq_38893760/article/details/85050043