来源:菜鸟教程
1.Java的控制台输入由System.in完成。为了获得一个绑定到控制台的字符流,我们可以把System.in包装在一个BufferedReader对象中创建一个字符流,基本语法如下:
BufferedReader br=new BufferedReader(new Input StreamReader(System.in));
我们可以用read()方法从控制台读取一个字符,也可以用readLine()方法读取一个字符串
2.read()方法的语法如下:
int read() throws IOException
每次调用该方法,它从输入流中读取一个字符并把该字符作为整数值返回,流结束的时候返回-1.该方法抛出IOException。
使用实例:
import java.io.*;
public class first{
public static void main(String[] args) throws IOException{
char c;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("输入字符,按下‘q’键退出");
do{
c=(char) br.read();
System.out.print(c);
}while(c!='q');
}
}
3.从控制台读取字符串,用readLine()方法,和read()一个样,不过它的返回类型是字符串:
String readLine() throws IOException;
实例:
import java.io.*;
public class first{
public static void main(String[] args) throws IOException{
String str;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("读取的字符串为");
do{
str=(String) br.readLine();
System.out.println(str);
}while(!str.equals("end"));
}
}