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

Why does my code terminate without executing nextLine() function while taking input for fullname?

I am trying to take input for two strings. One is for first name without any spaces and second one is for fullname that will include spaces between first-name and the last-name. As fname variable only holds one word so I used next() function there and nextLine() for full_name variable. But the code only takes input for fname and then terminates without taking input for full name. The IDE shows no error.

import java.util.Scanner;

public class main {
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter your first name: ");
        String fname = sc.next();
        System.out.println(fname);
        System.out.print("Enter your full-name: ");
        String full_name = sc.nextLine();
        System.out.println(full_name);
    }
}

>Solution :

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

A quick fix for your problem would be to change
this

String fname = sc.next();

into this

String fname = sc.nextLine().split(" ")[0];
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