Input using Scanner Class - java

I am a new java programmer, In my below code when am trying to enter the employee name like john smith, only john is getting printed in output.
And if I put
System.out.print("Enter Employee Name: ");
String employeeName = s.next();
above
System.out.print("Enter SEX: ");
char SEX = s.next().charAt(0);
this piece of code in output is not asking for my employeename value. and directly printing the remaining values.
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
**package cs480;
import java.util.Scanner;
public class CS480D1_Richa_2_Week2 {
public static void main(String [] args){
Scanner s=new Scanner(System.in);
System.out.print("Ente Employee ID: ");
int employeeId = s.nextInt();
System.out.print("Ente SEX: ");
char SEX = s.next().charAt(0);
System.out.print("Ente Employee Name: ");
String employeeName = s.next();
System.out.println("Employee ID is " +employeeId);
System.out.println("Employee Name is " +employeeName);
System.out.println("Employee gender is " +SEX);
}
}**

Please try with this:
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.print("Ente Employee ID: ");
int employeeId = s.nextInt();
System.out.print("Ente SEX: ");
char SEX = s.next().charAt(0);
System.out.print("Ente Employee Name: ");
String employeeName = s.nextLine();
employeeName = s.nextLine();// Try to add this line of code
System.out.println("Employee ID is " + employeeId);
System.out.println("Employee Name is " + employeeName);
System.out.println("Employee gender is " + SEX);
}

Try replacing your code
String employeeName = scanner.nextLine();
instead
String employeeName = scanner.next();
next() can read the input only till the space. It can't read two words separated by space. Also, next() places the cursor in the same line after reading the input.
nextLine() reads input including space between the words (that is, it reads till the end of line \n). Once the input is read, nextLine() positions the cursor in the next line.

Either you can use
scanner.nextLine()
or override delimiter to use next()
scanner.useDelimiter("\n");
scanner.next();

Scanner.next() uses a white-space delimiter(takes the element before white-space).
So either use
Scanner.nextLine()
or reset the delimiter using
Scanner s = new Scanner(input).useDelimiter("\\s*"your delimiter"\\s*");

Related

Including spaces in Scanner in 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

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);

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

need some guidance in reference to spaces in strings generated from scanner in java

My string description crashes the Console because of the spaces generated in normal sentence structure. i am looking for some guidance in reference to why this happens and futhermore if i am going about this the wrong way how should i be approaching it.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
System.out.println("-/- Job ticket -/-");
Scanner MyScanner = new Scanner (System.in);
String FirstName;
String LastName;
String Phone;
String Address;
String Description;
int ticketNumber;
int orderMonth ;
int orderDay;
int orderYear;
int requestedDay;
int requestedMonth;
int requestedYear;
System.out.println("First Name = ?");
FirstName = MyScanner.next();
System.out.println("Last Name = ?");
LastName = MyScanner.next();
System.out.println("Phone = ?");
Phone = MyScanner.next();
System.out.println("Address = ?");
Address = MyScanner.next();
System.out.println("Description = ?");
Description = MyScanner.next();
System.out.println("Ticket = ?");
ticketNumber = MyScanner.nextInt();
System.out.println("Order Date Month = ?");
orderMonth = MyScanner.nextInt();
System.out.println("Order Date Day");
orderDay = MyScanner.nextInt();
System.out.println("Order Date Year");
orderYear = MyScanner.nextInt();
System.out.println("Requested Date Month");
requestedMonth = MyScanner.nextInt();
System.out.println("Requested Date Day");
requestedDay = MyScanner.nextInt();
System.out.println("Requested Date Year");
requestedYear = MyScanner.nextInt();
System.out.println("=====================================================");
System.out.print("Ticket : ");
System.out.println(ticketNumber);
System.out.print("Customer: ");
System.out.print(FirstName);
System.out.print(" ");
System.out.println(LastName);
System.out.print("Home Phone: ");
System.out.println(Phone);
System.out.print("Order Date: ");
System.out.print(orderMonth);
System.out.print('/');
System.out.print(orderDay);
System.out.print('/');
System.out.println(orderYear);
System.out.print("Requested Date: ");
System.out.print(requestedMonth);
System.out.print('/');
System.out.print(requestedDay);
System.out.print('/');
System.out.println(requestedYear);
System.out.println("-----------------------------------------------------");
System.out.println("Address");
System.out.println(Address);
System.out.println("-----------------------------------------------------");
System.out.println("Description");
System.out.println(Description);
System.out.println("=====================================================");
System.out.println();
}
}
I see a problem in your code here.
When you use Scanner.next(), Scanner looks for the next whitespace " " and returns you all the text before that whitespace.
This is due to the concept of delimiters in the Scanner class and the default delimiter is a 'whitespace or next line' (You might want to read up on delimiters).
How does the delimiter work for you?
Eg: Your input is "Hello World\r\n"
When you invoke Scanner.next(), Scanner will find the whitespace, and return you everything before that, so it will return "Hello".
When you invoke Scanner.next() again, Scanner will find the \r\n (next line) and return you everything before that, so it will return "World".
Scanner will only prompt for new user input when it has finished reading all the input.
So for your code, what will happen is that:
Address = MyScanner.next();
System.out.println("Description = ?");
Description = MyScanner.next();
System.out.println("Ticket = ?");
If my input for Address is "123 ABC Avenue", Address will only get the input "123", while Description will automatically pull the value "ABC" from the input which is not empty yet.
Thus, you will observe that the program appears to "skip" the Description user prompt.
You should use the Scanner.nextLine() method if you want to pull the entire user input out from the Scanner, instead of Scanner.next()

Categories

Resources