Passing a comma delimited string into a class [closed] - java

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
Here is what I have so far in my code
public class Person {
public Person()
{
String person = "";
int age = 0;
String city = "";
int sibCount = 0;
// make an instance field for name, city, age, and siblingCount
Person person = new Person();
Person age = new Person();
Person city = new Person();
Person sibCount = new Person();
}
// make a method called parseCommaDelim
public void parseCommaDelim(String[] args){
// return a Person instance UNSURE HERE
}
// make a toString method
public String toString()
{
String str = "person" + person + "age" + age + "city" + city;
return str;
}
}
}
I am trying return a person instance and I am not sure how to do it. I tried 'return Person;' and my code did not like it.
My toString method is not working either because it does not know what person, age, or city is, and I am not sure why.

What you want to achieve is probably something along the following lines:
public class Person {
// fields
private String person = "";
private int age = 0;
private String city = "";
private int sibCount = 0;
// constructor
public Person() {
}
// public access methods (getters)
public String getPerson() {
return this.person;
}
public int getAge() {
return this.age;
}
public String getCity() {
return this.city;
}
public int getSibCount() {
return this.sibCount;
}
// toString
public String toString() {
return "person: " + person + ", age: " + age + ", city: " + city;
// factory method
public static Person parseCommaDelim(String s) {
String[] tokens = s.split(",");
Person instance = new Person();
instance.person = tokens[0];
instance.age = Integer.parseInt(tokens[1];
instance.city = tokens[2];
// ...
return instance;
}
}
The field person should probably renamed to name. Depending wether you want to make your class immutable or not you may want to add either a constructor which takes all parameters as parameters:
public Person(String name, int age, String city, int sibCount) {
this.name = name;
this.age = age;
this.city = city;
this.sibCount = sibCount;
}
or add setters for the changable fields, for example:
public void setCity(String city) {
this.city = city;
}
btw. with above constructor you could modify the factory to the following slightly cleaner code:
public static Person parseCommaDelim(String s) {
String[] tokens = s.split(",");
String person = tokens[0];
int age = Integer.parseInt(tokens[1];
String city = tokens[2];
int sibCount = Integer.parseInt(tokens[3]);
return new Person(person, age, city, sibCount);
}

public class Person {
public String person;
public int age;
public String city;
public int sibCount;
public Person()
{
person = "";
age = 0;
city = "";
sibCount = 0;
}
// make a method called parseCommaDelim
public String parseCommaDelim(String[] args){
// return a Person instance UNSURE HERE
}
// make a toString method
public String toString()
{
String str = "person" + person + "age" + age + "city" + city;
return str;
}
}

Related

Create a class Student with following attributes

I'm trying to learn the array object in Java but don't understand. I did understand how to store input into an array object but fail to understand how to compare each items inside an array to do #7 and #8. I tried to search up on the internet but stuck from there.
Create a class Student with following attributes: Name, Age, Address, Email address
Create an empty constructor that initializes empty values to all the attributes.
Create a constructor that takes all the parameters and initializes all the attributes with it.
Create accessor and mutator methods for all attributes.
Create a toString method to return the details of the student.
Ask the user to enter the details of any 5 students and store them in an array.
Ask the user to enter an address and print all the students who live in that address.
Print all the students whose email address contains “gmail.com”.
import java.util.*;
public class Student{
private String name;
private int age;
private String address;
private String email;
public Student(){}
public Student(String name, int age, String address, String email){
this.name = name;
this.age = age;
this.address = address;
this.email = email;
}
public void setName(String newName){
name = newName;
}
public void setAge(int newAge){
age = newAge;
}
public void setAddress(String newAddress){
address = newAddress;
}
public void setEmail(String newEmail){
email = newEmail;
}
public String getName(){
return name;
}
public int getAge(){
return age;
}
public String getAddress(){
return address;
}
public String getEmail(){
return email;
}
public String toString() {
return "Name: " + name + ", Age: " + age + ", Address: " + address + ", Email: " + email;
}
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
Student[] s= new Student[];5
for(int i = 0; i < 5; i++){
System.out.print("Name: ");
String name = sc.nextLine();
System.out.print("Age: ");
int age = sc.nextInt();
System.out.print("Address: ");
sc.nextLine();
String address = sc.nextLine();
System.out.print("Email: ");
String email = sc.nextLine();
s[i] = new Student(name,age,address,email);
}
for(int i = 0; i < s.size(); i++){
if(s)
}
System.out.println(Arrays.toString(s));
}
}
For 7, use the scanner to retrieve a string from the user, then compare it to each user's address
System.out.print("Please enter an address: ");
String anyAddress = sc.nextLine();
for (int i = 0; i < s.length; i++) {
if (s[i].getAddress().equals(anyAddress))
System.out.println(s[i]);
}
For 8, it's quite the same, iterate on the student (I show there a for-each loop), then verify if "gmail.com"is in their email, if true, then print it
for (Student student : s) {
if (student.getEmail().contains("gmail.com"))
System.out.println(student);
}

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
}
}
}
}

How to write a method that reads particular content in an array lists and count the number of array's content

I am a new learner and I should create a method that will make this program work with no problems at all so I can get the :::final result that should look like this:::
3 is 3
Mark is Mark
Richard is Richard
Here is the code (PLEASE read the comments I wrote in the code)
public class Main {
/*I wrote the following method (Student) but I keep get some issues:
Please help I spend many days and I can't figure it out and I am runnung out
of time as I should understand the problem or at least the correction that I
can read and figure out what I was doing wrong.*/
// My written code starts here
public static String Student(String[] sx){
int counter = 0;
for (int i = 0; i < sx.length; i ++){
if (sx[i] != null) counter ++;
}
return counter;
sx = new String[counter];
}
// My written code ENDS here
// From this point I should preserve the code without any changes
static Student studentA;
static Student studentB;
static Student studentC;
public static void main(String[] args) {
studentA = new Student("Mark", "John", "Jimmy");
studentB = new Student("Will", "George", "Androw");
studentC = new Student("Frank", "Sam");
int totalStudents = Student.getTotalStudents();
System.out.println(totalStudents + " is 3");
System.out.println(studentA.getFirstName() + " is Mark");
studentA.setFirstName("Richard");
System.out.println(studentA.getFirstName() + " is Richard");
}
}
Check the following code snippet
import java.util.List;
public class Main {
// My written code starts here
static class Student {
String firstName;
String middleName;
String lastName;
// Constructor for setting the class variable with all 3 field
public Student(String firstName, String middleName, String lastName) {
this.firstName = firstName;
this.middleName = middleName;
this.lastName = lastName;
}
// Constructor for setting the class variable with 2 field
public Student(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
//to get the FirstName field of a student object
public String getFirstName() {
return firstName;
}
//to set the FirstName field of a student object
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public static int getTotalStudents() {
// this is wrong way of doing this.
// You should ideally send a list Of Student to know the number of students as shown below
return 3;
}
public static int getTotalStudentsFromList(List<Student> studentList) {
return studentList.size();
}
}
// My written code ENDS here
// From this point I should preserve the code without any changes
static Student studentA;
static Student studentB;
static Student studentC;
public static void main(String[] args) {
studentA = new Student("Mark", "John", "Jimmy");
studentB = new Student("Will", "George", "Androw");
studentC = new Student("Frank", "Sam");
int totalStudents = Student.getTotalStudents();
System.out.println(totalStudents + " is 3");
System.out.println(studentA.getFirstName() + " is Mark");
studentA.setFirstName("Richard");
System.out.println(studentA.getFirstName() + " is Richard");
}
}
I have added possible comments to explain the code. Let me know if you feel any difficulty in understanding this.

How to turn my classes (Person, Student. Faculty and Staff) into GUI? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
please teach me how to convert the code into a interface. What should be done is that there is a person class which has a name, address, gender, and phone. then a student, faculty, staff class which inherits the person class. but the student has a course and major, faculty has a rank and research area, and staff has a position and an office
this is my person code
//Person.java
class Person{
private String myName;
private String myAddress;
private char myGender;
private int myPhone;
public Person()
{
myName = "";
myAddress = "";
myGender = 'N';
myPhone = 0;
}
public Person(String name, String address, char gender, int phone){
myName = name;
myAddress = address;
myGender = gender;
myPhone = phone;
}
public String getName(){
return myName;
}
public String getAddress()
{
return myAddress;
}
public char getGender()
{
return myGender;
}
public int getPhone()
{
return myPhone;
}
public void setName(String name)
{
myName = name;
}
public void setAddress(String address)
{
myAddress = address;
}
public void setGender(char gender)
{
myGender = gender;
}
public void setPhone(int phone)
{
myPhone = phone;
}
public String toString()
{
return myName + ", address: " + myAddress + ", gender: " + myGender + ", phone: " + myPhone;
}
}
this is my student code
//Student.java
class Student extends Person
{
private String myCourse;
private String myMajor;
public Student()
{
super();
myCourse = "";
myMajor = "";
}
public Student(String name, String address, char gender, int phone,
String course, String major)
{
super(name, address, gender, phone);
myCourse = course;
myMajor = major;
}
public String getCourse()
{
return myCourse;
}
public String getMajor()
{
return myMajor;
}
public void setCourse(String course)
{
myCourse = course;
}
public void setMajor(String major)
{
myMajor = major;
}
public String toString()
{
return super.toString() + ", course: " + myCourse + ", major: " + myMajor;
}
}
this is my faculty code
//Faculty.java
public class Faculty extends Person
{
private String myRank;
private String myResearch;
public Faculty()
{
super();
myRank = "";
myResearch = "";
}
public Faculty(String name, String address, char gender, int phone, String rank, String research)
{
super(name, address, gender, phone);
myRank = rank;
myResearch = research;
}
public String getRank()
{
return myRank;
}
public String getResearch()
{
return myResearch;
}
public void setRank(String rank)
{
myRank = rank;
}
public void setResearch(String research)
{
myResearch = research;
}
public String toString() {
return super.toString() + ", rank: " + myRank + ", research: " + myResearch;
}
}
this is my staff code
//Staff.java
public class Staff extends Person
{
private String myPosition;
private String myOffice;
public Staff()
{
super();
myPosition = "";
myOffice = "";
}
public Staff(String name, String address, char gender, int phone, String position, String office)
{
super(name, address, gender, phone);
myPosition = position;
myOffice = office;
}
public String getPosition()
{
return myPosition;
}
public String getOffice()
{
return myOffice;
}
public void setPosition(String position)
{
myPosition = position;
}
public void setResearch(String office)
{
myOffice = office;
}
public String toString() {
return super.toString() + ", position: " + myPosition + ", office: " + myOffice;
}
}
enter image description here
please teach me how to convert the code into a interface
Basicly these are just the Models that your application is going to use. You cannot create a user interface having just these Models, but you can make it yourself.
In Java, you have various libraries which help you to create GUI, for example JavaFX or Swing (not really recommended today).
When it comes to the project architecture, what you can use is a design pattern called Model-View-Controller (MVC).
There are also other questions which consider basics of user interfaces in Java, which could help you:
How to create a GUI in Java
or
Create an application GUI by Javafx
And if you are still unsure of which GUI library you should use, see this question:
Java GUI frameworks. What to choose? Swing, SWT, AWT, SwingX, JGoodies, JavaFX, Apache Pivot?

Java - How can I create an array of a different class and iterate through it calling its toString method?

I have a Person class with the fields "name" and "phoneNumber" that are set through the constructor. I am trying to create a separate testing class that will create an array of Person and iterate through them by calling to their toString() method.
I am not sure how to do this, any help is appreciated.
Here is my first class which is all I have so far;
public class Person
{
private String name;
private String phoneNumber;
public Person(String name, String phoneNumber)
{
this.name = name;
this.phoneNumber = phoneNumber;
}
public String getName()
{
return name;
}
public String getNumber()
{
return phoneNumber;
}
public String getPerson()
{
return name + " " + phoneNumber;
}
#Override
public String toString()
{
return "["+getPerson()+"]";
}
}
Hope this will help,
public class Test {
public static void main(String[] args) {
Person array[] = {new Person("Jason", "123456"), new Person("Karl", "78945"), new Person("Tom", "789456")};
for(int i = 0; i < array.length; i++){
array[i].toString();
//System.out.println(array[i].toString());
}
}
}
class Person
{
private String name;
private String phoneNumber;
public Person(String name, String phoneNumber)
{
this.name = name;
this.phoneNumber = phoneNumber;
}
public String getName()
{
return name;
}
public String getNumber()
{
return phoneNumber;
}
public String getPerson()
{
return name + " " + phoneNumber;
}
#Override
public String toString()
{
return "["+getPerson()+"]";
}
}
Save the file as Test.java
Firstly the toString method is for an INDIVIDUAL Person object, and cannot be applied to a whole set, you need to make the method static and have a whole static array defined in the class to be able to go through all instances of the Person class.
private static Person[] pArray = new Person[20];
//I picked 20 randomly, if you want any possible number use an arrayList<Person>
private static int count = 0;
In the constructor
pArray[count] = this;
count++;
Then your toString method:
String list = "[";
for(Person p : this.pArray)
list = list + p.getPerson() + " ,"
list = list + "]";
return list;

Categories

Resources