Dipu M. answered 01/29/24
Professional Java and Salesforce Mentor, Seasoned Software Engineer
The issue you're encountering in your Java code is a common one when using a `Scanner` object for both string and numeric input. When you read the age using `in.nextInt()`, it consumes only the number, not the end-of-line character that is entered when you press Enter. So when `in.nextLine()` is called for reading the college name, it reads the remainder of the line of input (which is just the end-of-line character from the age input) and then moves on.
To fix this, you can add an extra `in.nextLine()` call after reading the age and before reading the college name. This extra call will consume the end-of-line character. Here's the corrected code:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
String college, name;
int age;
Scanner in = new Scanner(System.in);
System.out.println("Enter your name here");
name = in.nextLine();
System.out.println("Enter your age here");
age = in.nextInt();
in.nextLine(); // This line consumes the end-of-line character
System.out.println("Enter your college here");
college = in.nextLine();
System.out.println("Hello, my name is " + name + " and I am " + age + " years old. I am enjoying my time at " + college + " very much.");
}
}
This modification will ensure that the user's input for the college name is correctly captured.