【问题标题】:Input shouldnt exceed xxx KB输入不应超过 xxx KB
【发布时间】:2015-03-11 17:15:02
【问题描述】:

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

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

我实际上尝试过使用

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

验证它。这是 Google 的外部 jar 文件。

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

CountingInputStream input = new CountingInputStream(System.in);     
System.out.println("Enter Values: ");

while (scanner.hasNext() && input.getCount() < (256 * 1024))

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

【问题讨论】:

  • 这些问题来自哪里?是在线问题吗?
  • 我认为这意味着它只会接受一定数量的输入,而不是你必须验证它。你能给我们更多关于这些句子的上下文吗?
  • 这些是我的大学问题@markspace
  • 所以我的输入不能做什么?但是为什么这个 CountingInputStream 被我的朋友使用并告诉我这个
  • 我认为我们无法真正回答为什么你的朋友会告诉你一些事情。也许你应该问他们。

标签: java inputstream java.util.scanner


【解决方案1】:

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

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

while(...)
   in.read();

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

【讨论】:

    【解决方案2】:

    使用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...
      }
    
    }
    

    【讨论】:

    • 我猜这看起来不错..我认为 int MAX = 256*1024 对吗?
    猜你喜欢
    • 1970-01-01
    • 2018-11-26
    • 2017-08-30
    • 2021-03-20
    • 2013-11-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-23
    相关资源
    最近更新 更多