How do I read user inputs, one line at a time to create an object. Which then goes into a ArrayList? As you can see, when I enter the name, it's breaks it up and only stores the last name. Or if I do: first-middle-last name, it stores the middle and last name.
I enter the name the first time, which calls the search method first, to see if the name already exists in the ArrayList. That works fine. And if the name isn't in the list, the search returns null. Which then prompts the inputs and add method.
case 1: {
System.out.print("Enter the Students name: ");
String nameSearch = kbd.next();
Student stu = dc.search(nameSearch );
if (stu != null) {
System.out.println(stu);
}
else {
System.out.print("Enter name AGAIN: ");
String nameAdd= kbd.nextLine();
System.out.print("Enter grade (freshman, sophomore, junior, senior: ");
String categoryAdd = kbd.nextLine();
System.out.print("Major: ");
String majorAdd = kbd.nextLine();
System.out.print("Enter graduating year: ");
int yearAdd = kbd.nextInt();
System.out.print("Enter student ID: (xxxx.xxxx: ");
double idAdd= kbd.nextDouble();
dc.add(nameAdd, categoryAdd , majorAdd ,
yearAdd , idAdd);
}
break;
}
My input:
Enter the Students name: John Smith
Not Found(Search Method)
TEST
Enter name AGAIN: TEST2
Enter grade (freshman, sophomore, junior, senior: senior
Major: Computer Science
Enter graduating year: 2013
Enter student ID: 1234.4567
How it's stored inside the object when I print ArrayList:
Name: Smith
Grade: senior
Major: Computer Science
Graduating Year: 2013
Student ID: 1234.4567
The add method:
public Student add(String name, String grade,
String major, int year, double id) {
Student newStu = new Student(addName, addGrade, addMajor, addYear, addId);
studentList.add(newStu );
System.out.println("Added!");
return null;
}
This line:
String nameSearch = kbd.next();
Should probably be
String nameSearch = kbd.nextLine();
right?
Make kbd a BufferedReader (e.g. BufferedReader kbd = new BufferedReader(new InputStreamReader(System.in));), then do this...
case 1: {
System.out.print("Enter the Students name: ");
String nameSearch = kbd.readLine();
Student stu = dc.search(nameSearch );
if (stu != null) {
System.out.println(stu);
}
else {
System.out.print("Enter name AGAIN: ");
String nameAdd= kbd.readLine();
System.out.print("Enter grade (freshman, sophomore, junior, senior: ");
String categoryAdd = kbd.readLine();
System.out.print("Major: ");
String majorAdd = kbd.readLine();
System.out.print("Enter graduating year: ");
int yearAdd = Integer.parseInt(kbd.readLine());
System.out.print("Enter student ID: (xxxx.xxxx: ");
double idAdd= Double.parseDouble(kbd.readLine());
dc.add(nameAdd, categoryAdd , majorAdd ,
yearAdd , idAdd);
}
break;
}
It should be String nameSearch = kbd.nextLine();. I read on the multiline java tutorial.
Hope this helps. In some way.
Related
Im still learning java and i want to understand more about array. Im still in school and we were asked to create an asean phonebook which can store, edit, delete, and view/search the information that are inputted. Im still doing the storing of information block of code and im struggling how to save multiple input in an array that is limited only to 100 contacts and can be searched later in the code. Can someone help me with my task and make me understand??
import java.util.Scanner;
public class Phonebook
{
public static void main (String [] args)
{
Scanner input = new Scanner (System.in);
int i = 0;
String studentNumber, surName, firstName, occuPation, countryCode, areaCode, numBer;
char genDer;
do
{
Menu();
System.out.println(" ");
System.out.print("Go to: ");
String choice = input.next();
if (choice.equals("1") || choice.equals("2") || choice.equals("3") || choice.equals("4") || choice.equals("5"))
{
i++;
switch(choice)
{
case "1":System.out.println("Enter student number: ");
studentNumber = input.next();
System.out.println("Enter surname: ");
surName = input.next();
System.out.println("Enter first name: ");
firstName = input.next();
System.out.println("Enter occupation: ");
occuPation = input.next();
System.out.println("Enter gender (M for male, F for female): ");
genDer = input.next();
System.out.println("Enter counter code: ");
countryCode = input.next();
System.out.println("Enter area code: ");
areaCode = input.next();
System.out.println("Enter number: ");
numBer = input.next();
break;
case "2":System.out.println("2");break;
case "3":System.out.println("3");break;
case "4":System.out.println("4");break;
case "5":System.out.println("5");break;
}
}
else
{
System.out.println("Invalid keyword, Please try again");
}
}
while (i < 1);
}
static void Menu()
{
System.out.println("[1] Store to ASEAN phonebook");
System.out.println("[2] Edit entry in ASEAN phonebook");
System.out.println("[3] Delete entry from ASEAN phonebook");
System.out.println("[4] View\\search ASEAN phonebook");
System.out.println("[5] Exit");
}
}
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);
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?
I have a class where a user inputs information about an employee (first and last name, address, hire date) for a user determined number of employees.
import java.util.ArrayList;
import java.util.Scanner;
public class Employee {
public static void main(String [] args){
String employeeName = null;
String employeeAddress = null;
String hireDate = null;
Scanner userInput = new Scanner(System.in);
System.out.println("How many employees would you like to enter information for?");
int numEmployees = userInput.nextInt();
for( int i = 0; i < numEmployees; i++) {
Scanner input = new Scanner(System.in);
System.out.println("Enter employees first name: ");
String firstName = input.nextLine();
System.out.println("Enter employees last name: ");
String lastName = input.nextLine();
System.out.println("Enter street employee lives on:");
String street = input.nextLine();
System.out.println("Enter city employee lives in:");
String city = input.nextLine();
System.out.println("Enter state employee lives in:");
String state = input.nextLine();
System.out.println("Enter employee's zip code:");
String zip = input.nextLine();
System.out.println("Enter month employee was hired:");
String month = input.nextLine();
System.out.println("Enter day employee was hired:");
String day = input.nextLine();
System.out.println("Enter year employee was hired:");
String year = input.nextLine();
Name name = new Name(firstName, lastName);
Address address = new Address(street, city, state, zip);
Date date = new Date(month, day, year);
employeeName = name.getName();
employeeAddress = address.getAddress();
hireDate = date.getDate();
ArrayList<String> obj = new ArrayList<String>();
obj.add(employeeName);
obj.add(employeeAddress);
obj.add(hireDate);
System.out.println(obj);
}
}
}
I'm trying to get the program to go through the user prompts, take that info and put it in a position in an ArrayList, then repeat for however many times the user determined earlier and display all at once at the end. Something like this:
FirstName LastName, Address, Hire Date
FirstName LastName, Address, Hire Date
And so on. Right now, my code will run through the user prompts, display that, then run through the next round of prompts and display that:
Enter Name:
Name
Enter Address:
Address
Enter Hire Date:
Hire Date
[Name, Address, Hire Date]
Enter Name:
Name
Enter Address:
Address
Enter Hire Date:
Hire Date
[Name, Address, Hire Date]
I realize this is because my array and array display are within the for loop, but when I move the array outside the loop I get no display. When I move just the array display outside the loop, my code doesn't compile.
Move this line:
System.out.println(obj);
out of the for loop. And use List to contain the ArrayList. Then you display it in a separate for loop:
List<ArrayList<String>> objs = new ArrayList<ArrayList<String>>(); //use list of objs
for( int i = 0; i < numEmployees; i++ )
{
//all the inputs
ArrayList<String> obj = new ArrayList<String>();
obj.add(employeeName);
obj.add(employeeAddress);
obj.add(hireDate);
objs.add(obj);
}
for( int i = 0; i < numEmployees; i++ ) //for loop just to display
System.out.println(objs.get(i)); //display each element here
What you are printing out is a tuple of type [string, string, string]. This can be represented as a List. Then for each employee you want to store this tuple in another List of type List<List<String>>.
public static void main( String [] args )
{
String employeeName = null;
String employeeAddress = null;
String hireDate = null;
Scanner userInput = new Scanner(System.in);
System.out.println("How many employees would you like to enter information for?");
int numEmployees = userInput.nextInt();
List<List<String>> employesInfo = new ArrayList<List<String>>();
for( int i = 0; i < numEmployees; i++ )
{
Scanner input = new Scanner(System.in);
System.out.println("Enter employees first name: ");
String firstName = input.nextLine();
System.out.println("Enter employees last name: ");
String lastName = input.nextLine();
System.out.println("Enter street employee lives on:");
String street = input.nextLine();
System.out.println("Enter city employee lives in:");
String city = input.nextLine();
System.out.println("Enter state employee lives in:");
String state = input.nextLine();
System.out.println("Enter employee's zip code:");
String zip = input.nextLine();
System.out.println("Enter month employee was hired:");
String month = input.nextLine();
System.out.println("Enter day employee was hired:");
String day = input.nextLine();
System.out.println("Enter year employee was hired:");
String year = input.nextLine();
Name name = new Name(firstName, lastName);
Address address = new Address(street, city, state, zip);
Date date = new Date(month, day, year);
employeeName = name.getName();
employeeAddress = address.getAddress();
hireDate = date.getDate();
ArrayList<String> obj = new ArrayList<String>();
obj.add(employeeName);
obj.add(employeeAddress);
obj.add(hireDate);
employeesInfo.add(obj);
}
for (int i = 0; i < numEmployees; i++ ) {
System.out.println(emploeesInfo.get(i));
}
}
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