Friday, August 30, 2019

java - nextLine method in the Scanner



Possible Duplicate:
Scanner issue when using nextLine after nextInt






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

}
}

No comments:

Post a Comment

hard drive - Leaving bad sectors in unformatted partition?

Laptop was acting really weird, and copy and seek times were really slow, so I decided to scan the hard drive surface. I have a couple hundr...