Including spaces in Scanner in java - java

I am writing a simple code that takes number,name,surname from the user with scanner.
But when user enters name with spaces in it(two or more names) the code thinks string after the first space is surname.
I tried using input.nextLine(); in that case it skipped name completely and took only surname from the user.
Scanner input = new Scanner(System.in);
System.out.println("Enter number");
int num = input.nextInt();
System.out.println("Enter Name");
String name = input.next();
System.out.println("Enter Surname");
String surname = input.next();

Try this:
Scanner input = new Scanner(System.in);
System.out.println("Enter number");
int num=input.nextInt();
input.nextLine(); // add this
System.out.println("Enter Name");
String name=input.nextLine();
System.out.println("Enter Surname");
String surname=input.nextLine();
System.out.println(num + " - " + name + " - " + surname);
Sample input/output:
Enter number
1
Enter Name
user name
Enter Surname
sur name
1 - user name - sur name

Use sc.nextLine() instead of sc.next() to read String with spaces

Related

I have to enter a first name, last name, student id, and avg and have it displayed on a line separated by commas on a new csv file. How do I do this?

Here is my updated code. Again, the instructions are as follows: "Enter a first name, last name, student id, and avg, then have those 4 things displayed in a new csv file, with each of the 4 inputs separated by a comma in each record." This code works well, is there anything I can do better? Also, is "in.close()" necessary in this case since I am not reading a file, but rather user input?
public class Homework07 {
public static void main(String[] args) throws FileNotFoundException {
System.out.println("Welcome! This program will store student records that you enter.");
System.out.println("When you are done entering student records, simply type in 'Done' .");
Scanner in = new Scanner(System.in);
PrintWriter outFile = new PrintWriter("students.csv");
while (true) {
System.out.print("Please enter the first name: ");
String firstName = in.nextLine();
if (firstName.equals("Done")) {
break;
}
System.out.print("Please enter the last name: ");
String lastName = in.nextLine();
System.out.print("Please enter the student ID: ");
int studentId = in.nextInt();
System.out.print("Please enter the current average: ");
double currentAvg = in.nextDouble();
in.nextLine();
String newRecord = (firstName + ", " + lastName + ", " + studentId + ", " + currentAvg);
outFile.println(newRecord);
}
in.close();
outFile.close();
}
}
your code capture the enter key entered by user to I added an empty in.nextLine(); to escape it, and secondly I added outFile.flush(); to flush the stream to the file.
System.out.println("Welcome! This program will store student records that you enter.");
System.out.println("When you are done entering student records, simply type in 'Done' .");
Scanner in = new Scanner(System.in);
PrintWriter outFile = new PrintWriter("students.csv");
while (true) {
System.out.print("Please enter the first name: ");
String firstName = in.nextLine();
if (firstName.equals("Done")) {
break;
}
System.out.print("Please enter the last name: ");
String lastName = in.nextLine();
System.out.print("Please enter the student ID: ");
int studentId = in.nextInt();
System.out.print("Please enter the current average: ");
double currentAvg = in.nextDouble();
in.nextLine();
outFile.write(firstName + "," + lastName + "," + studentId + "," + currentAvg);
outFile.flush();
}
in.close();
outFile.close();
Your call to the Scanner#nextDouble() method does not consume the ENTER key hit (the newline character) therefore you need to do it yourself by placing this line: in.nextLine(); directly under this line:
double currentAvg = in.nextDouble();
Ironically, you need to apply a newline character when you write to your file for every record you want to save, like this:
String record = new StringBuilder(firstName).append(", ").append(lastName)
.append(", ").append(studentId).append(", ")
.append(currentAvg).append(System.lineSeparator())
.toString();
outFile.write(record);

Java Scanner Taking Extra Input

I'm working on a switch statement that takes inputs with Scanner, and when I run in NetBeans, one of the inputs takes an extra blank input. The extra input happens at variable dateAdmission when the user is asked to input "Enter date of admission".
case "patient":
{
System.out.println("Enter name: ");
String name = in.nextLine();
System.out.println("Enter Address: ");
String address = in.nextLine();
System.out.println("Enter date of birth: ");
String dob = in.nextLine();
System.out.println("Enter MCP number: ");
int mcp = in.nextInt();
in.nextLine();
System.out.println("Enter date of admission: ");
String dateAdmission = in.nextLine();
System.out.println();
String hospital = in.nextLine();
System.out.println("Enter name of doctor: ");
String doctor = in.nextLine();
System.out.println("Enter room number: ");
int roomNum = in.nextInt();
a[i] = new Patient(name, address, dob, mcp, dateAdmission, hospital, doctor, roomNum);
break;
}
You might have forgotten to provide System.out.println("Enter hospital");
before the
String hospital = in.nextLine();
What happened was it printed nothing and took the extra input for hospital?

Create password for user that consists of surname written backwards, followed by a star, age, then a star, then first name written backwards

public static void main(String[] args)
{
String firstName = "";
double age =0;
String surname ="";
String password ="";
Scanner scan = new Scanner (System.in);
System.out.println("Please enter your first name:");
firstName= scan.nextLine();
System.out.println("Please enter your age:");
age=scan.nextDouble();
System.out.println("Please enter your surname:");
surname= scan.nextLine();
System.out.println("Please enter your password:");
password=scan.nextLine();
}
Do i create another variable for surnameBackwards?
Something like this:
String surnameBackwards = StringUtils.reverse(surname) + "*" + age + "*" + StringUtils.reverse(firstName)

Scanner class do not take input properly

I am trying with user input to the values firstname, middlename, lastname, age for by using scanner class, but the below program only takes firstname, middlename, lastname and not the value of age.
public void inputEmployeeDetails(){
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the firstname ");
firstname= scanner.nextLine();
System.out.println("Enter the middlename ");
middlename= scanner.nextLine();
System.out.println("Enter the lastname");
lastname= scanner.nextLine();
System.out.println("Enter the age");
age= scanner.nextInt();
}
I need to take all the values one after the other through the user prompt.
Based on the entered data I am displaying the employee details. Could someone let me know what I am missing.
I would like to also like to take multiple inputs from the user. Please let me know if I am right in the below
System.out.println("Do you like to fetch more records press "Yes" or "No");
String input=scanner.nextLine();
if(input="Yes")
inputEmployeeDetails();
The age variable takes the next ENTER key that you press, so nothing is stored. Since the datatype of ENTER is different than the data type of age variable, hence your code was getting InputMismatchException. You need to check if the next value is an int then assign it to variable. Please refer below once:
import java.util.Scanner;
public class Test{
public static void main(String []args){
String firstname, middlename, lastname;
int age;
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the firstname ");
firstname= scanner.nextLine();
System.out.println("Enter the middlename ");
middlename= scanner.nextLine();
System.out.println("Enter the lastname");
lastname= scanner.nextLine();
System.out.println("Enter the age");
if(scanner.hasNextInt()) {
age= scanner.nextInt();
}else
age = 0;
System.out.println(firstname + " " + middlename + " " + lastname + " " + age);
}
}
Check this program:
String firstname,middlename,lastname,choice;
int age, flag;
Scanner scanner = new Scanner(System.in);
do{
choice=null;
System.out.println("Enter the firstname ");
firstname= scanner.nextLine();
System.out.println("Enter the middlename ");
middlename= scanner.nextLine();
System.out.println("Enter the lastname");
lastname= scanner.nextLine();
System.out.println("Enter the age");
flag=0;age=0;
while(flag==0){
try{
age= scanner.nextInt();
flag=1;
}
catch(Exception e){
scanner.nextLine();
System.out.println("Wrong entry, please enter digits only:");
}
}
System.out.println(firstname+" "+middlename+" "+lastname+" "+age);
System.out.println("Do you like to fetch more records press Yes or No");
scanner.nextLine();
choice=scanner.nextLine();
}while(choice.contains("Y")||choice.contains("y"));
System.out.println("Program terminated.");
scanner.close();
System.exit(0);

Java ask String input with multiple words

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..
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
Use:
name = scan.nextLine();
Also, if the ID number is an integer, use nextInt() (make sure to also declare idnumber as an int instead of string)
Fixed code:
System.out.println("DOCTOR");
System.out.println("Enter ID Number:");
idnumber = scan.nextInt();
scan.nextLine();
System.out.println("Enter Name");
name = scan.nextLine();
System.out.println("Enter Field of Specialization:");
field = scan.nextLine();
System.out.println("ID " + idnumber);
System.out.println("Name " + name);
System.out.println("Specializtion " + field );
Using just next() will take all input before a space. nextLine() will take all input before return is pressed.
More on Scanner here
Pro tip: In most cases you'll use scan.nextLine() rather than scan.next() so you may want to get into the habit of using it.
Since you say scan.nextLine() "doesn't work", I suggest using BufferedReader.
BufferedReader br=new BufferedReader(new InputStreamReader(System.in);
//in your code:
int idnumber = Integer.parseInt(br.readLine());
String name = br.readLine();
String field = br.readLine();
You have to import java.io.BufferedReader and java.io.InputStreamReader

Categories

Resources