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!
Related
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.
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.
Is it possible to do such a thing? Say I wanted to add the values I gave values to in CountriesTest and add them to the ArrayList in Countries. Also how could I reference aCountries to print for option 2, seeing that I created it inside option 1 I can't access it anywhere else.
Here is my interface
public interface CountriesInterface
{
public String largestPop();
public String largestArea();
public String popDensity();
}
Here is the Countries class
import java.util.*;
public class Countries implements CountriesInterface
{
private final List<CountriesInterface> theCountries = new ArrayList<>();
private String cName;
private String finalPopName;
private String finalAreaName;
private String finalDensityName;
private int cPop = 0;
private int cArea = 0;
private int popDensity = 0;
private int popCounter = 0;
private int areaCounter = 0;
private int densityCounter = 0;
public Countries(String cName, int cPop, int cArea, int popDensity)
{
this.cName = cName;
this.cPop = cPop;
this.cArea = cArea;
this.popDensity = popDensity;
}
public String largestPop()
{
for(int i = 0; i < theCountries.size(); i++)
{
if(cPop > popCounter)
{
popCounter = cPop;
finalPopName = cName;
}
}
return finalPopName;
}
public String largestArea()
{
for(int i = 0; i < theCountries.size(); i++)
{
if(cArea > areaCounter)
{
areaCounter = cArea;
finalAreaName = cName;
}
}
return finalAreaName;
}
public String popDensity()
{
for(int i = 0; i < theCountries.size(); i++)
{
if(popDensity > densityCounter)
{
densityCounter = popDensity;
finalDensityName = cName;
}
}
return finalDensityName;
}
}
Here is the CountriesTest class
import java.util.*;
public class CountriesTest
{
public static void main(String[] args)
{
int population = 0;
int area = 0;
int density = 0;
Scanner myScanner = new Scanner(System.in);
boolean done = false;
do
{
System.out.println("1. Enter a country \n2. Print countries with the largest population, area, and population density \n3. Exit");
int choice = Integer.parseInt(myScanner.nextLine());
if (choice == 1)
{
System.out.print("Enter name of country: ");
String input1 = myScanner.nextLine();
System.out.print("Enter area of country in square kilometers: ");
String input2 = myScanner.nextLine();
population = Integer.parseInt(input2);
System.out.print("Enter population of country: ");
String input3 = myScanner.nextLine();
area = Integer.parseInt(input3);
density = population/area;
Countries aCountries = new Countries(input1, population, area, density);
}
else if(choice == 2)
{
System.out.println("The country with the largest population: " );
System.out.println("The country with the largest area: " );
System.out.println("The country with the largest population density is: " );
}
else if(choice == 3)
{
done = true;
}
else
System.out.println("Invalid Choice");
}
while (!done);
System.exit(0);
}
}
OK, there's some mix-up in your code.
You are using the "Countries" class at the same time for an individual Country AND the list of countries. I won't recommand it, but at least you should make "static" members and methods which are for the list of countries. Or you could declare List theCountries = new ArrayList<>(); inside the main method instead.
You are never adding the new "Countries" object to the list of countries. So, if you've declared theCountries in the main method, just uste "theCountries.add(aCountries)" right after the "new Countries(...)".
your seach methods (like largestPop) won't work because they are never searching through the content of the "theCountries" ArrayList. (the "i" variable is just iterating through the indices, but never actually used to get a countent from this ArrayList).
and btw, System.exit(0) is not needed (it's implied)
Can anyone tell me where im going wrong I have three files Person.java Queue.java & Cinema.java, ive managed to do queues without objects Person.java but. I am having trouble implementing with objects.
Heres my Queue.java
public class Queue
{
private Person[] person = new Person[10];
private int rear;
public Queue()
{
rear = 0;
}
public boolean isEmpty()
{
return rear == 0;
}
public String remove() //remove String element
{
String result = person[0].toString(); //shuffle String elements
rear--;
for (int i = 0; i < rear ; i++)
{
person[i] = person[i + 1];
}
return result;
}
public void add(Person x) //add String element
{
if (rear == person.length)
{
resize();
}
person[rear] = x;
rear++;
}
private void resize()
{
Person[] temp = new Person[person.length * 2]; //resize String array
for (int i = 0; i < person.length; i++)
{
temp[i] = person[i];
}
person = temp;
}
}
Then heres Person.java (Object).
public class Person
{
private String name;
private int age = 0;
public Person(String name1, int age1)
{
this.name = name1;
this.age = age1;
}
}
And heres the main java file Cinema.java
import java.util.*;
public class Cinema {
public static void main (String[] args)
{
Queue q = new Queue();
Scanner k = new Scanner(System.in);
System.out.print("Enter name: ");
String name = k.nextLine();
System.out.print("Enter Age : ");
int age = k.nextInt();
q.add(name);
System.out.println(name + " joined queue");
}
}
Basically I want a person to join the queue with a name and age and the first person goes to buy the ticket and the age is checked. I can do the check bit its just getting it to read with objects.
Thanks
So I see two issues up here :
The Queue class seems to be implemented as a Stack rather than a Queue. I would suggest, Google about what queues are .
In your main method
String name = k.nextLine();
System.out.print("Enter Age : ");
int age = k.nextInt();
q.add(name);
Here, add method requires a person object as its parameter rather than a String object.
The code should be like :
String name = k.nextLine();
System.out.print("Enter Age : ");
int age = k.nextInt();
Person p1 = new Person(name,age);
q.add(p1);
Hope this helps.
EDIT!!!:
For your question in the comment. If you want to return age of the people in the Queue. You first would have to make two getter methods. One inside the Person class & other in the Queue class:
In person class:
public int getAge()
{
return age;
}
In Queue class:
public Person[] getPerson()
{
return person;
}
After writing these functions down. You can have the ages of people in the queue as :
Person[] p = q.getPerson(); // q is the Queue object
for(int i=0;i<p.length;i++)
{
if(p[i]!=0)
{
System.out.println(p[i].getAge());
}
}
Hope this helps. if this helps you reach the solution of your problem, do upvote and select the answer as correct one.
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;
}