2

I have a program in which I need to read a file word by word and save this in a String variable. This works fine (I use a while loop), but the problem is that my string variable doesn't have the same value outside the loop. If I check what the variable contains inside the while loop, I get over 30000 words, but when I try the same thing outside the while-loop, only 1 word comes up.

String ord = null;
while (fil.hasNext()) {
    ord = leser.next();
    System.out.println(ord); //If I print it here I get the whole file
}
System.out.println(ord); // If i try to print out the content here, I only get 1 word

I don't understand why the variable "ord" doesn't contain the same inside and outside the loop, and how can I fix this? I of course need this variable in other places in my program, but since there is only 1 word stored, the rest of my program doesn't work as intended.

2
  • try to concate instead of overwriting it Commented Oct 4, 2013 at 9:32
  • You are just getting the last word read outside the loop. Inside loop, words are printed on different iteration. You should add them to a list, or create a StringBuilder by concatenating them. Commented Oct 4, 2013 at 9:32

8 Answers 8

4

The value of ord is constantly changing. Because you choose to print it each time during the loop, you believe it contains the entire file.

You could instead use a StringBuilder and append strings to that.

StringBuilder builder = new StringBuilder();
while (fil.hasNext()) {
    String tmp = leser.next();
    System.out.println(tmp); // If still needed
    builder.append(tmp);
}

String completeString = builder.toString();
Sign up to request clarification or add additional context in comments.

Comments

1

ord is re-initializing inside while loop.So in final iteration of while loop, ord contains the last word present in leser.next().

do one thing

String ord = null;

StringBuffer str = new StringBuffer();

while (fil.hasNext()) {

    ord = leser.next();
    System.out.println(ord);
    str.append(ord); //To retain the value of ord for future use.

}

System.out.println(str.toString); 

Comments

1

You variable keep reassigning and you are getting the last one.

Starting from here,

String ord = null;

// Started executing 
    while (fil.hasNext()) {
        ord = leser.next();
        System.out.println(ord); 
    }
//Ended executing

Now in the   ord  last assigned value is there 

System.out.println(ord); 

Where as inside

 // Started executing 
        while (fil.hasNext()) {
            ord = leser.next();      //new  value  assigned
            System.out.println(ord); // new value printed
        }
    //Ended executing

What you can do is store the previous value also.

   StringBuilder builder = new StringBuilder ();     
    // Started executing 
        while (fil.hasNext()) {

            builder.append(leser.next()); //append to previous val
            builder.append(System.getProperty("line.separator"));
        }
    //Ended executing
    System.out.println(builder.toString()); 

3 Comments

Thanks, this worked well :) Only one question, now all the words are written out all in one chunk, whereas before they were written out one on each line. Is there any way to do this with StringBuilder?
@user2795095 yes. you can append a new line after each append. I'l update my post. Please look at my update
Great, now I got it word for word. Thank you :)
0

variable ord contains only one value both inside and outside the loop. Inside the loop its value keep getting reassigned and printed. But outside the loop it will have the last value set in loop.

Comments

0

You can use StringBuffer instead like

StringBuffer ord = new StringBuffer;
while (fil.hasNext()) {
   ord.append(leser.next());
}
System.out.println(ord.toString());

1 Comment

StringBuilder is usually preferred, unless one has a need for thread safety (and the overheads that causes).
0

You reassign the variable ord every iteration.

It's clearest seen without the while loop, what you are doing is:

String ord = "test";
ord = "another string";

So the value of ord is simply changed. You need to store the values in a List:

List<String> ord = new LinkedList<>();
while (fil.hasNext()) {
    ord.add(leser.next());
}
System.out.println(ord);

Comments

0

why the variabel "ord" don't contain the same inside and outside the loop?

Because, String is immutable. Every step of while loop it generate new reference and previous reference of ord is lost.

and how can I fix this?

If you use StringBuilder instead of String and append the content inside while loop than you will see the whole file output outside of while loop.

Comments

0

As you can see, your are reading the file word by word, and each time your are set the ord variable to the current word:

String ord = null;
while (fil.hasNext()) {
     /*if the next word exist - lets set ord to the next word, means 
     each time the ord variable changes to the next word. */
    ord = leser.next();
    System.out.println(ord);
}
System.out.println(ord); //will print the last word in the file

If you want to save the whole file inside the ord variable, you could do something like this:

String ord = null;
while (fil.hasNext()) {
     /*if the next word exist - lets set ord to the ord variable 
     content + the next word, means we are just adding the next word*/
    ord = ord + leser.next();
    System.out.println(ord); //print current word
}
System.out.println(ord); //will print the whole file

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.