输入不应超过 xxx KB



我用 Java 解决一些问题,我在问题中遇到了这一行......"输入的总大小不超过 300 KB" , "输入的总大小不超过 256 KB"

我的

疑问是如何确保我的输入小于该值。

我实际上尝试使用

CountingInputStream (CountingInputStream input = new CountingInputStream(System.in);) 

这是谷歌的外部jar文件。

但是当我在在线编译器中提交解决方案时,编译器不会采用CountingInputStream。 那么如何在不以一般方式使用此?..的情况下做到这一点呢?

CountingInputStream input = new CountingInputStream(System.in);     
System.out.println("Enter Values: ");
while (scanner.hasNext() && input.getCount() < (256 * 1024))

现在我正在做...但是有没有办法我可以在不使用CountingInputStream的情况下控制我的输入.请帮忙

编写自己的类来装饰InputStream,重写 read 方法来计算字节数,然后在字节数超过某个阈值时抛出异常。您的驱动程序可能如下所示:

InputStream in = new ByteLimiterInputStream(new FileInputStream("file.bin"));
while(...)
   in.read();

当您读取的数据过多时,这将引发异常。由您来编写ByteLimiterInputStream类。这毕竟是一项学术练习:锻炼自己的大脑,不要向别人询问答案。

使用InputStream,调用read()方法,并递增计数器。

read()将返回单个字节,或在流末尾返回 -1。

例如

int MAX = 256 * 1024;
int count = 0;
while (true) {
  int return = is.read();
  if (return == -1) break;
  if (++count >= MAX) {
    // maximum limit reached
  } else {
    // store the byte somewhere, do something with it...
  }
}