無語北極

Why always just a silent watcher,but not in it?

原创 Java 控制台输入收藏

新一篇: Wicket 框架初探 | 旧一篇: js 几种常用的表单输入验证

学习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.


发表于 @ 2005年09月19日 22:05:00|评论(loading...)|编辑

新一篇: Wicket 框架初探 | 旧一篇: js 几种常用的表单输入验证

评论

#more207 发表于2007-09-10 13:07:46  IP: 221.201.201.*
有道理!! 谢谢这位老大。
发表评论  


当前用户设置只有注册用户才能发表评论。如果你没有登录,请点击登录
Csdn Blog version 3.1a
Copyright © 無語北極