为什么scanner类比bufferedreader要花很长时间

slhcrj9b  于 2021-07-12  发布在  Java
关注(0)|答案(1)|浏览(482)

**结束。**此问题需要详细的调试信息。它目前不接受答案。
**想改进这个问题吗?**更新问题,使其成为堆栈溢出的主题。

一小时前关门了。
改进这个问题
我试图用scanner类在codechef上解决这个问题
https://www.codechef.com/problems/weightbl
但我得到运行时错误
使用扫描仪的代码图像:

  1. class Codechef
  2. {
  3. public static void main (String[] args) throws java.lang.Exception
  4. {
  5. try{
  6. Scanner scan=new Scanner(System.in);
  7. int test_case=scan.nextInt();
  8. while(test_case>0)
  9. {
  10. int w1=scan.nextInt();
  11. int w2=scan.nextInt();
  12. int x1=scan.nextInt();
  13. int x2=scan.nextInt();
  14. int M=scan.nextInt();
  15. int diff=w2-w1;
  16. if(diff>=x1*M&&diff<=x2*M)
  17. System.out.println("1");
  18. else
  19. System.out.println("0");
  20. test_case--;
  21. }
  22. }catch(Exception e){return;}
  23. }
  24. }

但是当我使用bufferedreader时,它显示了使用bufferedreader类的正确答案

  1. import java.util.*;
  2. import java.lang.*;
  3. import java.io.*;
  4. /* Name of the class has to be "Main" only if the class is public. */
  5. class Codechef
  6. {
  7. public static void main (String[] args) throws java.lang.Exception
  8. {
  9. BufferedReader buf=new BufferedReader(new InputStreamReader(System.in));
  10. int t=Integer.parseInt(buf.readLine());
  11. for(int i=0;i<t;i++){
  12. String a =buf.readLine();
  13. String word[]=a.split(" ");
  14. int w1=Integer.parseInt(word[0]);
  15. int w2=Integer.parseInt(word[1]);
  16. int x1=Integer.parseInt(word[2]);
  17. int x2=Integer.parseInt(word[3]);
  18. int m=Integer.parseInt(word[4]);
  19. if(w2<=(w1+x2*m) && w2>=(w1+x1*m)){
  20. System.out.println(1);
  21. }
  22. else{
  23. System.out.println(0);
  24. }
  25. }
  26. }
  27. }

请帮助我为什么它给我扫描扫描类运行时需要1.01秒bufferedreader需要0.72秒在c++它需要0.19秒

  1. # include <iostream>
  2. # include <bits/stdc++.h>
  3. using namespace std;
  4. int main() {
  5. int t;
  6. cin>>t;
  7. while(t--){
  8. int w1,w2,x1,x2,M;
  9. cin>>w1>>w2>>x1>>x2>>M;
  10. int x = w2-w1;
  11. int min= x1*M;
  12. int max = x2*M;
  13. if(x>=min && x<=max){
  14. cout<<"1\n";
  15. }
  16. else{
  17. cout<<"0\n";
  18. }
  19. }
  20. }

我需要用c++或java来编写代码吗

pbgvytdp

pbgvytdp1#

您的扫描仪正在从输入流中读取较小的信息位,一次读取一个,并且没有缓冲,而且这个过程很慢,因为这个过程中最慢的步骤,即从输入流读取,必须执行多次。
使用缓冲输入的全部目的是通过减少从文件和缓冲区中读取大块数据的次数,然后根据需要从代码的缓冲区中提取数据,从而实现更高效的读取。这样,从输入流读取的瓶颈就大大减少了。
你试过:

  1. Scanner scan = new Scanner(new BufferedInputStream(System.in));

如果是,结果如何?

相关问题