java从键盘输入内容方法小结

方法一:

使用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 李元霸











  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值