提问人:0xe82de 提问时间:8/5/2021 最后编辑:halfer0xe82de 更新时间:8/6/2021 访问量:181
使用扫描仪后可以使用bufferedreader吗?[复制]
Can I use bufferedreader after using scanner? [duplicate]
问:
我正在测试 Scanner 和 Bufferedreader。使用扫描仪后,我尝试使用BufferedReader。
但是,如果我关闭扫描仪,则会发生错误。为什么会出现错误?
我试过谷歌搜索,但我不明白。
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.Scanner;
public class ScannerAndBufferedReaderTest2 {
public static void main(String[] args) throws IOException {
// Scanner
Scanner sc = new Scanner(System.in);
System.out.print("Enter number : ");
int in1 = sc.nextInt();
sc.close(); // <-- If I erase this part, there will be no error.
System.out.println("Your number : " + in1);
// BufferedReader
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
bw.write("Enter number: ");
bw.flush();
int in2 = Integer.parseInt(br.readLine());
br.close();
bw.write("Your number : " + String.valueOf(in2));
bw.flush();
bw.close();
}
}
/* Error
Exception in thread "main" java.io.IOException: Stream closed
at java.base/java.io.BufferedInputStream.getBufIfOpen(BufferedInputStream.java:176)
at java.base/java.io.BufferedInputStream.read(BufferedInputStream.java:342)
at java.base/sun.nio.cs.StreamDecoder.readBytes(StreamDecoder.java:284)
at java.base/sun.nio.cs.StreamDecoder.implRead(StreamDecoder.java:326)
at java.base/sun.nio.cs.StreamDecoder.read(StreamDecoder.java:178)
at java.base/java.io.InputStreamReader.read(InputStreamReader.java:181)
at java.base/java.io.BufferedReader.fill(BufferedReader.java:161)
at java.base/java.io.BufferedReader.readLine(BufferedReader.java:326)
at java.base/java.io.BufferedReader.readLine(BufferedReader.java:392)
at test.Test2.main(Test2.java:27)
*/
答:
0赞
Priya Tripathi
8/5/2021
#1
Scanner sc = new Scanner(System.in); //" 1st time "
System.out.print("Enter number : ");
int in1 = sc.nextInt();
sc.close(); // <-- If I erase this part, there will be no error.
System.out.println("Your number : " + in1);
// BufferedReader
BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); //"2nd time"
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
bw.write("Enter number: ");
bw.flush();
int in2 = Integer.parseInt(br.readLine());
br.close();
bw.write("Your number : " + String.valueOf(in2));
bw.flush();
bw.close();
sc.close(); // **"close your scanner over here"**
当您关闭扫描仪时,您正在使用 (System.in) 提供的键盘从用户那里获取两次时间输入,这意味着您正在关闭整个 System.in。如果您仍想关闭扫描仪,请在程序末尾写下。 祝你好运;)
评论
System.in