【问题标题】:Loop printing too many times循环打印太多次
【发布时间】:2014-04-02 09:57:20
【问题描述】:

所以我是 Java 新手,我很难理解为什么我的程序循环如此之多。
所以我有这个接收文件的程序。它是二进制的,我将其转换为文本。
我猜我离解决方案不是很远,因为最后一个输出基本上是正确的,但我不知道如何得到那个。



public class meu {
    public static void main(String[] args)
        throws Exception {

        File file = new File("sporocilo.txt");

        Scanner s = new Scanner(file);
        String lastString = "";

        while (s.hasNextLine()) {
            String line = s.nextLine();
            lastString = lastString + line;

            StringBuffer result = new StringBuffer();
            for (int i = 0; i < lastString.length(); i += 8) {
                result.append((char) Integer.parseInt(lastString.substring(i, i + 8), 2));
            }
            System.out.println(result);
        }
    }
}

想要的输出:
世界上有10种人:懂二进制的和不懂二进制的。

实际输出:

There ar 
There are 10 typ
There are 10 types of pe
There are 10 types of people in 
There are 10 types of people in the worl
There are 10 types of people in the world: Those
There are 10 types of people in the world: Those who und
There are 10 types of people in the world: Those who understand 
There are 10 types of people in the world: Those who understand binary, 
There are 10 types of people in the world: Those who understand binary, and thos
There are 10 types of people in the world: Those who understand binary, and those who do
There are 10 types of people in the world: Those who understand binary, and those who don't.

我们将不胜感激。

【问题讨论】:

  • 提示:System.out.println(result); 在循环内。

标签: java loops


【解决方案1】:

整个StringBuffer相关部分循环外

...
while (s.hasNextLine()) {
    String line = s.nextLine();
    lastString = lastString + line;
}
StringBuffer result = new StringBuffer();
for (int i = 0; i < lastString.length(); i += 8) {
    result.append((char) Integer.parseInt(lastString.substring(i, i + 8), 2));
}
System.out.println(result); 
...

【讨论】:

  • 感谢您的回答,我之前尝试过,但如果我这样做了,我将面临另一个问题,“找不到符号、符号变量结果、位置类 meu”。
  • StringBuffer 放在循环之外。
  • 我也试过了...结果几乎是一样的,只是如果我把它放在循环之外,它就在一行中。 Stackoverflow 是我最后的选择,我已经对此考虑了很多xD
  • 这行得通...非常感谢您的宝贵时间,非常感谢!
  • 这就是为什么像 SO 这样的网站存在的原因。 :-)
【解决方案2】:

您需要将打印语句放在循环之外:

while (s.hasNextLine()) {
    String line = s.nextLine();
    lastString = lastString + line;

    StringBuffer result = new StringBuffer();
    for (int i = 0; i < lastString.length(); i += 8) {
        result.append((char) Integer.parseInt(lastString.substring(i, i + 8), 2));
    }
}
System.out.println(result);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多