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);
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):
After the first two reads the scanner will be positioned just after the token
barbut before the new line immediately following it. The call tonextLinewill 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:To solve the problem you can either use
readLineinstead ofreadto read the first two tokens, or else you can add an extra call toreadLinejust 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.