I have a java program where I am collecting entries from a user. The user is prompted to enter a name, phone number, and email address.
When I type the full name (ie: Mike Smith) the program only retains the first name. When it sends the email address and phone number to the text doc they are swapped so the email address is in the phone number section and the phone number is in the email address section.
Here is the section of my main getting the information from the user
String name = Validator.getEntry(ip, "Enter name: ");
String email = Validator.getEntry(ip, "Enter email address");
String phone = Validator.getEntry(ip, "Enter phone number: ");
AddressBookEntry newEntry = new AddressBookEntry(name, email, phone);
AddressBookIO.saveEntry(newEntry);
Here is the section of my validator class validating the entry
public static String getEntry(Scanner ip, String prompt)
{
System.out.println(prompt);
String e = ip.next();
ip.nextLine();
return e;
}
I did try to troubleshoot this by eliminating the validator and just typing
system.out.println("Enter name:");
name = ip.next();
and so on for the email and phone but I got the same results as running it through the validator class. I'm confused on what to check next. Is there anything wrong with what I have done?
Here is my AddressBookEntry clas
public class AddressBookEntry
{
private String name;
private String emailAddress;
private String phoneNumber;
public AddressBookEntry()
{
name = "";
emailAddress = "";
phoneNumber = "";
}
public void setName(String name)
{
this.name = name;
}
public String getName()
{
return name;
}
public void setEmailAddress(String emailAddress)
{
this.emailAddress = emailAddress;
}
public String getEmailAddress()
{
return emailAddress;
}
public void setPhoneNumber(String phoneNumber)
{
this.phoneNumber = phoneNumber;
}
public String getPhoneNumber()
{
return phoneNumber;
}
public AddressBookEntry(String newname, String newphone, String newemail)
{
name = newname;
emailAddress = newemail;
phoneNumber = newphone;
}
}
Here is my IO class
import java.io.*;
public class AddressBookIO
{
private static File addressBookFile = new File("address_book.txt");
private static final String FIELD_SEP = "\t";
private static final int COL_WIDTH = 20;
// use this method to return a string that displays
// all entries in the address_book.txt file
public static String getEntriesString()
{
BufferedReader in = null;
try
{
checkFile();
in = new BufferedReader(
new FileReader(addressBookFile));
// define the string and set a header
String entriesString = "";
entriesString = padWithSpaces("Name", COL_WIDTH)
+ padWithSpaces("Email", COL_WIDTH)
+ padWithSpaces("Phone", COL_WIDTH)
+ "\n";
entriesString += padWithSpaces("------------------", COL_WIDTH)
+ padWithSpaces("------------------", COL_WIDTH)
+ padWithSpaces("------------------", COL_WIDTH)
+ "\n";
// append each line in the file to the entriesString
String line = in.readLine();
while(line != null)
{
String[] columns = line.split(FIELD_SEP);
String name = columns[0];
String emailAddress = columns[1];
String phoneNumber = columns[2];
entriesString +=
padWithSpaces(name, COL_WIDTH) +
padWithSpaces(emailAddress, COL_WIDTH) +
padWithSpaces(phoneNumber, COL_WIDTH) +
"\n";
line = in.readLine();
}
return entriesString;
}
catch(IOException ioe)
{
ioe.printStackTrace();
return null;
}
finally
{
close(in);
}
}
// use this method to append an address book entry
// to the end of the address_book.txt file
public static boolean saveEntry(AddressBookEntry entry)
{
PrintWriter out = null;
try
{
checkFile();
// open output stream for appending
out = new PrintWriter(
new BufferedWriter(
new FileWriter(addressBookFile, true)));
// write all entry to the end of the file
out.print(entry.getName() + FIELD_SEP);
out.print(entry.getEmailAddress() + FIELD_SEP);
out.print(entry.getPhoneNumber() + FIELD_SEP);
out.println();
}
catch(IOException ioe)
{
ioe.printStackTrace();
return false;
}
finally
{
close(out);
}
return true;
}
// a private method that creates a blank file if the file doesn't already exist
private static void checkFile() throws IOException
{
// if the file doesn't exist, create it
if (!addressBookFile.exists())
addressBookFile.createNewFile();
}
// a private method that closes the I/O stream
private static void close(Closeable stream)
{
try
{
if (stream != null)
stream.close();
}
catch(IOException ioe)
{
ioe.printStackTrace();
}
}
// a private method that is used to set the width of a column
private static String padWithSpaces(String s, int length)
{
if (s.length() < length)
{
StringBuilder sb = new StringBuilder(s);
while(sb.length() < length)
{
sb.append(" ");
}
return sb.toString();
}
else
{
return s.substring(0, length);
}
}
}
Scanner.next() will read one word at a time, which is why it is only reading the first name. Use Scanner.nextLine() if you want the whole line.
System.out.println(prompt);
String e = ip.nextLine();
return e;
Related
I have a text file like down below:
jack; 488;22;98
kylie; 541;72;81
jenna; 995;66;17 .
.
The list is formatted as follows:
On every line, the first number after the name is the student's code and the numbers following it are scores.
I want to pass the student's code (as a String) as the input to the program and it should return the student's second score to me.
I have tried bufferedreader ,but I can just write all text files as output, but I can't search for the code and the other things.
Thanks
BufferedReader br = new BufferedReader(new FileReader("filePath"));
String contentLine = br.readLine();
while (contentLine != null) {
String[] result=contentLine.split(";");
String studentCode =result[1].trim();
// apply your logic for studentCode here
contentLine = br.readLine();
}
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;
public class FilterCsv {
private class Student {
private String name;
private String code;
private String score;
private String score2;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getScore() {
return score;
}
public void setScore(String score) {
this.score = score;
}
public String getScore2() {
return score2;
}
public void setScore2(String score2) {
this.score2 = score2;
}
#Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", code='" + code + '\'' +
", score='" + score + '\'' +
", score2='" + score2 + '\'' +
'}';
}
}
private Function<String, Student> mapToItem = (line) -> {
System.out.println(line);
String[] p = line.split(";");
Student student = new Student();
student.setName(p[0]);
if (p[1] != null && p[1].trim().length() > 0) {
student.setCode(p[1]);
}
if (p[2] != null && p[2].trim().length() > 0) {
student.setScore(p[2]);
}
if (p[3] != null && p[3].trim().length() > 0) {
student.setScore2(p[3]);
}
return student;
};
private List<Student> processInputFile(String inputFilePath, String name) {
List<Student> inputList = new ArrayList<>();
try {
File inputF = new File(inputFilePath);
InputStream inputFS = new FileInputStream(inputF);
BufferedReader br = new BufferedReader(new InputStreamReader(inputFS));
// skip the header of the csv
inputList = br.lines().map(mapToItem).collect(Collectors.toList());
br.close();
String secondScore = inputList
.stream()
.peek(System.out::println)
.filter((s -> s.getName().equals(name)))
.findFirst()
.get().getScore2();
System.out.println("Score 2 for " + name + " is: " + secondScore);
} catch (IOException e) {
System.out.println(e);
}
return inputList;
}
public static void main(String[] args) {
new FilterCsv().processInputFile("your filepath, "studentsName");
}
}
add some error checking and stuff...
Cheers
I am trying to learn Java and am really struggling on part of a problem that I have. I am being asked to write a method to read a text file where each line representing an instance of an object e.g. SalesPerson
The question is asking me to add an identifier id for every line that read in, the id is not present in the text file. I have id declared in my Sales Person class with a constructor and getter and setter methods, and have my method to read the text file below in another class. However it doesn't work and I am not sure where I am going wrong. Could someone give me a pointer..? I would be very grateful.,
public static Collection<SalesPerson> readSalesData() {
String pathname = CXU.FileChooser.getFilename();
File aFile = new File(pathname);
Scanner bufferedScanner = null;
Set<SalesPerson> salesSet = new HashSet<>();
try {
int id;
String name;
String productCode;
int sales;
int years;
Scanner lineScanner;
String currentLine;
bufferedScanner = new Scanner(new BufferedReader(new FileReader(aFile)));
while(bufferedScanner.hasNextLine()) {
currentLine = bufferedScanner.nextLine();
lineScanner = new Scanner(currentLine);
lineScanner.useDelimiter(",");
id = salesPerson.getId();
name = lineScanner.next(); //return the next token as a string
years = lineScanner.nextInt();
productCode = lineScanner.next(); // return the next token as a string
sales = lineScanner.nextInt(); // return the next token as a double
salesSet.add(new SalesPerson(id, name, years, productCode, sales));
}
}
catch (Exception anException) {
System.out.println("Error: " + anException);
}
finally {
try {
bufferedScanner.close();
}
catch (Exception anException) {
System.out.println("Error: " + anException);
}
}
return salesSet;
}
\\Constructor from Class SalesPerson
public SalesPerson(int aId, String aname, int aYears, String aProductCode, int aSales) {
super(); // optional
this.id = ++nextId;
this.name = aname;
this.years = aYears;
this.productCode = aProductCode;
this.sales = aSales;
}
Please check the following code I tried to make things little more simple:
package com.project;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
public class Temp {
public static void main(String[] args) {
Set<SalesPerson> salesPersons = (Set<SalesPerson>) readSalesData();
System.out.println(salesPersons.toString());
}
public static Collection<SalesPerson> readSalesData() {
Set<SalesPerson> salesPersons = new HashSet<>();
try {
File file = new File("D:/file.txt");
FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(fileReader);
String line;
while ((line = bufferedReader.readLine()) != null) {
if (line.isEmpty())
break;
String[] rowData = line.split(";");
salesPersons.add(new SalesPerson(rowData[0].trim(), Integer.parseInt(rowData[1].trim()), rowData[2].trim(), Integer.parseInt(rowData[3].trim())));
}
fileReader.close();
} catch (Exception ex) {
System.out.println(ex);
}
return salesPersons;
}
}
package com.project;
public class SalesPerson {
// Static to keep reserve value with each new instance
private static int AUTO_ID = 1;
private int id;
private String name;
private int years;
private String productCode;
private int sales;
public SalesPerson() {
}
public SalesPerson(String name, int years, String productCode, int sales) {
this.id = AUTO_ID;
this.name = name;
this.years = years;
this.productCode = productCode;
this.sales = sales;
AUTO_ID++;
}
// Getters & Setters...
#Override
public String toString() {
return "ID: " + id + ", Name: " + name + ", Years: " + years + ", Product Code: " + productCode + ", Sales: " + sales + System.lineSeparator();
}
}
And this my data file:
FullName1 ; 20; p-code-001; 10
FullName2 ; 30; p-code-002; 14
FullName3 ; 18; p-code-012; 1040
I have created class Patient (pojo), where I have declared variables.
I have added getter and setter methods, as well as a constructor:
public class Patient {
private String patientName;
private String phoneNumber;
private int age;
//generate getter and setter method
public String getPatientName() {
return patientName;
}
public void setPatientName(String patientName) {
this.patientName = patientName;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
//generate constructor
public Patient(String patientName, String phoneNumber, int age) {
this.patientName = patientName;
this.phoneNumber = phoneNumber;
this.age = age;
}
}
I have created an interface PatientDetails and implemented the methods in the Hospital class.
public interface PatientDetails {
public void addpatient();
public void refreshPatient()throws IOException;
}
Here is how the methods are implemented:
public class Hospital implements PatientDetails {`
Scanner scan = new Scanner(System.in);
int token = 0;
String name, mobileNumber;
static HashMap<Integer, Patient> map = new HashMap<Integer, Patient>();
File file = new File("E:\\Patient\\pt.txt");
int age;
public void addpatient() {
BufferedWriter bufferedWriter = null;
FileWriter fileWriter = null;
try {
// true = append file
// write a data in a file
fileWriter = new FileWriter(file, true);
bufferedWriter = new BufferedWriter(fileWriter);
System.out.println("Enter the name");
scan.nextLine();
name = scan.nextLine();
System.out.println("Enter Mobile number must be 10 digit");
mobileNumber = scan.nextLine();
System.out.println("Enter the age");
age = scan.nextInt();
bufferedWriter.write("TokenNumber:" + token + "," + "PatientName:" + name + ",PhoneNumber:" + mobileNumber
+ ",Age :" + age + ";");
// for nextline
bufferedWriter.newLine();
// close file
bufferedWriter.close();
fileWriter.close();
System.out.println("yours Appoint cofirmed....\nPatient Name: " + name + "\nMobile number: " + mobileNumber
+ "\nToken number is: " + token + "\nAge is:" + age);
token++;
} catch (IOException e) {
// TODO Auto-generated catch block
System.out.println("Something went wrong");
e.printStackTrace();
}
}
#Override
public void refreshPatient() throws IOException {
Patient patient=new Patient(mobileNumber, mobileNumber, age);
String filePath = file.getPath();
System.out.println("refreshed successfully");
String line;
BufferedReader reader = new BufferedReader(new FileReader(filePath));
map=new HashMap<>();
while ((line = reader.readLine()) != null) {
String[] parts = line.split(":", 2);
if (parts.length >= 2) {
String key = parts[0];
String value = parts[1];
//map.put(Integer.parseInt(key), value);
} else {
System.out.println("ignoring line: " + line);
}
}
System.out.println(map);
reader.close();
}`)
I have added the patient name, age, and mobile number into the patient.txt file.
When I call the refresh method all the values should come to the map, but I am not getting the Patient class values into the map.
How to fix that?
you should split with , before :.
After the user is registered, they can login which is supposed to read their details from a text file by using a BufferedReader. However, I am unsure of how to use a BufferedReader to read the arraylist of User objects line by line to check the details are in the text file and allow for the user to login.
This is what I have written:
public class LoginJFrame extends javax.swing.JFrame {
ArrayList<User> users = new ArrayList<>();
public LoginJFrame() {
initComponents();
}
private void btnLoginActionPerformed(java.awt.event.ActionEvent evt) {
String nickname = edtNickname.getText();
String loginID = edtLoginID.getText();
String password = String.valueOf(edtPassword.getPassword());
try {
BufferedReader br = new BufferedReader(new FileReader("userinfo.txt"));
String readFile = br.readLine();
while (readFile != null) {
String[] splitString = readFile.split(",");
nickname = splitString[0];
loginID = splitString[1];
password = splitString[2];
User user = new User(nickname, loginID, password);
users.add(user);
readFile = br.readLine();
this.dispose();
ThreadJFrame threadPage = new ThreadJFrame();
threadPage.setVisible(true);
}
} catch (Exception e) {
e.printStackTrace();
}
}
The only reason why I have another arrayList that is a string is because I cannot figure out a way for the BufferedReader to read my User arrayList line by line. Is there a way for the BufferedReader to read the arraylist class type instead of a string ArrayList?
The User object is a separate class that stores the nickname, login ID and password by using a string.
public class User {
String nickname;
String loginID;
String password;
public User(String nickname, String loginID, String password) {
this.nickname = nickname;
this.loginID = loginID;
this.password = password;
}
public String getNickname() {
return nickname;
}
public String getLoginID() {
return loginID;
}
public String getPassword() {
return password;
}
public void setNickname(String nickname) {
this.nickname = nickname;
}
public void setLoginID(String loginID) {
this.loginID = loginID;
}
public void setPassword(String password) {
this.password = password;
}
#Override
public String toString() {
return "User{" + "nickname= " + nickname + ", loginID= " + loginID + ", password= " + password + '}';
}
currentLine = br.readLine();
while (currentLine != null) {
userstring.add(currentLine);
}
Well, that code only reads a single line since you only ever invoke the readline() method once.
The code should be something like:
currentLine = br.readLine();
while (currentLine != null) {
userstring.add(currentLine);
currentLine = br.readLine();
}
And since your data for the User is contained in a single line (since you just save the toString() of your User class) you will need to parse the data into its individual tokens probably by using the String.split(...) method.
Of course your readToFile(...) method won't really do anything because you define the ArrayList locally and don't return any data from the method so the rest of your class can't access the data.
I wrote code and I can save same data in .csv file.
Now i want to read my data from csv file for example by UID.
I tried but can not get all my data by name.
Here is source
Pojo class code
public class Product {
private String UID;
private String name;
private String personalNumber;
#Override
public String toString() {
return "Product{" +
"UID='" + UID + '\'' +
", name='" + name + '\'' +
", personalNumber='" + personalNumber + '\'' +
", gender='" + gender + '\'' +
", issueState='" + issueState + '\'' +
", documentType='" + documentType + '\'' +
'}';
}
private String gender;
private String issueState;
private String documentType;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getUID() {
return UID;
}
public void setUID(String UID) {
this.UID = UID;
}
public String getPersonalNumber() {
return personalNumber;
}
public void setPersonalNumber(String personalNumber) {
this.personalNumber = personalNumber;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getIssueState() {
return issueState;
}
public void setIssueState(String issueState) {
this.issueState = issueState;
}
public String getDocumentType() {
return documentType;
}
public void setDocumentType(String documentType) {
this.documentType = documentType;
}
}
And here is a main java class
public class ReadFromFile {
public static void main(String[] args) throws Exception {
File file = new File("C:\\\\cardReaderID\\2017-08-31.csv");
Scanner input = new Scanner(file);
Product[] products = new Product[0];
while(input.hasNext()) {
String UID = input.next();
String name = input.next();
String personalNumber = input.next();
Product newProduct = new Product();
newProduct.setUID(UID);
newProduct.setName(name);
newProduct.setPersonalNumber(personalNumber);
}
for (Product product : products) {
System.err.println(product);
}
}
How I can read all my data from csv file by name? I mean, UID,fullname and etc.
How i can solve my problem?
Thanks everyone
Here is a solution
public class CSVReader {
public static void main(String[] args) {
String csvFile= "C:\\\\cardReaderID\\2017-08-31.csv";
BufferedReader br = null;
String line = "";
String cvsSplitBy = ",";
try {
br = new BufferedReader(new FileReader(csvFile));
while ((line = br.readLine()) != null) {
// use comma as separator
String[] country = line.split(cvsSplitBy);
System.out.println("Country [code= " + country[4] + " , name=" + country[5] + "]");
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}