import java.util.Scanner;
public class MadLibs {
public static void main(String[] args) {
String name, place, college, profession, animal, petName;
int number;
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter a name: ");
name = keyboard.nextLine();
System.out.print("Enter a number: ");
number = keyboard.nextInt();
System.out.print("Enter a place: ");
place = keyboard.nextLine();
System.out.print("Enter a college: ");
college = keyboard.nextLine();
System.out.print("Enter a profession: ");
profession = keyboard.nextLine();
System.out.print("Enter a animal: ");
animal = keyboard.nextLine();
System.out.print("Enter a pet name: ");
petName = keyboard.nextLine();
keyboard.close();
}
}
Can't figure out why "enter a college" and "enter a place" are printing on the same line and not acting as separate inputs.
CodePudding user response:
Try below snippet it will definitely work :
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter a name: ");
String name = keyboard.nextLine();
System.out.print("Enter a number: ");
int number = keyboard.nextInt();
System.out.print("Enter a place: ");
keyboard.next();
String place = keyboard.nextLine();
System.out.print("Enter a college: ");
keyboard.next();
String college = keyboard.nextLine();
System.out.print("Enter a profession: ");
String profession = keyboard.nextLine();
System.out.print("Enter a animal: ");
String animal = keyboard.nextLine();
System.out.print("Enter a pet name: ");
String petName = keyboard.nextLine();
}
CodePudding user response:
The nextLine() method of java.util.Scanner class advances this scanner past the current line and returns the input that was skipped. This function prints the rest of the current line, leaving out the line separator at the end.
enter code here
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
String name, place, college, profession, animal, petName;
int number;
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter a name: ");
name = keyboard.nextLine();
System.out.print("Enter a number: ");
number = keyboard.nextInt();
System.out.print("Enter a place: ");
place = keyboard.nextLine();
keyboard.nextLine(); //brings to next line
System.out.print("Enter a college: ");
college = keyboard.nextLine();
System.out.print("Enter a profession: ");
profession = keyboard.nextLine();
System.out.print("Enter a animal: ");
animal = keyboard.nextLine();
System.out.print("Enter a pet name: ");
petName = keyboard.nextLine();
keyboard.close();
}
}