Unable to print out the desired output - java

So I am creating a program that reads customer details and order details from two different files. I created methods to read the file, store the data in the object of customers and then add the object of customers into linkedlist.. Now when I try doing the same for order file, I am getting the wrong output. so in the code shown below, I am trying to check if the customer name entered in order file matches the name stored in customer linkedlist.. So say I have two rows in the order.txt file:
Ord101 true James
Ord102 false Jim
with what I have done, I get the following output:
Ord102 false Jim
Ord102 false Jim
instead of getting the correct output which would be:
Ord101 true James
Ord102 false Jim
because both, James and Jim are names present in Customer file and linkedlist. So here is my code for reading order file:
public void readFileOrder() {
Scanner y;
String b,c,d;
LinkedList<Customers> list=new LinkedList<Customers>(); //another method was already created to add data inside list and its working so list contains data
LinkedList<order> list1=new LinkedList<order>();
Boolean isOpen;
order Order1=new order();
while(y.hasNext())
{
b=y.next();
isOpen=y.nextBoolean();
d=y.next();
System.out.println(list);
Customers customers1=new Customers();
for(int i=0;i<list.size();i++) //this is where i'm checking if the customer name in the order file matches the value in list
{
if(list.get(i).getName().equals(d))
{
customers1=list.get(i);
Order1.setCustomer(customers1);
Order1.setName(b);
Order1.setIsOpen(isOpen);
list1.add(Order1);
}
}
}
for(int j=0;j<list1.size();j++)
{
System.out.println(list1.get(j).getCustomer()+" and "+list1.get(j).getName()+" and "+list1.get(j).getIsOpen());
}
}
just in case, provided below are Customer and order class:
import java.util.LinkedList;
public class Customers {
#Override
public String toString() {
return "Customers [Name=" + Name + ", age=" + age + ", email=" + email + ", Address=" + Address + "]";
}
String Name;
int age;
String email;
String Address;
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getAddress() {
return Address;
}
public void setAddress(String address) {
Address = address;
}
public void removeCustomer(String name2, LinkedList<Customers> list) {
for(int k=0;k<list.size();k++)
{
if(list.get(k).getName().equals(name2))
{
list.remove(list.get(k));
}
}
}
}
order class:
import java.util.LinkedList;
public class order{
String name;
Boolean isOpen;
Customers customer;
String cusName;
public order() {
super();
}
public String getName() {
return name;
}
public order(Customers customer) {
super();
this.customer = customer;
}
public void setName(String name) {
this.name = name;
}
public Boolean getIsOpen() {
return isOpen;
}
public void setIsOpen(Boolean isOpen) {
this.isOpen = isOpen;
}
public String getCustomer() {
return customer.getName();
}
public void setCustomer(Customers customer) {
this.customer=customer;
this.cusName=customer.getName();
}
}

You are adding references to the same order to the list over and over again, each time overwriting the attributes set in the previous iteration of the loop. Instead, create a new order inside the loop.
In other words, change this:
order Order1=new order();
while(y.hasNext()) {
to this:
while(y.hasNext()) {
order Order1=new order();

Related

Searching through a list of child subjects

So my issue is trying to use the getName() and getPhone() methods (in class Contact) in the main method.
I don't know how to use them in this context with all 3 classes.
Here is what the program is supposed to be doing
Apologies if this is not too concise, I just started programming recently.
public class LookupPhonebook{
public static void main(String[] args) {
Phonebook phonebook = new Phonebook("Sam Johnson");
phonebook.addContact(new Contact("Kelly Wong", "(02) 12345678"));
phonebook.addContact(new Contact("Richard Jackson", "(02) 87654321"));
phonebook.show();
String searchName = Input.askString("Enter a contact name: ");
phonebook.findContactByName(searchName);
if (searchName.equals(phonebook.getName())) {
System.out.println("Phone number is " + phonebook.getPhone());
}
else {
System.out.println(searchName + " not found");
}
}
}
import java.util.*;
public class Phonebook {
private String owner;
private ArrayList<Contact> contacts = new ArrayList<Contact>();
public Phonebook(String owner) {
this.owner = owner;
}
public void addContact(Contact contact) {
contacts.add(contact);
}
public void show(){
System.out.println(owner + "'s phonebook");
for (Contact contact : contacts) {
System.out.println(contact);
}
}
public Contact findContactByName(String name) {
for (Contact contact : contacts) {
if (contact.getName().equals(name)) {
return contact;
}
else {
continue;
}
}
return null;
}
}
public class Contact {
private String name;
private String phone;
public Contact(String name, String phone) {
this.name = name;
this.phone = phone;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String toString() {
return name + ": " + phone;
}
}
This method is the only one used in a class provided to help with the exercise.
/**
* Asks the user the given question, waits for the user to enter a
* single character at the keyboard, and then returns this character.
*
* #param question the question to be printed
* #return the character that the user entered as an answer to the question
*/
public static char askChar(String question) {
System.out.print(question + " ");
return scanner.nextLine().charAt(0);
}
You need to store the result from findContactByName to a local variable following the instruction. The original program just throw away the result.
public static void main(String[] args) {
Phonebook phonebook = new Phonebook("Sam Johnson");
phonebook.addContact(new Contact("Kelly Wong", "(02) 12345678"));
phonebook.addContact(new Contact("Richard Jackson", "(02) 87654321"));
phonebook.show();
String searchName = Input.askString("Enter a contact name: ");
// 2. Search contact and store is local variable
Contact result = phonebook.findContactByName(searchName);
// 3. If we found contact
if (result != null) {
System.out.println("Phone number is " + result.getPhone());
} else {
// 4. No contact is found
System.out.println(searchName + " not found");
}
}

Checking if an object is in arraylist in Java

So here is assignment :
A student entity has a name and an address (both represented by an object of class Name and Address), in addition to a university ID, and a course schedule represented by an ArrayList of Courses
Your code should not allow the creation of Two students with the same university ID
So I'm thinking of using ArrayList to hold a list of student and check if student exists or not before create a new student. sorry, this is my first question so I'm trying my best to explain it:
This is my Address class:
public class Address {
private int streetNumber;
private String streetName;
private String city;
private String state;
private int province;
private String country;
public Address (int streetNumber,String streetName,String city,String state,int province,String country)
{
this.streetNumber=streetNumber;
this.streetName=streetName;
this.city=city;
this.state=state;
this.province=province;
this.country=country;
}
public int getStreetNumber() {
return streetNumber;
}
public void setStreetNumber(int streetNumber) {
this.streetNumber = streetNumber;
}
public String getStreetName() {
return streetName;
}
public void setStreetName(String streetName) {
this.streetName = streetName;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public int getProvince() {
return province;
}
public void setProvince(int province) {
this.province = province;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String toString() {
return " [streetNumber=" + streetNumber + ", streetName=" + streetName
+ ", city=" + city + ", state=" + state + ", province="+province+", country="
+ country + "]";
}
public boolean equals(Address add)
{
if(add==null)
{
return true;
}
if(this.getClass()!=add.getClass())
{
return false;
}
Address address=(Address) add;
return streetNumber==address.streetNumber &&
province==address.province && streetName.equals(address.streetName)
&& city.equals(address.city)&& state.equals(address.state)&& country.equals(address.country);
}
}
This is my Name class
public class Name {
private String firstName;
private String lastName;
private char middle;
public Name (String fiName,String laName, char middle)
{
this.firstName=fiName;
this.lastName=laName;
this.middle=middle;
}
public String getFirst()
{
return firstName;
}
public void setFirst(String first)
{
firstName=first;
}
public String getLast()
{
return lastName;
}
public void setLast(String last)
{
lastName=last;
}
public char getMiddle()
{
return middle;
}
public void setMiddle(char midd)
{
middle=midd;
}
/*public String toString()
{
return "[First Name= "+ firstName +" Last Name "+ lastName+" Middle Name "+ middle +"";
}*/
}
This is my Student class:
public class Student {
private int studentId;
private Name name;
private Address address;
boolean a;
ArrayList<Course> courseSchedule = new ArrayList<Course>();
ArrayList<Student> student=new ArrayList<Student>();
public Student(String fiName,String laName, char middle,int stNumber,String stName,String city,String state,int province,String country,int id)
{
if(student.contains(id))
{
System.out.println("Student cannot be same id");
}
else
{
address= new Address(stNumber,stName,city,state,province,country);
name=new Name(fiName,laName,middle);
this.studentId=id;
student.add();
}
}
public int getID()
{
return studentId;
}
public void setId(int id)
{
this.studentId = id;
}
public ArrayList<Course> getCourseSchedule()
{
return courseSchedule;
}
public void setCourseSchedule(ArrayList<Course> courseSchedule)
{
this.courseSchedule = courseSchedule;
}
public void addCourse(Course c) {
courseSchedule.add(c);
}
public void dropCourse(Course course) {
courseSchedule.remove(course);
}
}
My question is how can you add Student Object into Student ArrayList
and how can I check if the Student Id exists in ArrayList with contains() method
student.contains(id) this line right here it does not seem to be right
I hope im explain my question a little clear now. Sorry for my english also.
You would not keep a list of Student objects within the class for Student. Your ArrayList<Student> student=new ArrayList<Student>(); does not belong there.
You would have another structure or collection kept elsewhere named something like StudentBody. When a student is instantiated, it is added to the StudentBody collection.
List< Student > studentBody = new ArrayList< Student >() ; // This list is stored somewhere else in your app.
You could loop a List of Student objects in the StudentBody object. For each you would access the UniversityId member field and compare to your new one being added.
Or you could use a Map, where the key is a UniversityId object and the value is a Student object. Check for an existing key before adding.
These solutions ignore the important issue of concurrency. But that is likely okay for a homework assignment in a beginning course in programming.
Use A HashMap() for collecting information based on unique Ids.
public class Student {
private int studentId;
private Name name;
private Address address;
private static HashMap<Integer,Student> students = new ConcurrentHashMap<>(); // Make a static Map so all objectrs shared same data
public Student(String fiName,String laName, char middle,int stNumber,String stName,String city,String state,int province,String country,int id)
{
if(students.contains(id))
{
System.out.println("Student can be same id");
}
else
{
address= new Address(stNumber,stName,city,state,province,country);
name=new Name(fiName,laName,middle);
this.studentId=id;
students.put(id,this); // use this to add current object
}
}

Generic linked list inside of linked list?

I am trying to write a program which stores information about a person in a linked list. I made a simple person class to store the name, age and addresses in the list. I would also like to store multiple addresses for EACH person, and a fact about the place in another linked list, inside the person class.
So for example, "Tara" can have a home address of "10 Central Ave" and a work address of "5 Willow street" etc. The problem is, I don't know how to have a linked list inside another.
My goal is to check whether the person's name is already on the list, and if so, add another address for them. (So that there is no repeats). I am a beginner and can really use some help.
public class Person {
private String name;
private int age;
public LinkedList <String> adresses;
public Person() {
name = "default";
age = 0;
adresses = new LinkedList<>();
}
public Person(String n, int a) {
name = n;
age = a;
}
public LinkedList<Adress> getAdresses() {
return adresses;
}
public void setAdresses(LinkedList<Adress> adresses) {
this.adresses = adresses;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String toString() {
return name+" "+age+" "+adresses;
}
}
public class Adress {
public String adress;
public String fact;
public Adress(String a, String f) {
adress = a;
fact = f;
}
public String getAdress() {
return adress;
}
public void setAdress(String adress) {
this.adress = adress;
}
public String getFact() {
return fact;
}
public void setFact(String fact) {
this.fact = fact;
}
}
public class Test {
public static void main(String[] args) {
Person Tara = new Person("Tara",35);
Person Judah = new Person("Judah",28);
Person Mark = new Person("Mark",45);
Person Seth = new Person("Seth",23);
LinkedList<Object> tester = new LinkedList<>();
tester.add(Tara);
tester.add(Judah);
tester.addLast(Mark);
tester.addLast(Seth);
System.out.println(tester);
}
}
How is about to use the next classic data structure for your project?
public class Person {
private String name
private int age;
public List<Address> addresses;
//...
}

Convert Object to String

I have a couple to class in which I'm getting and setting a few things and then finally calling it in my main method. But when I call my class in the main method it just gives me the object instead of name,address and age. I know this structure is very complicated but I want to keep this structure because later on I will be adding a lot of things to this. It would be AMAZING if someone could tell me how to do this. I would really appreciate this. Below is my code for all my classes
This is my first class
public class methodOne
{
public String getName()
{
String name = "UserOne";
return name;
}
public int getAge()
{
int age = 17;
return age;
}
public String getAddress()
{
String address = "United States";
return address;
}
}
This is my second class
public class methodTwo
{
String name;
String address;
int age;
public methodTwo(methodOne objectOne)
{
name=objectOne.getName();
address=objectOne.getAddress();
age=objectOne.getAge();
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
This is my third class
public class methodThree {
private methodTwo methodTwoInMethodThree;
private methodOne methodOneInMethodThree;
public methodThree()
{
this.methodOneInMethodThree = new methodOne();
this.methodTwoInMethodThree = new methodTwo(methodOneInMethodThree);
}
public methodTwo getMethodTwoInMethodThree() {
return methodTwoInMethodThree;
}
public void setMethodTwoInMethodThree(methodTwo methodTwoInMethodThree) {
this.methodTwoInMethodThree = methodTwoInMethodThree;
}
}
This is my fourth class which is the method maker
public class methodMaker {
public methodThree brandNewFunction(methodTwo object)
{
methodThree thirdMethod = new methodThree();
thirdMethod.setMethodTwoInMethodThree(object);
return thirdMethod;
}
}
This is my main class which calls methodMaker. What I want to achieve is that when I print the value it should print the name,address and age but instead it just prints trial.methodThree#4de5ed7b
public class mainClass {
public static void main(String args[])
{
methodMaker makerOfMethods = new methodMaker();
methodOne one = new methodOne();
methodTwo object = new methodTwo(one);
System.out.println(makerOfMethods.brandNewFunction(object).toString());
}
}
What you need to do is to override the default implementation of the .toString() method in the objects you want to print out:
#Override
public String toString()
{
return "Name: " + this.name;
}
EDIT:
I do not know exactly where you are printing, and you naming convention doesn't really help out, but from what I am understanding, you would need to implement it in all of you classes since they all seem to be related to each other.
So, in your methodOne class (can also be applied to methodTwo):
#Override
public String toString()
{
return "Name: " + this.name + " Age: " + this.age + " Address: + " this.address;
}
In your methodThree class:
private methodTwo methodTwoInMethodThree;
private methodOne methodOneInMethodThree;
#Override
public String toString()
{
StringBulder sb = new StringBuilder();
if(this.methodTwoInMethodThree != null)
{
sb.append("Method 2:").append(methodTwoInMethodThree.toString());
}
if(methodOneInMethodThree != null)
{
sb.append("Method 1:").append(methodOneInMethodThree.toString());
}
return sb.toString();
}
When you call
MyClass myObject = new MyClass();
System.out.println(myObject);
Implicitly , java calls instead
System.out.println(myObject.toString());
So, if in MyClass, you override toString(), then whatever your toString method returns is what's gonna be printed.
Side note: are you confusing classes and methods? Methods are functions in your classes, classes are wrappers around a bunch of attributes and methods. Your naming is confusing.
try this code:
public class methodTwo
{
String name;
String address;
int age;
public methodTwo(methodOne objectOne)
{
name=objectOne.getName();
address=objectOne.getAddress();
age=objectOne.getAge();
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String toString(){
return name+" "+address+" "+age;
}
}
Are you printing the object using println()?
From the docs, println():
calls at first String.valueOf(x) to get the printed object's string value
This string value is obtained from the object's toString() method, which:
returns a string consisting of the name of the class of which the object is an instance, the at-sign character `#', and the unsigned hexadecimal representation of the hash code of the object
So if you want to print anything other than this you have to override the toString() method in your object and return a string containing whatever you want.
Just google "override tostring java" and you will see a ton of examples.

Outputing string values from objects saved in an ArrayList

I have a small problem with printing out strings that are stored in an object. The object is stored in an ArrayList.
I have three clases that I use im my program:
Friend Class:
package one;
public class Friend implements InterfaceFriend {
private String name;
private String email;
private String phone;
public Friend(String name, String phone, String email) {
// TODO Auto-generated constructor stub
}
#Override
public String getPhone() {
return phone;
}
#Override
public String getEmail() {
return email;
}
#Override
public String getName() {
return name;
}
#Override
public void setPhone(String phone1) {
phone1 = phone;
}
#Override
public void setEmail(String email1) {
email1 = email;
}
#Override
public void setName(String name1) {
name1 = name;
}
}
FriendInterface:
package one;
public interface InterfaceFriend {
String getPhone(); // Returns phone number.
String getEmail(); // Returns email.
String getName(); // Returns name.
void setPhone(String phone); // Sets phone.
void setEmail(String email); // Sets email.
void setName(String name); // Sets name.
}
and Test Class:
package one;
import java.util.ArrayList;
import java.util.List;
public class FriendTest {
static List<Friend> friends;
static Friend friend;
public static void main(String args[]) {
friends = new ArrayList<Friend>();
friend = new Friend("Jane Doe", "085-5555555", "jane.doe#gmail.com");
friends.add(friend);
friend = new Friend("John Doe", "085-1111111", "john.doe#gmail.com");
friends.add(friend);
friend = new Friend("Paul Weller", "085-3333333", "paul.weller#gmail.com");
friends.add(friend);
System.out.println("Friends added to list:");
System.out.println(friends.toString());
}
}
The problem is that when I am running the System.out.println(friends.toString());from the Test Class i am getting this:
Friends added to list:
[one.Friend#38f0b51d, one.Friend#4302a01f, one.Friend#615e7597]
Instead the Strings with the values that I want. Any help appreciated.
You'll need to override the toString() method in the Friend class as commented already, but you also need to complete the constructor that you're using.
public Friend(String name, String phone, String email) {
this.name = name;
this.phone = phone;
this.email = email;
}
Moreover, the code in your setters are backwards.
In you friend class you need to override toString()
public class Friend implements InterfaceFriend {
...
...
public String toString(){
return name + " " + email + " " + phone; // or whatever format you want printed
}
}
you simply override toString method. place this inside of Friend class. problem solved..
public String toString(){
// return your Strings..
}
Override to toString() in your class, to what output suits you. The reason you're getting that output is because the default toString() provided in objects is a hash code.
public String toString(){
return name; //assuming you only want to display the name else edit it
}

Categories