Doe
Doe

Reputation: 71

Loop printing too many times

So I'm a big time Java noobie and I'm having hard time understanding why my program is looping so much.
So I've got this program which recieves a file. It's binary and I converted it to text.
I'm guessing I'm not very far from the solution cause the last output is baisically correct, but I don't know how to get just that one.



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

Wanted output:
There are 10 types of people in the world: Those who understand binary, and those who don't.

Actual output:

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.

Help would be much appreciated.

Upvotes: 1

Views: 1472

Answers (2)

Hungry Blue Dev
Hungry Blue Dev

Reputation: 1325

The entire StringBuffer related part outside the loop:

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

Upvotes: 4

Salah
Salah

Reputation: 8657

You need to put the print statement outside the loop like:

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

Upvotes: 3

Related Questions