Java输入输出方式(一)

利用 BufferedReader 对象 输入字符和字符串

1、输入字符,用read()实现

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		System.out.println("输入字符,输入q结束:");
		char c;
		do {
			c = (char) br.read();
			System.out.println(c);
		} while (c != 'q');

2、输入字符串,用readLine() 实现

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		System.out.println("输入字串,输入end结束:");
		String str;
		do {
			str = (String) br.readLine();
			System.out.println(str);
		} while (!str.equals("end"));

利用 Scanner 对象输入字符串

1、利用next() 方法输入单个字符串,遇到空格后停止

Scanner scan = new Scanner(System.in);
		if (scan.hasNext()) {
			String string = (String) scan.next();
			System.out.println("输入的字符串为:" + string);
		}
		scan.close();

2、利用nextLine()方法输入有空格的字符串

Scanner scan = new Scanner(System.in);
		if (scan.hasNextLine()) {
			String string = (String) scan.nextLine();
			System.out.println("输入的字符串为:" + string);
		}
		scan.close();

对比一下可以发现,next()中空格是无效输入,未接收有效输入前被忽略,接收有效输入后作为分隔符或者结束符。而nextLine()中空格可以作为有效输入,以回车作为结束符。