2014-04-02 183 views
1

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



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. 

帮助将非常感激。

+4

提示:'的System.out.println (结果);'在循环内部。 – Maroun

回答

4

整个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); 
... 
+0

谢谢你的回答,我曾尝试过,但如果我这样做,我面临另一个问题,“找不到符号,符号变量结果,位置类meu”。 – Doe

+0

将'StringBuffer'放到循环之外。 – Astrobleme

+0

我已经尝试过了......结果几乎是一样的,只是如果我把它放在循环外部,它全部在一行中。 Stackoverflow是我的最后手段,我已经把相当多的想法,已经xD – Doe

3

你需要把print语句像外循环:

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);