I don't know what I'm doing and would appreciate any help.
I'm reading a text file with the following code:
7
10 416-555-6667 Burgess Smith 15
15 905-777-8888 Thomas Patel 10
20 905-111-2222 Morris J. Stevenson 5
25 416-222-3333 Spencer Larson 30
30 416-333-4444 Adams Doe 18
35 905-122-5454 Price Hanks 15
40 905-343-5151 Clement L. Webster 8
private static void fileReader() throws FileNotFoundException
{
int eId = 0;
String nme = "";
String phne = "";
int yrs = 0;
String line ="";
Employee emp = new Employee(eId, nme, phne, yrs);
File inputfile = new File("Emp.txt");
Scanner in = new Scanner(inputfile);
n = in.nextInt() - 1;
in.nextLine();
in.useDelimiter("");
for (int i=0;i<=n;i++)
{
int l = 0;
int m = 0;
int n = 0;
line = in.nextLine();
while (Character.isDigit(line.charAt(l)))
{
l++;
}
m = l + 1;
while (!Character.isLetter(line.charAt(m)) && !Character.isWhitespace(line.charAt(m)))
{
m++;
}
n = m + 1;
while (!Character.isDigit(line.charAt(n)))
{
n++;
}
eId = Integer.parseInt(line.substring(0, l));
emp.setEmpId(eId);
phne = line.substring(l + 1, m - 1);
emp.setTelephone(phne);
nme = line.substring(m + 1, n - 1);
emp.setName(nme);
yrs = Integer.parseInt(line.substring(n));
emp.setYears(yrs);
empArr.add(i, emp);
}
in.close();
}
class for set and get methods:
public class Employee
{
private int empId;
private String telephone;
private String name;
private int yearsOfWork;
public Employee(int id, String name, String telephone, int yearsOfWork)
{
empId = id;
this.telephone = telephone;
this.name = name;
this.yearsOfWork = yearsOfWork;
}
public void setEmpId(int id)
{
empId = id;
}
public void setName(String name)
{
this.name = name;
}
public void setTelephone(String telephone)
{
this.telephone = telephone;
}
public void setYears(int years)
{
yearsOfWork = years;
}
public int getEmpId()
{
return empId;
}
public String getName()
{
return name;
}
public String getTelephone()
{
return telephone;
}
public int getYears()
{
return yearsOfWork;
}
public String toString()
{
return "ID:" + empId + ", name: " + name + ", phone: " + telephone + ", years of work: " + yearsOfWork + "\n";
}
}
When I call the get method of my ArrayList outside of its for loop, the text at each index is overwritten by the text at the last index.
I think I'm missing some fundamental concept of constructors and objects here.
Any help is appreciated. Thanks.
Your hunch is correct, you are missing the emp object creation. You have to move the emp object creation into the loop.
Your Employee class and getter/setter methods are correctly written.
Rewrite your fileReader() method similar to given below : -
String line ="";
//Declare an Arraylist for an Employee
List<Employee> employee = new ArrayList<Employee>();
//Read a file
File inputfile = new File("Emp.txt file path");
Scanner in = new Scanner(inputfile);
//Reading a number from a first sentence
int n = Integer.parseInt(in.nextLine());
for (int i=0;i<n;i++) {
// Reading each sentence
line = in.nextLine();
//Parse an Emp id
int eId = Integer.parseInt(line.substring(0, 2));
//Parse a phone number
String phone = line.substring(3, 14);
//Parse a name
String name = line.split("\\d+")[4];
//Parse years
int years = Integer.parseInt(line.split("\\D+")[4]);
//Now create an object by putting all above values in a constructor
Employee emp1 = new Employee(eId, name, phone, years);
//Add that object in an arraylist
employee.add(emp1);
}
//As you have overridden toString method, print an arraylist
System.out.println(emp.toString());
//Closing the scanner
in.close();
}
Hope this helps.
Related
I'm trying to take data out of a txt file and create comparable objects out of the data and add them to an array. After that array is created, I want to make a 2d array that stores a 1 in a slot if two options meet the requirements. I keep getting a String index out of range: 0 error though and I do not know where it comes from.
import java.util.*;
import java.io.*;
public class CourseScheduler
{
public int numberOfCourses;
public int[][] adjacent;
public Course[] courses;
public CourseScheduler(String filename)
{
File file = new File(filename);
try{
Scanner scan = new Scanner(file);
numberOfCourses = scan.nextInt();
courses = new Course[numberOfCourses];
adjacent = new int[numberOfCourses][numberOfCourses];
scan.useDelimiter(",|\\n");
for(int i = 0; i < numberOfCourses;i ++){
if(scan.hasNext()){
String dept = scan.next();
String num = scan.next();
String building = scan.next();
String room = scan.next();
String instruct = scan.next();
courses[i] = new Course(dept, num, building, room, instruct);
}
}
}
catch(FileNotFoundException ex){
System.out.println("File was not found");
}
for(int x = 0;x<numberOfCourses;x++){
for(int y = 0;y<numberOfCourses;y++){
adjacent[x][y] = (courses[x].compare(courses[y]));
}
}
}
This is the code for the main class
public class Course{
String department;
String courseNum;
String buildingCode;
String roomCode;
String instructorName;
public Course(String dept, String number, String building, String room, String instructor){
department = dept;
courseNum = number;
buildingCode = building;
roomCode = room;
instructorName = instructor;
}
public String getDept(){
return department;
}
public String getCourse(){
return courseNum;
}
public String getBuilding(){
return buildingCode;
}
public String getRoom(){
return roomCode;
}
public String getInstructor(){
return instructorName;
}
public String toString(){
return department + ";" + courseNum + ";" + buildingCode + ";" + roomCode + ";" + instructorName;
}
public int compare(Course comp){
int ans = 1;
String compNum = comp.getCourse();
if(instructorName == comp.getInstructor())
ans = 0;
if(buildingCode == comp.getBuilding()){
if(roomCode == comp.getRoom())
ans = 0;
}
if(department == comp.getDept()){
if(courseNum.charAt(0) == compNum.charAt(0))
ans = 0;
}
return ans;
}
}
this is the code for the course class
Educated guess: Most likely your error is coming from this line:
if(courseNum.charAt(0) == compNum.charAt(0))
ans = 0;
Either courseNum or compNum are empty.
I did not try to compile and run it but its seems that the exception comes from this line
if(courseNum.charAt(0) == compNum.charAt(0))
If a string is empty, charAt(0) will throw exactly the given exception.
Tip: if you don't know how to use a debugger, use the old fashioned System.out.println(). Put println() here and there in your code to understand how it works.
package chapter10;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Customer {
private String name;
private String streetAddress;
private String phoneNumber;
private int total;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getStreetAddress(){
return streetAddress;
}
public void setStreetAddress(String streetAddress) {
this.streetAddress = streetAddress;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public int getTotal(){
return total;
}
public void setTotal(int total){
this.total = total;
}
public static void assign(){
int a = (int) (Math.random() + 10);
int r = (int) (Math.random() + 10);
int f = (int) (Math.random() + 10);
System.out.println(a + r + f + "x" + "x" + "x");
}
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
ArrayList <Customer > customerList = new ArrayList <Customer>();
char ans;
do
{
Customer customer = new Customer();
System.out.print("Customer name ");
customer.setName(in.next());
int i = 0;
++i;
System.out.print("Street Address ");
customer.setStreetAddress(in.next());
System.out.print("Phone Number ");
customer.setPhoneNumber(in.next());
customerList.add(customer);
System.out.println("Enter total sales ");
customer.setTotal(in.nextInt());
System.out.println("Would you like to enter in a new customer ( y/n)? ");
String answer = in.next();
ans = answer.charAt(0);
((String) customerList).concat("")
} while(ans == 'y');
for(Customer c: customerList){
System.out.print(c.getName() + "\n" + "Phone number is " +c .getPhoneNumber() +"\n" + "Total sales is "+ c.getTotal() + "\n" + "Address is"+ c.getStreetAddress());
}
for(int i=0; i<customerList.size(); i++){
//System.out.print(customerList.get(i).getName());
}
}
}
I need to assign a number to each value in the arraylist but i am getting an error that says that I have to convert to string (arraylist). How do I add it?
If what I gather from the comments is correct then I believe this is what you want:
Your current assign() is incorrect if you want random values 1-10, it should look like this instead:
public String assign(){
Random rand = new Random();
int a = rand.nextInt(10) + 1;
int r = rand.nextInt(10) + 1;
int f = rand.nextInt(10) + 1;
return a+r+f+"xxx";
}
Customer will look like this:
public class Customer {
private String name;
private String customerNumber;
private String streetAddress;
private String phoneNumber;
private int total;
...
...
...
public String getCustomerNumber() { return this.customerNumber; }
public void setCustomerNumber(String cNumber) { this.customerNumber = cNumber; }
And assigning the numbers should look like this:
for(Customer c : customerList) {
c.setCustomerNumber(assign());
}
Also avoid this line of code, it's a really bad idea:
((String) customerList).concat("")
You should probably rename the customerNumber to customerID.
Hiiii
As i understand you are trying to to add number to each value to arrayList ,And same time you are creating arrayList of customer object, So first understand about arrayList of object,
Customer c1 = new Customer();
Customer c2 = new Customer();
ArrayList<Customer> al = new ArrayList();
al.add(c1);
al.add(c2);
Here this ArrayList object save only address of customer object so how can you change the address of Customer object ; You can not add number in Customer type ArrayList Object,
There is another way typecast your ArrayList to Object type and then no need to typecast again , you can add any type of object in ArrayList
like this,
Customer c1 = new Customer();
Customer c2 = new Customer();
ArrayList<Object> al = new ArrayList();
al.add(c1);
al.add(c2);
In your code there's the following line:
((String) customerList).concat("")
Trying to cast a List to a String is doomed to failure - I'm not sure why do you think it should work.
If you want a String representation of the list, you should implement a toString() method in class Customer and then you can do something like:
System.out.println(Arrays.toString(customerList.toArray()));
Instead of using ArrayList, you can use Map. In which you can have the number as key and value as Customer.
http://examples.javacodegeeks.com/java-basics/java-map-example/ Contains the example of using Map
Answer in Storing a new object as the value of a hashmap? contains info about how to use Object as value in HashMap
The following code should produce a program that allows one to search for people in an address book, but I'm having some issues with the following lines of code marked. I don't think I'm missing a class...This is odd.
I'm fairly new in java so I apologize if this is basic.
Apparently BinarySearchTree can't be resolved to a type
import java.util.Scanner;
import java.io.*;
public class useBinarySearchTree
{
public static void main (String[] args)
{
BinarySearchTee<AddrEntry> addrbook = new BinarySearchTree<AddrEntry>();// error exists here
AddrEntry inentry, tentry;
String nameLook;
Scanner keybd = new Scanner(System.in);
String again;
final int INORDER = 1;
int numentries;
int i;
int ok;
// create address book from input file
buildAddrBook(addrbook);
do
{
// prompt user for name to look up
System.out.println("Address/Phone Lookup:\n" + "Enter name: ");
nameLook = keybd.nextLine();
inentry = new AddrEntry(nameLook, null, null, null);
tentry = addrbook.get(inentry);
if (tentry != null)
{
// print the address book entry
System.out.println("\nAddress Book Entry\n");
System.out.println("__________________\n");
System.out.println(tentry);
System.out.println();
}
else
{
// if the person is not in the book, see if they should be added
System.out.println("\n" + nameLook + " not found in address book\n");
System.out.println("\nWould you like to add this person? [y or n] => ");
again = keybd.nextLine();
System.out.println(again);
if (again.equals("Y") || again.equals("y"))
addEntry(addrbook, keybd);
}
System.out.println("\nAnother Lookup? [y or n] => ");
again = keybd.nextLine();
}
while (again.equals("Y") || again.equals("y"));
// prompt the user to see if they want to see the entire address book before exiting
System.out.println("\nPrint the address book? [y or n] => ");
again = keybd.nextLine();
if (again.equals("Y") || again.equals("y"))
{
System.out.println();
numentries = addrbook.reset(INORDER);
for (i = 1; i <= numentries; i++)
{
tentry = addrbook.getNext(INORDER);
System.out.println(tentry);
}
}
}
// read entries from file and insert them into the address book
public static void buildAddrBook (BinarySearchTree<AddrEntry> addrbook)// here as well {
AddrEntry hold;
String name;
String street;
String town;
String phone;
int ok = 1;
try
{
FileReader freader = new FileReader("addrbook.dat");
BufferedReader addresses = new BufferedReader(freader);
name = addresses.readLine();
while (name != null)
{
street = addresses.readLine();
town = addresses.readLine();
phone = addresses.readLine();
hold = new AddrEntry(name, street, town, phone);
addrbook.add(hold);
name = addresses.readLine();
}
}
catch(
Exception e
)
{
}
}
// add a new entry to the address book
public static void addEntry (BinarySearchTree<AddrEntry> addrbook, Scanner keybd)//also here {
int ok;
AddrEntry hold;
String name;
String street;
String town;
String phone;
System.out.println("\nEnter name: ");
name=keybd.nextLine();
System.out.println("Enter street address: ");
street=keybd.nextLine();
System.out.println("Enter town, state, and zip: ");
town=keybd.nextLine();
System.out.println("Enter phone number: ");
phone=keybd.nextLine();
hold=new
AddrEntry (name, street, town, phone);
addrbook.add(hold);
}
AddrEntry class
public class AddrEntry implements Comparable<AddrEntry> {
private String name;
private String street;
private String town;
private String phone;
public AddrEntry() {}
public AddrEntry(String nn, String st, String tt, String ph) {
name = nn;
street = st;
town = tt;
phone = ph;
}
public void setEntry(String nn, String st, String tt, String ph) {
name = nn;
street = st;
town = tt;
phone = ph;
}
public String toString() {
return name + "\n" + street + "\n" + town + "\n" + phone;
}
public boolean equals(Object ptest) {
if (ptest == null || !(ptest instanceof AddrEntry))
return false;
return this.name.equals(((AddrEntry)ptest).name) &&
this.street.equals(((AddrEntry)ptest).street) &&
this.town.equals(((AddrEntry)ptest).town) &&
this.phone.equals(((AddrEntry)ptest).phone);
}
public int compareTo(AddrEntry ent) {
return name.compareTo(ent.name);
}
}
Having trouble figuring out exactly how to do this. Ive wrote 10 different things and worked on it for 8 hours and have yet to figure out how to get this to work. What I'm trying to do with this program is get a the persons name, friends name, persons age, friends age, and persons popularity (All of this from a .txt file with each line as : Michelle, 12/20/2008, Camilla) . I have gotten the persons name to output correctly, persons age to output correctly, and persons friend to output correctly. But having trouble with popularity and getting friends age from personsofinterest's age.
What I need help with :
1.Popularity points adding up and returned for each time the personOfInterest is in the name array. With the popularity I have went back and debugged it after i was getting 0 for every popularity for each person. And I got that it wasn't adding anything to the return, I tried many different ways but still could not figure it out.
2.Setting personOfInterest name to certain age to be used as friendsAge if the users friend is a personOfInterest already found age for.(All personOfInterest names in .txt field is someones friend)
friends_data.txt :
Michelle, 12/20/2008, Camilla
Bryan, 3/8/2007, Tom
Camilla, 6/7/2005, Michelle
Tom, 10/15/2007, Bryan
Charlotte, 3/2/2008, Michelle
I believe my code looks a little messy, started going back and throwing things together I thought would work.
Person Class :
import java.util.ArrayList;
public class Person {
public String personsName;
public String personsFriend;
public String personsBirthday;
public int personsPopularity;
public int popularity = 0;
public ArrayList<String> friends = new ArrayList<>();
public Person(String aName, String aFriend, String aBirthday) {
personsName = aName;
personsFriend = aFriend;
friends.add(personsFriend);
personsBirthday = aBirthday;
}
public String getName() {
return personsName;
}
public String getFriendsName() {
return personsFriend;
}
public String getBirthday() {
return personsBirthday;
}
public void getPopularityNumber(){
for(int i = 0; i < friends.size(); i++){
if (personsName.equals(friends.get(i))){
popularity = 1 + popularity;
}
else
popularity = popularity;
}
System.out.println(popularity);
}
public String getFriend() {
return personsFriend;
}
public int getAge() {
int MONTH = 0;
int DAY = 0;
int YEAR = 0;
for (int i = 0; i < 3; i++) {
String[] dates = personsBirthday.split("/");
String month = dates[0];
String day = dates[1];
String year = dates[2];
MONTH = Integer.parseInt(month);
DAY = Integer.parseInt(day);
YEAR = Integer.parseInt(year);
}
int age = (2014 - YEAR);
int moAge = (5 - MONTH);
if (moAge < 0) {
age--;
}
return age;
}
}
Main File :
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.util.ArrayList;
public class PersonTester {
public static void main(String[] args) throws FileNotFoundException {
//Get that file and start the scan on that broseph
File inputFile = new File("friends_data.txt");
Scanner in = new Scanner(inputFile);
//Set up an array for our Person objects
final int SIZE = 5;
Person[] personsOfInterest = new Person[SIZE];
String[] friends = new String[5];
//Lets get this i declared as 0 for our array!
int i = 0;
int popularity = 0;
String person;
while (in.hasNextLine()) {
String line = in.nextLine();
String[] nameBirthdayname = line.split(", ");
person = nameBirthdayname[0];
String birthday = nameBirthdayname[1];
String friend = nameBirthdayname[2];
friends[i] = friend;
personsOfInterest[i] = new Person(person, friend, birthday);
i++;
}
for (i = 0; i < SIZE; i++) {
System.out.println("");
System.out.println("New Person");
System.out.println("--------------------------------------------------------");
System.out.println("Persons Name : " + personsOfInterest[i].getName());
System.out.println("Popularity : " + personsOfInterest[i].getPopularityNumber());
System.out.println("Their age on May 1, 2014 : " + personsOfInterest[i].getAge());
System.out.println("Persons Best Friend : " + personsOfInterest[i].getFriend());
System.out.println("Best Friends Age on May 1,2014 : " + personsOfInterest[i].getName());
System.out.println("--------------------------------------------------------");
}
}
}
Have Also Tried this for getPopularityNumber Method :
public void getPopularityNumber(String[] friends) {
for (int i = 0; i < 5; i++) {
if (personsName.equals(friends[i])) {
popularity = 1 + popularity;
} else
popularity = popularity;
}
System.out.println(popularity);
}
Any help would be greatly appreciated!
I have used this site to help me on many of my programming assignments before but I can not find anything similar to the issue that I am having now.
I am trying to first print the myHobbies array in the toString of the person class using the method printHobby, as well as calculate the total duration the the user has been doing the Hobby in printDuration. I am not sure why I can not get it to work and have been struggling with it for a while.
Any help would be appreciated. Here are my classes. This is my first time posting so if I am doing something wrong, please let me know.
//--------------------Person--------------------
public class Person {
String fName;
String lName;
String address;
int age;
String hobbyText;
private double durationH = 0;
private double totalDuration = 0;
Person(String f, String l, String a, int ag) {
fName = f;
lName = l;
address = a;
age = ag;
}
static Hobby[] myHobbies = new Hobby[5];
static int i = 0;
public static void setHobby(Hobby mh) {
myHobbies[i] = mh;
i++;
}
public String toString() {
return fName + " " + lName + " " + address + " " + age + " "
+ printDuration() + " ";
}
public double printDuration() {
for (int k = 0; k < myHobbies.length; k++)
totalDuration += myHobbies[k].getDuration();
return totalDuration;
}
public String printHobbies() {
for (int j = 0; j < myHobbies.length; j++)
hobbyText = myHobbies[j].toString();
return hobbyText;
}
}
//--------------------HobbyDriver--------------------
import java.util.Scanner;
public class HobbyDriver {
public static void main(String[] args) {
Hobby[] newHobby = {
new Hobby("Comics", "09/25/2012", "The Comic Store", 1),
new Hobby("Baseball", "09/30/2012", "Fenway Park", 3),
new Hobby("Programming", "09/212/2012", "Home", 6),
new Hobby("Board Games", "09/01/2012", "Tom's House", 3),
new Hobby("Watching Dr. Who", "09/27/2012", "Home", 1) };
String personChoice;
Scanner hobbyScan = new Scanner(System.in);
do {
String fName;
String lName;
int age;
String address;
String hobbyName;
String partDate;
String location;
double duration;
int userHobby;
String hobbyChoice;
System.out.println("What is your first name?");
fName = hobbyScan.nextLine();
System.out.println("What is your last name?");
lName = hobbyScan.nextLine();
System.out.println("What is your address?");
address = hobbyScan.nextLine();
System.out.println("What is your age?");
age = hobbyScan.nextInt();
hobbyScan.nextLine();
do {
System.out
.println("What hobbies would you like to do?\n"
+ "choose between Comics(0)\nBaseball(1)\nProgramming(2)\nBoard Games(3)\nWatching Dr.Who(4)\n"
+ "\nEnter the name of the hobby and then press enter");
userHobby = hobbyScan.nextInt();
hobbyScan.nextLine();
System.out
.println("Would you like to add another hobby? (enter yes/no)");
hobbyChoice = hobbyScan.nextLine();
Person.setHobby(newHobby[userHobby]);
} while (hobbyChoice.equals("yes"));
System.out
.println("Would you like to add another person? (enter yes/no)");
personChoice = hobbyScan.nextLine();
int i = 0;
Person[] newPerson = new Person[5];
newPerson[i] = new Person(fName, lName, address, age);
System.out.println(newPerson[i].toString());
i++;
} while (personChoice.equals("yes"));
}
}
//--------------------Hobby--------------------
public class Hobby {
private String hobbyName;
private String partDate;
private String location;
private double duration;
Hobby(String h, String p, String l, double d) {
hobbyName = h;
partDate = p;
location = l;
duration = d;
}
public String toString() {
return hobbyName + " " + partDate + " " + location + " " + duration;
}
public void setDuration(double d) {
d = duration;
}
public double getDuration() {
return duration;
}
}
the problem is the following:
public String printHobbies() {
for (int j = 0; j < myHobbies.length; j++)
hobbyText = myHobbies[j].toString();
return hobbyText;
}
First, you overwrite your string in each loop. Write
hobbyText += myHobbies[j].toString();
Second, You will get a NPE if you don't add 5 Hobbies, because every item in the array is null at the beginning.
So you will have to check if myHobbies[j] is not null:
public String printHobbies() {
for (int j = 0; j < myHobbies.length; j++) {
if(myHobbies[j] != null) {
hobbyText += myHobbies[j].toString();
}
}
return hobbyText;
}
You also may want to have a look at Collections: http://docs.oracle.com/javase/1.4.2/docs/api/java/util/Collections.html
There are few bugs which may cause an issue in your code, it depends on current usage.
You do not reset the total duration, which means, that it returns proper result only after the first invocation. Otherwise it is multiplied by the number of invocations.
public double printDuration() {
for (int k = 0; k < myHobbies.length; k++)
totalDuration += myHobbies[k].getDuration();
return totalDuration;
}
You use the simple array with the fix size 5. It means, that if you add more than 5 hobbies, it will throw IndexOutOfBoundsException.
You call toString() method on all hobbies in the array nevertheless they were set. The arrays are initialized to null by default, which means, that if you set less than 5 hobbies, you try to call it on null which throws NullPointerException.
public String printHobbies() {
for (int j = 0; j < myHobbies.length; j++)
hobbyText += myHobbies[j].toString();
return hobbyText;
}