1

I have two classes. And I want the code in the for loop in the class below to run twice, however when I sent int i = 0 and the condition to i < 2, it only seemed to run once. As you can see I've had to set it to i < 3 to get it to run just twice.

import java.util.Scanner;

public class LPrint {       
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);

        System.out.println("sender: ");

        String a = input.next();

        System.out.println("recepiant: ");

        String b = input.next();

        Letter one = new Letter(a, b);

        System.out.println("letter: ");

        for (int i = 0; i < 3; i++) {
            one.body = one.body.concat(input.nextLine() + "\n");
        }

        System.out.print(one.getLetter());
    }
}

In the other class, the String body = "", and it is only used in String result = ("to " + recepiant + ":\n").concat(body + "\n").concat("regards,\n").concat(sender);

1
  • 1
    You should test your hypothesis about how many times the loop runs... this is good debugging practice. Insert a System.out.println("Looping...") in the body of the loop and see how many times it prints... Commented Nov 23, 2011 at 22:35

1 Answer 1

8

I think that your problem comes from reading an unwanted string containing only a new line on the first iteration through the loop. I guess your input looks something like this (with either a space or a newline between foo and bar):

foo bar
baz
qux

After the first two reads the scanner will be positioned just after the token bar but before the new line immediately following it. The call to nextLine will read the rest of the first line (i.e. the new line character). It does not read the second line as you intended. When you read three lines you get these strings:

"\n"
"baz\n"
"qux\n"

To solve the problem you can either use readLine instead of read to read the first two tokens, or else you can add an extra call to readLine just before your loop and discard any remaining characters from the current line, including the new line character.

See this code on ideone that demonstrates the problem more clearly.

Sign up to request clarification or add additional context in comments.

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.