Using multiple classes java - java

I would like to know how to use multiples clas in Java. I know how use method from other class and also constructors but i would like know how create a new "object" for example. If i am making a PersonDirectory, then i can have class called Person which has the attributes Name and Age. Then i want to make a Person[] in my PersonDirectory Class and add names and ages to it. How can i do that? I have some code that i did, but it doesn't seem to work out.
import java.io.*;
public class PersonDirectory {
static BufferedReader br = new BufferedReader
(new InputStreamReader(System.in));
static Person[] personArray = new Person[2];
public static void main(String[] args) throws IOException{
for (int i = 0; i < personArray.length; i++) {
System.out.print("Please enter the name of the person: ");
String name = br.readLine();
System.out.print("Please enter the age of the person: ");
int age = Integer.parseInt(br.readLine());
personArray[i] = new Person(name,age);
}
for(Person p : personArray) {
System.out.println("The name is "+p.getName()+" and the age is "+p.getAge());
}
}
}
second class
public class Person {
private static String name = "";
private static int age = 0;
public Person(String name,int age) {
this.name = name;
this.age = age;
}
public static String getName() {
return name;
}
public static int getAge() {
return age;
}
}

This is because the properties in the Person class are static. Static means that they are shared between all object(instances). Remove the static keyword from the Person class and you will be fine.

Related

How can we create an instance for a nested class in array of objects in java?

import java.util.Arrays;
import java.util.Scanner;
public class employee{
public String name;
public class employee_address{
String street_name;
String city;
String zipcode;
String state;
String country;
}
public static void main(String []args){
Scanner user_input = new Scanner(System.in);
int no_of_employees = user_input.nextInt();
employee[] employees_list = new employee[no_of_employees];
for(int i = 0;i < no_of_employees;i++){
employees_list[i].name = user_input.nextLine();
employees_list[I].employee_address = // this is it ?
}
}
}
In the code above I do understand that the employee_address is a class and can't be accessed
directly without an instance being created like in the code, that makes no sense. but how can I create an instance of the employee_address class that is associate with each employee.
like in the code above 'employee_address' is associated with every employee but how can the class 'employee_address' be initialised and how can I set the street_name, city and the rest of the members in the address class. any ideas would be appreciated.
You can't directly create an instance of inner class, the reason because since it is the property of another instance we always need to use it though the instance of parent variable.
Let's say you have a class, which have two propeties:
public class Employee {
public String name;
public EmployeeAddress emAddress;
}
to access emAddress you need to use through the instance of Employee class, for example -
Employee object = new Employee();
EmployeeAddress empAdd = object.new EmployeeAddress();
Full code:
public class Employee {
public String name;
public EmployeeAddress emAddress;
public class EmployeeAddress {
String street_name;
String city;
String zipcode;
String state;
String country;
public String getStreet_name() {
return street_name;
}
public void setStreet_name(String street_name) {
this.street_name = street_name;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getZipcode() {
return zipcode;
}
public void setZipcode(String zipcode) {
this.zipcode = zipcode;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
#Override
public String toString() {
return "EmployeeAddress [street_name=" + street_name + ", city=" + city + ", zipcode=" + zipcode
+ ", state=" + state + ", country=" + country + "]";
}
}
public static void main(String[] args) {
Scanner user_input = new Scanner(System.in);
int no_of_employees = user_input.nextInt(); // let's say no_of_employees = 1
Employee[] employees = new Employee[no_of_employees];
for (int i = 0; i < no_of_employees; i++) {
Employee object = new Employee();
object.setName("Virat Kohli");
EmployeeAddress empAdd = object.new EmployeeAddress();
empAdd.setCity("New Delhi");
empAdd.setCountry("India");
empAdd.setState("Delhi");
empAdd.setStreet_name("Chandni Chalk");
empAdd.setZipcode("741124");
object.setEmAddress(emAddress);
employees[i] = object;
}
System.out.println(employees[0]);
user_input.close();
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public EmployeeAddress getEmAddress() {
return emAddress;
}
#Override
public String toString() {
return "Employee [name=" + name + ", emAddress=" + emAddress + "]";
}
public void setEmAddress(EmployeeAddress emAddress) {
this.emAddress = emAddress;
}
}
I have modified your code to sonar standard.
Below code uses Java naming conventions (which your code does not).
Notes after the code.
import java.util.Scanner;
public class Employee {
private String name;
private EmployeeAddress address;
public class EmployeeAddress {
String streetName;
String city;
String zipcode;
String state;
String country;
}
public static void main(String[] args) {
Scanner userInput = new Scanner(System.in);
int noOfEmployees = userInput.nextInt();
Employee[] employeesList = new Employee[noOfEmployees];
for (int i = 0; i < noOfEmployees; i++) {
employeesList[i] = new Employee();
employeesList[i].name = userInput.nextLine();
EmployeeAddress employeeAddress = employeesList[i].new EmployeeAddress();
employeesList[i].address = employeeAddress;
employeesList[i].address.streetName = userInput.nextLine();
}
}
}
An inner class is a normal class. It is not a member of its enclosing class. If you want class Employee to have an [employee] address, as well as a [employee] name, you need to add another member variable to class Employee whose type is EmployeeAdress.
Employee[] employeesList = new Employee[noOfEmployees];
The above line creates an array but every element in the array is null. Hence you need to first create a Employee object and assign it to an element of the array. Hence the following line in my code, above:
employeesList[i] = new Employee();
Since EmployeeAddress is not a static class, in order to create a new instance, you first need an instance of the enclosing class, i.e. Employee. Hence the following line in the above code.
EmployeeAddress employeeAddress = employeesList[i].new EmployeeAddress();
Since all your code is in class Employee, in method main you can directly access the members of both class Employee and EmployeeAddress. Nonetheless you need to be aware of the different access modifiers in java.
A few hints:
stick to naming conventions: class names in Java start with capital letters
use (class) definitions before using them (collect them at the top if not inconventient)
if you are sure you want to use inner classes, set them static, unless you want them to be entangled in generics.
Usually normal classes in each their own file are a lot more flexible and far easier to use
if you use objects that only carry public data, try to use final keyword and initialize them ASAP
use proper objects first, and after finishing them assign them to arrays. avan better would be the use of ArrayList and the like
if Employee contains EmployeeAddress, it should initialize it if conventient. so an object is always responsible for its own stuff
Use try/resrouce/catch
scanner.nextInt() can be problematic with newline/line breaks. For user input better readLine() and parse input
Code:
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Scanner;
public class Employee {
static public class EmployeeAddress {
public final String street_name;
public final String city;
public final String zipcode;
public final String state;
public final String country;
public EmployeeAddress(final Scanner pScanner, final PrintStream pOutPS) {
street_name = readLine(pScanner, pOutPS, "Please enter Street Name:");
city = readLine(pScanner, pOutPS, "Please enter City Name:");
zipcode = readLine(pScanner, pOutPS, "Please enter Zip Code:");
state = readLine(pScanner, pOutPS, "Please enter State:");
country = readLine(pScanner, pOutPS, "Please enter Country:");
}
}
static public String readLine(final Scanner pScanner, final PrintStream pOutPS, final String pPrompt) {
pOutPS.print(pPrompt);
final String value = pScanner.nextLine();
pOutPS.println();
return value;
}
static public int readInt(final Scanner pScanner, final PrintStream pOutPS, final String pPrompt) {
return Integer.parseInt(readLine(pScanner, pOutPS, pPrompt));
}
public final String name;
public final EmployeeAddress address;
public Employee(final Scanner pScanner, final PrintStream pOutPS) {
name = readLine(pScanner, pOutPS, "Please enter Employee Name: ");
System.out.println("Name: " + name);
address = new EmployeeAddress(pScanner, pOutPS);
}
public static void main(final String[] args) {
try (final Scanner user_input = new Scanner(System.in);
final PrintStream output = System.out;) {
final int no_of_employees = readInt(user_input, output, "Please enter number of users: ");
final Employee[] employees_list = new Employee[no_of_employees]; // either this line
final ArrayList<Employee> employees = new ArrayList<>(); // or this line
for (int i = 0; i < no_of_employees; i++) {
output.println("Creating user #" + (i + 1) + "...");
final Employee newEmployeeWithAddress = new Employee(user_input, output);
employees_list[i] = newEmployeeWithAddress; // either this line
employees.add(newEmployeeWithAddress); // or this line
}
}
}
}

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() ).

adding multiple objects to ArrayList is not printing very well

import java.util.ArrayList;
import java.util.Scanner;
public class Student {
static String studentNum;
static int age;
static String Name;
Student(int Age, String Name){
this.Name = Name;
this.age = Age;
}
public static String input_read() {
Scanner sc = new Scanner(System.in);
if (sc.hasNext()) {
studentNum = sc.next();
} else {
sc.close();
}
return studentNum;
}
public static int setAge() {
System.out.println("Enter the age of the Student");
return Integer.valueOf(input_read());
}
public static String setName() {
System.out.println("Enter the name of the Student");
return input_read();
}
public static int getAge() {
return age;
}
public static String getName() {
return Name;
}
public static void main(String[] args) {
ArrayList<Student> ar = new ArrayList();
for (int i=0; i<2; i++) {
Student s1= new Student(setAge(), setName());
ar.add(s1);
}
for (Student each :ar){
System.out.println(each.getName());
System.out.println(each.getAge());
}
}
}
I am new guy in Java. I created a program to add student age and name. This program output is printing only last object 2 times. It is not printing all the objects in the list. Anybody know why?
You should remove the keyword static from your member variables.
That is causing them to be shared across all instances.
See here: What does the 'static' keyword do in a class?

Creating and Returning a List of Employees in Java

Good evening all. I'm just trying to create a class with a method that allows you to create a list of users, their ages, and their departments (although I haven't coded the department part yet!). I want to be able to return the list of employees SORTED by age. I haven't coded Java in a long while, and I'm a little rusty. Most of my time has been spent in Perl and C++ lately, so any help would be greatly appreciated. Thanks, guys!
Here's my (broken) code:
import java.util.Scanner;
import java.io.*;
import java.util.Arrays;
import java.util.Comparator;
public class Department{
public static void main(String[] args){
Scanner in = new Scanner(System.in);
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("How many employees?\n");
int noOfEmployees = in.nextInt();
String[][] employeeInformation;
employeeInformation = new String[noOfEmployees][3];
for (int row = 0; row < employeeInformation.length; row++){
System.out.print("Enter employee name: ");
try {
employeeInformation[0][row] = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
System.out.print("Enter employee age: ");
try {
employeeInformation[1][row] = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
}
Arrays.sort(employeeInformation, new Comparator<String[]>() {
public int compare(String[] entry1, String[] entry2){
String name = entry1[0];
String age = entry2[0];
return name.compareTo(age);
}
});
for(int i=0;i<employeeInformation.length;i++){
System.out.println(employeeInformation[i][i]);
}
}
}
using your code
employeeInformation[0][row] = br.readLine();
employeeInformation[1][row] = br.readLine();
should be
employeeInformation[row][0] = br.readLine();
employeeInformation[row][1] = br.readLine();
and why are you comparing age with name in your sort
return name.compareTo(age); // this does not make sense.
Sorry to be rough, but try using a debugger or print statements
OK I have some thing for you. I took your class and modified it to make work and make little better. You may still want to make more error checking and other optimizations as you see fit. This is just a working sample.
Code explanation:
I have created a inner class called employee. But feel free to tear that out into a separate class. I just did for convenience sake to post a sample. I hope it helps you.I have tested and it works.
package com.vkg;
import java.util.Arrays;
import java.util.Scanner;
public class Department {
public static void main(String[] args) {
Department department = new Department();
Scanner in = new Scanner(System.in);
System.out.println("How many employees?\n");
int noOfEmployees = in.nextInt();
Employee[] employees = new Employee[noOfEmployees];
for (int i = 0; i < employees.length; i++) {
Employee employee = department.new Employee();
System.out.print("Enter employee name: ");
String employeeName = in.next();
employee.setName(employeeName);
System.out.print("Enter employee age: ");
int age = in.nextInt();
employee.setAge(age);
employees[i] = employee;
}
Arrays.sort(employees);
for (Employee employee : employees) {
System.out.println(employee.getName() + "'s age = " + employee.getAge());
}
}
public class Employee implements Comparable<Employee> {
private String name;
private int age;
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;
}
#Override
public int compareTo(Employee o) {
if(this == o || this.age == o.age) {
return 0;
} else if (this.age < o.age) {
return -1;
} else {
return 1;
}
}
}
}

How to add an integer to my arraylist?

I currently have my code set up so a student's name and subject is added to my arraylist, and then printed when user is done. How ever as I'm not wanting to add a string now, I want to add a student number, i'm unfamiliar with how to go about this. I have tried replacing set with add, and string with int, but to no prevail.
Here is my main code
import java.util.*;
public class StudentData
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
ArrayList<Student> studentList = new ArrayList<Student>();
String yesNo = "true";
do
{
System.out.println("Enter student's name: ");
String name = in.next();
System.out.println("Enter student's subject: ");
String subject = in.next();
System.out.println("Enter student's number: ");
int number = in.nextInt();
Student s = new Student(name,subject,number);
s.setName(name);
s.setSubject(subject);
s.Number.add(number);
studentList.add(s);
do
{
System.out.println("Would you like to enter data for another student? Yes/No ");
yesNo = in.next();
}
while (!yesNo.equalsIgnoreCase("YES") && !yesNo.equalsIgnoreCase("NO"));
}
while (yesNo.equalsIgnoreCase("YES"));
for(int i = 0; i < studentList.size(); i++)
{
System.out.println(studentList.get(i).getName());
System.out.println(studentList.get(i).getSubject());
}
}
}
and
class Student
{
private String studentName;
private String studentSubject;
public Student(String name, String subject, int number )
{
setName(name);
setSubject(subject);
Number.add(number);
}
public String getName()
{
return studentName;
}
public void setName(String name)
{
studentName = name;
}
public String getSubject()
{
return studentSubject;
}
public void setSubject(String subject)
{
studentSubject = subject;
}
public int getNumber()
{
return studentNumber;
}
public void Number.add(int number)
{
studentNumber = number;
}
}
As you are storing Student objects in your list you are also storing the member variables of each object as you entered them. So no different approach needs to be taken to store an integer.
You can declare your private int studentNumber; in your student class, add a getter and a setter for it and then modify your constructor so that setStudentNumber(number); would work in the same way as setting your two Strings up.
Then to iterate through your list you could make use of the 'enhanced-for' syntax instead of a plain old for loop, meaning:
for (Student s : studentList) {
System.out.println(s.getName());
System.out.println(s.getSubject());
System.out.println(s.getStudentNumber());
}
Hope that this helps, if you need anything more just give me a shout below.

Categories

Resources