学习java也有一段时日了,每当要输出显示的时候,System.out.println就会被我毫不犹豫地敲了出来。今天突然看到一小程序,大致如下:
……
public static void main(String args[]) throws IOException {
int x;
System.out.println("请输入考生成绩:");
x=System.in.read();
if ((x >= 0) && (x <= 100)) {
System.out.println("您输入的考生成绩是:" + x);
……
} else
System.out.println("对不起,您输入的数据是非法的");
}
……
得到的结果出乎我意料:
请输入考生成绩:
1
您输入的考生成绩是:49
请输入考生成绩:
4
您输入的考生成绩是:52
原来System.in.read()从控制台是按字符读取,x的值是该字符的ASCII码值。所以要对该字符简单“包装”一下:
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
x=Integer.parseInt(in.readLine()); //如果要读取字符串,则:String s =in.readLine();
这样我们就可以得到我们想要的输入值啦。
下面是一个引自冷月学堂的一个详细示例:
使用 System.in 就可以捕获控制台输入。System.in 是一个 InputStream 的实例,为了方便,我们还可以使用 BufferedReader 来包装这个对象。
/*
* @(#) Test.java
* @author James Fancy
*/
package jamesfancy;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Test {
public static void main(String[] args) throws IOException {
// 用 BufferedReader 包装 System.in,以便更方便的读取输入
// 主要是为了使用 readLine() 方法来读取
BufferedReader reader = new BufferedReader(new InputStreamReader(
System.in));
/* 读入字符串的示例 */
System.out.print("What's your name: ");
String name = reader.readLine();
/* 读入 boolean 值的示例 */
boolean male = false;
// 如果输入的不是 true 或者 false,就一直循环直到输入正确为止
while (true) {
System.out.print("Are you male (True/False): ");
// 读入输入内容
String sMale = reader.readLine().trim();
// 判断输入是否符合要求
if (sMale.equalsIgnoreCase("true")
|| sMale.equalsIgnoreCase("false")) {
// 将字符串转换成 boolean
male = Boolean.parseBoolean(sMale);
break;
} else {
// 不符合要求的时候输出提示信息
System.out.println("You can only input TRUE or FALSE here.");
}
}
/* 读入整数值的示例 */
int age = 0;
while (true) {
System.out.print("How old are you: ");
// 读入输入的字符串(它可能是一个整数)
String sAge = reader.readLine();
try {
// 将字符串转换为 int 值
// 如果输入的不是整数,转换时会抛 NumberFormatException
age = Integer.parseInt(sAge);
break;
} catch (NumberFormatException nfe) {
// 如果输入有误,提示
System.out.println("Please input a integer as your age.");
}
}
/* 输出读入的信息 */
System.out.println("Hello " + name + ". I am so glad to meet you, a "
+ age + " years old pretty " + (male ? "boy" : "girl") + ".");
}
}
/* Result of executing */
//What's your name: James Fancy
//Are you male (True/False): yes
//You can only input TRUE or FALSE here.
//Are you male (True/False): true
//How old are you: twenty-five
//Please input a integer as your age.
//How old are you: 25
//Hello James Fancy. I am so glad to meet you, a 25 years old pretty boy.