Wednesday, July 25, 2018

java - nextLine method in the Scanner











Why is the empty sc.nextLine(); under the husband so necessary? it did not equal to anything, and surely the wife did not have that line... but the program won't run without it. My book comments it as Skip over trailing newLine character. but I don't see how there's anything to skip!



public class FileTest {
public static void main(String[] args) {

Scanner sc = new Scanner(System.in);
System.out.print("For your blended family, \n enter the wife's name");
String wife = sc.nextLine();
System.out.print("Enter the number of her children:");

int herkids = sc.nextInt();

System.out.print("Enter the husband's name:");
//sc.nextLine(); // Why is this line so necessary?
String husband = sc.nextLine();
System.out.print("Enter the number of his children:");
int hisKids = sc.nextInt();

System.out.println(wife + " and " + husband + " have " + (herkids + hisKids) + " children.");


}
}

Answer



Check this question,



Scanner issue when using nextLine after nextXXX



Look at the accepted answer,




"The problem is with the input.nextInt() command it only reads the int value. So when you continue reading with input.nextLine() you receive the "\n" Enter key. So to skip this you have to add the input.nextLine(). Hope this should be clear now."


No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...