Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Java Code not accepting the input from the user

I am a beginner in Java Programming. I am not able to figure out exactly where I am going wrong. I am trying to print out a string, which is to be taken by the user.
But my Program just prints the very first line of the code and exits without even asking for the second input.
Here is the code.

package com.company;
import java.util.Scanner;

public class string {
public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    String name = "XYZ";
    int age = sc.nextInt();
    String sem = sc.nextLine();
    System.out.format("The name of the guy is %s and his age is %d \n",name , age );
    System.out.printf("His ongoing semester is %s",sem);

}


}

Here is my program, code asks for the input of age, and without further asking for the input of other strings it exits.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

package com.company;
import java.util.Scanner;

public class string {
public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    String name = "XYZ";
    int age = sc.nextInt(); sc.nextLine();
    String sem = sc.nextLine();
    System.out.format("The name of the guy is %s and his age is %d \n",name , age );
    System.out.printf("His ongoing semester is %s",sem);

}


}

I dont exactly know but I mostly face this issue and int age = sc.nextInt(); sc.nextLine(); this kind of fix to solve this issue. You can also use sc.next() if you want to take only one word from user

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading