InputStreamReader
比Scanner
类有什么优势?
扫描仪在所有方面对我来说似乎都更好。
为什么我必须将throws IOException
与InputStreamReader
一起使用?
例如:-
1)
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
2)
Scanner sc=new Scanner(System.in);
1)可以做什么,2)不能做什么?
答案 0 :(得分:0)
使用缓冲读取器时,我们需要导入java.io包,因此我们需要通过try和catch或使用throws Exception处理异常。在nextInt之后使用nextLine时,使用Scanner类有一个缺点: 它不读取值并且输出与预期输出不同
//示例扫描仪
import java.util.Scanner;
public class c
{
public static void main(String args[])
{
Scanner scn = new Scanner(System.in);
System.out.println("Enter an integer");
int a = scn.nextInt();
System.out.println("Enter a String");
String b = scn.nextLine();
System.out.printf("You have entered:- "+ a + " " + "and name as " + b);
}
}
输入:2,rajat
预期输出:You have entered:-2 and name as rajat
实际输出:You have entered:-2 and name as
它不需要在字符串b中使用rajat,而BufferReader类没有这种问题
//示例缓冲读取器
import java.io.*;
class c
{
public static void main(String args[]) throws IOException
{
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
System.out.println("Enter an integer");
int a = Integer.parseInt(br.readLine());
System.out.println("Enter a String");
String b = br.readLine();
System.out.printf("You have entered:- " + a + " and name as " + b);
}
}
输入2,rajat
预期输出:You have entered:-2 and name as rajat
实际输出:You have entered:-2 and name as rajat