Java 从键盘读一个String型变量

来源:互联网 发布:c语言指针例题 编辑:程序博客网 时间:2024/05/17 02:52
在网易论坛JAVA版里看见这么一个问题:
主题:Java 从键盘读一个String型变量 怎么写啊?

Re:Java 从键盘读一个String型变量 怎么写啊?
用    DataInputStream
给你写个简单的例子,你看看:
(从键盘输入,判断输入是否为中文)
Code:
import java.io.*;
class strHz{
 public static void main(String args[]){
   DataInputStream is=new DataInputStream(System.in);
   try{
       String str=is.readLine();
       byte a[]=str.getBytes();
       if(a[0]>0)
          System.out.println("You enter is chinese");
       else
          System.out.println("You enter is not chinese");
        }catch(Exception e){ }
  }
}


   近几天在研究JAVA中的流,真的是稀里糊涂。
依稀记得DataInputStream 没有readLine()方法。
查了一下手册,得到如下结论:
嗯,DataInputStream的readLine()方法已经不提倡使用了。
应该使用BufferedReader的readLine()方法代替它。
应该这样,
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String str = br.readLine();

JDK参考手册上的内容:

readLine()  
         Deprecated. This method does not properly convert bytes to characters. As of JDK 1.1, the preferred way to read lines of text is via the BufferedReader.readLine() method. Programs that use the DataInputStream class to read lines can be converted to use the BufferedReader class by replacing code of the form:  
    DataInputStream d = new DataInputStream(in);
 
with:  
    BufferedReader d
         = new BufferedReader(new InputStreamReader(in));
原创粉丝点击