Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java ask String input with multiple words

Tags:

java

HI I am having problem with asking Direct Whole name using Java.

System.out.println("DOCTOR");
System.out.println("Enter ID Number:");
idnumber = scan.next();
System.out.println("Enter Name");
name = scan.next();
System.out.println("Enter Field of Specialization:");
field = scan.next();

System.out.println("ID               " + idnumber);
System.out.println("Name             " + name);
System.out.println("Specializtion    " + field );

and When I enter this information below:

ID = 100 Name = Brandon Sullano

it gives me this result

ID               100    
Name             Brandon    
Specializtion    Sullano

I want Name to be dynamic so I can Input even two words how to do it?
Thanks in Advance..

like image 671
Brandon Jake Sullano Avatar asked Feb 18 '26 14:02

Brandon Jake Sullano


1 Answers

Try this code:

import java.util.Scanner;

public class DoctorDoctor {

    public static void main (String [] args) {

        int idnumber;
        String name, field;

        Scanner sc = new Scanner(System.in);

        System.out.println("DOCTOR");

        /** Assuming ID number is an integer value */
        System.out.print("Enter ID Number: ");
        idnumber = sc.nextInt();
        sc.nextLine(); // This is important, for clearing the new line character

        System.out.print("Enter Name: ");
        name = sc.nextLine();

        System.out.print("Enter Field of Specialization: ");
        field = sc.nextLine();

        System.out.println();
        System.out.printf("%-15s: %d%n", "ID Number", idnumber);
        System.out.printf("%-15s: %s%n", "Name", name);
        System.out.printf("%-15s: %s%n", "Specialization", field);

        sc.close();
    }
}

Example input/output:

DOCTOR
Enter ID Number: 100
Enter Name: Brandon
Enter Field of Specialization: Heart Surgeon

ID Number      : 100
Name           : Brandon
Specialization : Heart Surgeon
like image 59
Watermel0n Avatar answered Feb 20 '26 08:02

Watermel0n



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!