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

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

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

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

class Codechef
   {
public static void main (String[] args) throws java.lang.Exception
{
     try{
        Scanner scan=new Scanner(System.in);
       int test_case=scan.nextInt();
       while(test_case>0)
       {
           int w1=scan.nextInt();
           int w2=scan.nextInt();
           int x1=scan.nextInt();
           int x2=scan.nextInt();
           int M=scan.nextInt();
           int diff=w2-w1;
           if(diff>=x1*M&&diff<=x2*M)
            System.out.println("1");
           else
           System.out.println("0");
           test_case--;
       }
    }catch(Exception e){return;}
}
}

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

import java.util.*;
import java.lang.*;
 import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
class Codechef
{
public static void main (String[] args) throws java.lang.Exception
{
    BufferedReader buf=new BufferedReader(new InputStreamReader(System.in));
    int t=Integer.parseInt(buf.readLine());
    for(int i=0;i<t;i++){
        String a =buf.readLine();
        String word[]=a.split(" ");
    int w1=Integer.parseInt(word[0]);
    int w2=Integer.parseInt(word[1]);
    int x1=Integer.parseInt(word[2]);
    int x2=Integer.parseInt(word[3]);
    int m=Integer.parseInt(word[4]);

    if(w2<=(w1+x2*m) && w2>=(w1+x1*m)){
        System.out.println(1);
    }
    else{
        System.out.println(0);
    }

    }
  }
 }

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


# include <iostream>

# include <bits/stdc++.h>

using namespace std;

int main() {
int t;
 cin>>t;
 while(t--){
 int w1,w2,x1,x2,M;
  cin>>w1>>w2>>x1>>x2>>M;
 int x = w2-w1;
 int min= x1*M;
 int max = x2*M;
 if(x>=min && x<=max){
  cout<<"1\n";
 }
 else{
  cout<<"0\n";
 }
 }
 }

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

pbgvytdp

pbgvytdp1#

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

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

如果是,结果如何?

相关问题