方法一:
使用System.in和InputStream
package za;
import java.io.InputStream;
public class InputTest
{
public static void main(String arg[]) throws Exception
{
InputStream input=System.in;
StringBuffer buf=new StringBuffer();
System.out.println("请输入内容:");
int temp=0;
while((temp=input.read())!=-1)
{
char c=(char)temp;
if(c=='\n')
break;
buf.append(c);
}
System.out.println("输入的内容为:"+buf);
input.close();
}
}
当输入:you are my sunshine!
输出:you are my sunshine!
当输入:李元霸
输出:??????
汉字不正常显示原因:因为数据是一个字节一个字节读入的,而汉字是双字节的
程序改进:
package za;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class InputTest
{
public static void main(String arg[]) throws Exception
{
BufferedReader buf=null;
buf=new BufferedReader(new InputStreamReader(System.in));
String str=null;
System.out.println("请输入内容:");
try{
str=buf.readLine();
}catch(IOException e)
{
e.printStackTrace();
}
System.out.println("输入的内容为:"+str);
}
}
输入:hello,李元霸!
输入:hello,李元霸!
方法二:
使用Scanner类
package za;
import java.util.Scanner;
public class InputTest
{
public static void main(String arg[]) throws Exception
{
Scanner scan=new Scanner(System.in);
System.out.print("输入数据:");
String str=scan.next();
System.out.println("输入输入为:"+str);
scan.close();
}
}
输入:hello world
输出:hello
原因:Scanner默认以空格作为分隔符,我们可以将'\n'回车作为分隔符。修改代码如下:
package za;
import java.util.Scanner;
public class InputTest
{
public static void main(String arg[]) throws Exception
{
Scanner scan=new Scanner(System.in);
scan.useDelimiter("\n");
System.out.print("输入数据:");
String str=scan.next();
System.out.println("输入输入为:"+str);
scan.close();
}
}
输入:hello 李元霸
输出:hello 李元霸