日期:2014-05-20  浏览次数:21007 次

如何从控制台输入数据?
初学java,请大家指点

------解决方案--------------------
String res= " ";
byte[]buf=new byte[512];
java.io.InputStream in=System.in;
try {
in.read(buf);
} catch (IOException e) {
e.printStackTrace();
}
res=new String(buf);
------解决方案--------------------
Scanner 类
或者用流 不过麻烦点
------解决方案--------------------
Scanner scanner=new Scanner(System.in);
System.out.print( "请输入您的数据: ");

int num=scanner.nextInt();

System.out.pringtln(num);
------解决方案--------------------
刚好前两天回答问题时,写过类似的代码,你看看吧,看能用得上么。

public static void main(String args[]){

boolean quitFlag = false ;
String lastLine = " " ;
BufferedReader stdin = null ;

System.out.println( "输入exit来退出 ");

while (!quitFlag){

try{
stdin = new BufferedReader( new InputStreamReader(System.in));
lastLine = stdin.readLine() ;
}catch (IOException e){
e.printStackTrace();
}

if (lastLine.trim().toLowerCase().equals( "exit ".toLowerCase())) {
quitFlag = true ;
System.out.println( "再见! ");
System.exit(0);
}

System.out.println( "你刚才输入了 " +lastLine.lenght() + "字符 ");
}
}
------解决方案--------------------
我也很关注这个问题。

我知道一种方法 用byte数组接收输入的字节
byte[] b = new byte[100];
try{
System.out.in(b);
}catch(IOException ioe){
ioe.printStackTrace();
}
String s = new String(b);//把byte数组转换成字符串
s = s.trim();//消除前后空格

那么s就是输入的字符串了.

是不是觉得很麻烦,我个人觉得很麻烦,至于为什么,我也不知道.
------解决方案--------------------
学习
------解决方案--------------------
java一痛~~~
java 1.5引进了Scanner类,在某种程度上解决了从标准输入的读入的问题。
------解决方案--------------------
用System.in.read()也行,以下是输入字符串并输出的例子:

import java.io.*;

class Test {
public static void main(String args[]) {
char ch[]=new char[60];
int i=0,j;
System.out.print( "please input: ");
/*请输入字符串,直到回车结束*/
while( (ch[i]=(char)System.in.read())!= '\n ')
i++;
/*输出字符串*/
for(j=0;j <=ch.length-1;j++)
System.out.print(ch[j]);

}
}