所以我是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.
非常感谢帮助。
答案 0 :(得分: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);
...
答案 1 :(得分: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);