Cant access object properties java - java

List<Employeee> employees = new ArrayList<>();
Scanner scanner = new Scanner(System.in);
String[] input = new String[6];
int n = Integer.valueOf(scanner.nextLine());
for (int i = 0; i < n; i++) {
input = scanner.nextLine().split(" ");
employees.add(new Employeee(input[0], Double.parseDouble(input[1]), input[2], input[3], input[4],
Integer.valueOf(input[5])));
}
for (Object i : employees) {
System.out.println(i.sallary); //And here ofc idk what to do to print them
System.out.println(i.name);
}
So here i just make a couple of object from my custom class and i put them inside of the list.
And after that i iterate over that list with a for loop and there i want to print their properties, but it doesn't let me. My Employeee class is simple I wont even paste the getters and setters from it.
public class Employeee {
private String name;
private double sallary;
private String possition;
private String department;
private String email;
private int age;
public Employeee(String name, double sallary, String possition, String department, String email, int age) {
this.name = name;
this.sallary = sallary;
this.possition = possition;
this.department = department;
this.email = email;
this.age = age;
}
}

There are numerous problems here.
You are mis-spelling your attribute names with wild abandon.
You are using Object in the for-each statement where you should be using Employee.
The fields you are trying to access directly from outside the class are declared as private, which means you can't. You should be using the respective accessor functions instead.

Related

Why does the 'contains' method return false when I enter the exact name on my ArrayList? [duplicate]

This question already has answers here:
Java List.contains(Object with field value equal to x)
(13 answers)
Closed 1 year ago.
I am trying to make a program that can add a customer's name, age, contact number and email. And I want to search for the name that the user wants, but it does not search the name even if I entered the same name exactly. How can I fix this?
Here is my code:
package com.company;
import java.util.ArrayList;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
ArrayList<customers> customers = new ArrayList<>();
customers.add(new customers("Zen",19,"0912121212","zen#gmail.com"));
customers.add(new customers("Mary",20,"09134343434","mary#gmail.com"));
System.out.println("Enter name: ");
String name = scan.nextLine();
System.out.println(customers.contains(name));
}
}
class customers{
private String name;
private int age;
private String contactNumber;
private String email;
public customers(String name, int age, String contactNumber, String email) {
this.name = name;
this.age = age;
this.contactNumber = contactNumber;
this.email = email;
}
}
List.contains()uses Object.equals() to determine whether an Object is already in that List.
So one approach could be to overwrite that method:
public class Customer
{
private String m_Name;
private int m_Age;
…
#Override
public final boolean equals( final Object o )
{
return o instanceof String name && name.equals( m_Name );
}
}
Although this will work, it is not recommended to implement equals() in this way (see here as a starting point).
Instead you should search for the name in the list:
String name = scan.nextLine();
System.out.println( customers.stream().anyMatch( c -> c.getName().equals( name ) ) );
A completely different approach would be to store the Customer objects not in an instance of List but in an instance of Map, with the name as the key:
public class Main
{
public static void main( String... args )
{
Scanner scan = new Scanner(System.in);
Map<String,Customer> customers = new HashMap<>();
var customer = new Customer( "Zen", 19, "0912121212", "zen#gmail.com" );
customers.put( customer.getName(), customer );
customer = new Customer( "Mary", 20, "09134343434", "mary#gmail.com" );
customers.put( customer.getName(), customer );
System.out.println( "Enter name: " );
String name = scan.nextLine();
System.out.println( customers.containsKey( name ) );
}
}
Finally, it would help in general if you would follow the basic naming conventions for the Java language: class names are starting with a Capital letter.
name is a String. Your List contains customers instances, not Strings. Therefore your List doesn't contain name.
In order to lookup an instance of one type by a key of another type, you can use a Map:
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
Map<String,customers> customers = new HashMap<>();
customers.put("Zen",new customers("Zen",19,"0912121212","zen#gmail.com"));
customers.put("Mary",new customers("Mary",20,"09134343434","mary#gmail.com"));
System.out.println("Enter name: ");
String name = scan.nextLine();
System.out.println(customers.containsKey(name));
}
Or, if you want to search for a customers instance having a certain name, you can iterate over the elements of your List (either with a loop or with a Stream).
For example:
System.out.println(customers.stream().anyMatch(c -> c.getName().equals(name)));
This is assuming your customers class has a getName() getter method.
Add another constructor to your class for just name and iterate over all objects in array list for the same name.
import java.util.ArrayList;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
ArrayList<customers> customers = new ArrayList<>();
customers.add(new customers("Zen",19,"0912121212","zen#gmail.com"));
customers.add(new customers("Mary",20,"09134343434","mary#gmail.com"));
System.out.println("Enter name: ");
String name = scan.nextLine();
customers obj = new customers(name);
customers toBeChecked;
for (int i=0; i<customers.size(); i++) {
toBeChecked = customers.get(i);
if(toBeChecked.getName().equals(obj.getName())) {
System.out.println("Same name");
}
}
}
}
class customers{
private String name;
private int age;
private String contactNumber;
private String email;
public customers(String name, int age, String contactNumber, String email) {
this.name = name;
this.age = age;
this.contactNumber = contactNumber;
this.email = email;
}
public customers (String name) {
this.name = name;
}
public String getName() {
return name;
}
}
The problem here is that you're not defining the ArrayList with a String type. If you want to keep the customers in your list, you can try this solution:
for(customers c:customers){
if(c.getName().equals(name)){
System.out.println(true);
}
}
Make sure to create a getter ( getName() ).

Add new parameters in for using Java ArrayList

I am a beginner using Java and I don't find the solution for this:
public class Company{
private String name;
private int age;
public Company(String n, int a){
name = n;
age = a;
}
/*get and set*/
public static void main(String[] args) {
ArrayList<Company> comp = new ArrayList<Company>();
comp.add(new Company("Tom", 23));
comp.add(new Company("John", 43));
comp.add(new Company("Charles", 25));
}
}
I would like to add parameters in a for, like email, address, etc. But .add is for new elements, no parameters.
Extend the Company class with the email, address fields (1), update the constructor (2), and pass the arguments you want (3).
public class Company {
...
private final String address; // 1
private final String email;
public Company(String n, int a, String address, String email) { // 2
...
this.address = address;
this.email = email;
}
public static void main(String[] args) {
...
comp.add(new Company("Charles", 25, "street", "charles#gmail.com")); // 3
}
}
If you already have an array filled with information for a specific field, you can use a for:
final List<String> emails = Arrays.asList("first#gmail.com", "second#gmail.com");
for (final String email : emails) {
comp.add(new Company(..., ..., ..., email));
}
You need to read about class members.
public class Company{
private String name;
private int age;
private String email;
private String address;
public Company(String n, int a, String e, String addr){
name = n;
age = a;
email = e;
address = addr;
}
First, you need to add variables to your class (that is the place where it will be stored per each class instance, as well as name or age are at the moment
Than you have to modify constructor (or create another one) to be able take these parameters, and also it is good idea to make getters and setters to get or set these parameters individually, so it can looks like this
public class Company{
private String name;
private int age;
private String email;
private String address;
public Company(String n, int a){
name = n;
age = a;
}
public Company(String n, int a,String email, String address){
name = n;
age = a;
this.email = email; //class instance object email is set to email from method parameter
this.address = address;
}
/*get and set*/
public void setEmail(String email){
this.email=email; //explicit setter
}
public String getEmail(){
return this.email;
}
public static void main(String[] args) {
ArrayList<Company> comp = new ArrayList<Company>();
comp.add(new Company("Tom", 23)); //will work, because I let your constructor
comp.add(new Company("John", 43));
comp.add(new Company("Charles", 25));
Company compToAdd= new Company("preparedFoo",22);
compToAdd.setEmail("fooomail"); //will work because setter
comp.add(compToAdd);
comp.add(new Company("FooName", 30,"fooMail","FooAddress")); //will work because new constructor
}
}

How do i store a whole void method in array variable

public void body()
String name = "", address = "",checkin = "", checkout = "";
InputStreamReader read = new InputStreamReader(System.in);
BufferedReader in = new BufferedReader(read);
for(k =1;;k++)
{
}
I need to store whole method in a array variable at once.
well actually for every loop i want to create a element in array.
Like chrylis said in his comment you could create a class Reservation with the fields you want to store.
public class Reservation {
private String name;
private String address;
private String checkin;
private String checkout;
public Reservation(String name, String address, String checkin, String checkout) {
this.name = name;
this.address = address;
this.checkin = checkin;
this.checkout = checkout;
}
//getters and setters ...
}
Then you can create a new Object of it in your method and add it to your array
ArrayList<Reservation> reservations = new ArrayList<>();
for(k =1;;k++) {
reservations.add(new Reservation(...));
}
I used an ArrayList instead of an Array because you can add as many elements as you want to an ArrayList

Java calling value from a method

first of all sorry for my english it is not perfect.
I got a little problem (for me a huge problem) in java.
package test;
import java.util.Scanner;
public class adress {
String adress;
String city;
int postcode;
String ergebnis;
public void setadress(String adress)
{
this.adress = adress;
}
public String getadress()
{
return adress;
}
public void setcity(String city)
{
this.city = city;
}
public String getcity()
{
return city;
}
public void setpostcode(int postcode)
{
this.postcode = postcode;
}
public int getpostcode()
{
return postcode;
}
public void output (String adress, String city, int postcode) {
Scanner a = new Scanner (System.in);
System.out.println("How much values?");
int b = a.nextInt();
int [] c = new int [b];
for (int i=0; i<c.length; i++) {
Scanner input = new Scanner (System.in);
System.out.println("Adress?");
String temp = input.nextLine();
setadresse(temp);
Scanner input3 = new Scanner (System.in);
System.out.println("City?");
String temp2 = input3.nextLine();
setcity(temp2);
Scanner input4 = new Scanner (System.in);
System.out.println("Postcode?");
int temp3 = input4.nextInt();
setpostcode(temp3);
this.adress = adress;
this.city = city;
this.postcode = postcode;
System.out.println("Adress: "+adress+"City"+city+"postcode"+postcode);
}
}
}
Now, i want to save the values in a new class in a array
package test;
public class save {
adress [] saver = new adress[10];
public adressenpool (String adress, String city, int postcode){
for(int i =0; i<10;i++)
saver[i] = ????? ; //i have tried several things here, but it will not work. i know it is just a little problem but i can't get it the mistake
}
}
}
How can i get the values from address class an copy it as an array in the saver class?
It looks like you are attempting to put 10 objects of class address in an object of class save, as opposed to just the information within address. This is generally a good idea so I encourage you to continue.
In order to create the address within method adressenpool you need to use its constructor. At present class address only had a default constructor, which creates an effectively empty address. I would add a new constructor that fully creates the object
public class adress {
String adress;
String city;
int postcode;
String ergebnis;
public adress(String adress, String city, int postcode, String ergebnis){
this.adress=address;
this.city=city;
this.postcode=postcode;
this.ergebnis=ergebnis;
}
//you can have several constructors so you can keep the empty constructor if you want to set the elements piece by piece
public adress(){
}
......
other methods as before
}
Having added the constructor you can now make addresses easily
public adressenpool (String adress, String city, int postcode,String ergebnis){
saver[0] = new adress(adress, city, postcode,ergebnis);
}
However, your method adressenpool only contains enough information to create 1 adress. You may wish to set which index to save it at. Or you may want to change from an array to an arraylist so you can just add new adress as you go.
public adressenpool (String adress, String city, int postcode,String ergebnis, int index){
saver[index] = new adress(adress, city, postcode,ergebnis);
}
Notes
Classes always start with an uppercase letter. Objects with
lowercase. So it should be class Save and class Address
For loops (and if statements) without braces are considered a dangerous thing to do. Always include {} with your loops even if it contains a single statement. So
for(int i =0; i<10;i++){
saver[i] new Adress(adress, city, postcode,ergebnis);
}
I think you should be more specific of what you want to do exactly.
Your first class has 4 members (3 String and 1 int) and you want to save the values from address class as an array in the saver class? What do you mean by the last one?
I am guessing you need to fill each address instance in the array you define (saver) by calling the appropriate setters. (You haven't defined setadresse() by the way). This can be done in a loop for example.
Also this is not very straight forward: //i have tried several things here, but it will not work. What have you tried and did not work?
Of course you need a main() function also to run your program.
I hope that helped a bit...
This will solve the issue
package temp;
import java.util.Scanner;
public class adress {
String adress;
String city;
int postcode;
String ergebnis;
public void setadress(String adress)
{
this.adress = adress;
}
public String getadress()
{
return adress;
}
public void setcity(String city)
{
this.city = city;
}
public String getcity()
{
return city;
}
public void setpostcode(int postcode)
{
this.postcode = postcode;
}
public int getpostcode()
{
return postcode;
}
public void setAddress () {
Scanner input = new Scanner (System.in);
System.out.println("Adress?");
String temp = input.nextLine();
setadress(temp);
Scanner input3 = new Scanner (System.in);
System.out.println("City?");
String temp2 = input3.nextLine();
setcity(temp2);
Scanner input4 = new Scanner (System.in);
System.out.println("Postcode?");
int temp3 = input4.nextInt();
setpostcode(temp3);
}
#Override
public String toString() {
// TODO Auto-generated method stub
return "Adress: "+adress+"City"+city+"postcode"+postcode;
}
}
And the second class
package temp;
import java.util.Scanner;
public class save {
adress [] saver;
public save(){
saver = new adress[10];
}
public void adressenpool(){
Scanner a = new Scanner (System.in);
System.out.println("How much values?");
int b = a.nextInt();
adress address1 = null;
for (int i=0; i<b; i++) {
address1 = new adress();
address1.setAddress();
this.saver[i] = address1;
}
}
public static void main(String[] args) {
save saveTemp = new save();
saveTemp.adressenpool();
for(int i=0; i<2; i++){
System.out.println(saveTemp.saver[i].toString());
}
}
}

Java Constructor

Good day!
I created overloading constructors as follows:
public ContactsBean(String firstName, String lastName,
String telNumber, String email) {
this.id = count;
count = count + 1;
this.firstName = firstName;
this.lastName = lastName;
this.email = email;
this.telNumber = telNumber;
}
public ContactsBean() {
this.id = count;
count = count + 1;
}
I want to auto-increment the id so i used this variables:
private static int count;
private int id;
My problem is, when I instantiate the ContactsBean() contacts = new ContactsBean(), the value of id is incremented by 2..
2,4,6,8... etc.
Why? How can I do the auto number of ID increment by 1?
Thank you.
EDIT:
Action:
private ContactsBean contacts = new ContactsBean();
private ContactsManager contactsManager = new ContactsManager();
public String add() {
contactsManager.addContacts(contacts);
return SUCCESS;
}
Manager:
private ContactsDAO contactsDAO = ContactsDAO.getInstance();
private List<ContactsBean> contactsList = contactsDAO.getContactsList();
public void addContacts(ContactsBean contact) {
contactsList.add(contact);
}
First, DRY (do not repeat yourself), would be better:
public ContactsBean(String firstName, String lastName,
String telNumber, String email){
this();
this.firstName = firstName;
this.lastName = lastName;
this.email = email;
this.telNumber = telNumber;
}
Second, there is no increment by two in your code. Please paste in your test code.
Try removing the first set of parentheses from
ContactsBean() contacts = new ContactsBean();.
That is, try this constructor:
ContactsBean contacts = new ContactsBean();
I think you are creating two objects of ContactsBean in your other classes may be you are unaware of it. You have to check the code.
Have you tried debugging your code setting a breakpoint on both constructors?
The suggestion of Eng. Fouad is a good tip but it's not gonna solve your problem.
Also note that your counter is not thread-safe (the problem has nothing to do with it, though. In that case your counter would have a lower value than it should)
And if you really need to keep track on how many objects you actually create, I don't think the best way to do this is with a static attribute in a Java Bean...
It might be due to the copy constructor calling the no-arg version of your contstructor.
(Or am I suffering from C++ sickness?)
My suggestion would be to not try to increment the contactID in the contructor, but either get it from the newly created database object where the ID is being incremented by databse via identity specification, or since you are getting the list of contacts base your next id off of contactsDAO.getContactsList().size()+1.
I'd also recommend changing from:
private ContactsDAO contactsDAO = ContactsDAO.getInstance();
private List<ContactsBean> contactsList = contactsDAO.getContactsList();
public void addContacts(ContactsBean contact) {
contactsList.add(contact);
}
To something like:
private ContactsDAO contactsDAO = ContactsDAO.getInstance();
private List<ContactsBean> contactsList;
public void addContacts(ContactsBean contact) {
int id = getContactList().size()+1;
contact.setId(id);
contactsList.add(contact);
}
public List<ContactsBean> getContactList(){
return contactsDAO.getContactsList();
}
alternatively if you are able to remove contacts from the database, this number might not be accurate for the ID. You could create a query based on such as:
select MAX(ID) from contacts
This will return the largest id number used.
private static int count = 0;
private int id;
// ...
public ContactsBean(String firstName, String lastName,String telNumber, String email)
{
this();
this.firstName = firstName;
this.lastName = lastName;
this.email = email;
this.telNumber = telNumber;
}
public ContactsBean()
{
id = ++count;
}
I learned that Struts2 generates the instance of an object(beans) automatically in the Action Classes so no need to instantiate it....
My code before is
private ContactsBean contacts = new ContactsBean();
private ContactsManager contactsManager = new ContactsManager();
public String add() {
contactsManager.addContacts(contacts);
return SUCCESS;
}
//getters and setters
I changed it to..
private ContactsBean contacts;
private ContactsManager contactsManager = new ContactsManager();
public String add() {
contactsManager.addContacts(contacts);
return SUCCESS;
}
//getters and setters
And it works...

Categories

Resources