object java class code - java

These are the instructions for this assignment. Any help would be appreciated. I am a rookie when it comes to java and cant seem to figure this out.
This exercise has two classes. The first class is named ObjectsToArrayList. The second class is called just Objects.
Your responsibility is to create the Object class and figure out how the ObjectsToArrayList class works.
The ObjectsToArraylist class will create an ArrayList of objects. It will ask for and populate the data fields of an Object, then add it to the ArrayList. This can be done for as many instances of the Object that the user wants to enter.
Requirements for the Object Class.
2 data fields: int obj_id, String obj_name.
2 Constructors: No-Arg and one that takes both values and assigns them to the data field.
Gets and sets for both data fields
A toString() method that returns output like:
The object ID is 22 and the name is Andrea
Here's my code
import java.util.*;
/**
*
* #author Student
*/
public class ObjectsToArrayList {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
ArrayList <Object> objectList = new ArrayList();
System.out.println("Please enter information for your favorite object!");
do { // collect an indicator to determine the method to call
Object object = new Object();
System.out.println("Enter a whole number for the ID of your object:\n"
+ "or enter 99 to quit.");
int tmpInt = input.nextInt();
// if 99 is entered exit the loop.
if (tmpInt == 99) {
break;
}
object.setObj_id(tmpInt);
input.nextLine();
// ask for the Object Name
System.out.println("Please enter the name of the Object:");
object.setObj_name(input.nextLine());
objectList.add(object);
} while (true); // this is a contineous loop if the break isn't included.
for(Object object:objectList) {
System.out.println(object.toString());
}
}
}
//****************************************************
//**** Objects Class is below this block **
//****************************************************
class Object {
// enter object code here (This is the part I cannot figure out)
}

Here are examples of constructors:
class Objects{
// This is a constructor with no argument
public Objects(){
}
// This is a constructor with 2 arguments
public Objects(int obj_id, String obj_name){
}
}
You can refer in the link below to learn more about creating constructors and assigning values to fields:
http://docs.oracle.com/javase/tutorial/java/javaOO/constructors.html
Note: Do not use Object as a class because Object is the root of the class hierarchy. Every class has Object as a superclass. All objects, including arrays, implement the methods of this class.
http://docs.oracle.com/javase/8/docs/api/java/lang/Object.html

Try something like this:
public class ObjectsToArrayList {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
ArrayList <Object> objectList = new ArrayList();
System.out.println("Please enter information for your favorite object!");
do { // collect an indicator to determine the method to call
Object object = new Object();
System.out.println("Enter a whole number for the ID of your object:\n"
+ "or enter 99 to quit.");
int tmpInt = input.nextInt();
// if 99 is entered exit the loop.
if (tmpInt == 99) {
break;
}
object.setObj_id(tmpInt);//runs the setObj_id method in the Objects class
//for the users input
input.nextLine();
// ask for the Object Name
System.out.println("Please enter the name of the Object:");
object.setObj_name(input.nextLine());//runs the setObj_name method in the Objects class
//for the users input
objectList.add(object);
} while (true); // this is a contineous loop if the break isn't included.
for(Object object:objectList) {
System.out.println(object.toString());//prints out what the toString method returns in
//the Objects class
}
}
}
//****************************************************
//**** Objects Class is below this block **
//****************************************************
public class Objects
{
//add stuff like methods and instance variables
private int ID;
private String name;
public Objects(){//default constructor
}
public Objects(int i, String n){//constructor to change both ID and name at the same time
ID = i;
name = n;
}
public void setObj_id(int i){//constructor to change only ID
ID = i;
}
public void setObj_name(String n){//constructor to change only name
name = n;
}
public String toString(){
return (name + ": " + ID);
}
}

Ok so you want to create your own object soo have 2 classes rather, personProfile and arrayOfProfiles
So class personDetails object note seperate class file not *not in same file
class personProfile{
private int ID = 0;
private String Name = "";
public personProfile(int id,String name){
ID = id;
Name = name;
}
public int getID(){
return ID;
}
public String getName(){
return name;
}
}
now the other class* different file
class arrayOfProfiles{
personProfile profiles[] = new personProfile[0];
public personProfile[] array(){
return profiles;
}
public void addProfileToArray(personProfile profileObject){
personProfile arrayMod = new personProfile[profiles.length+1];
for(int i = 0;i<profiles.length;i++){
arrayMod[i] = profiles[i];
}
arrayMod[arrayMod.length-1] = profileObject;
}
public static void main(String args[]){
arrayOfProfiles profiles = new arrayOfProfiles();
for(int i = 0;i<5;i++){
int id = Integer.parseInt(JOptionPane.showInputDialog("enter ID ");
String name = JOptionPane.showInputDialog("enter name");
profiles.addProfileToArray(new personProfile(id,name));
}
for(int i =0;i<profiles.array().length;i++){
System.out.println("ID :"+profiles[i].getID()+" name - "+profiles[i].getName());
}
}
}

Related

Two instance variables in the class of a one dimensional array

I'm hoping someone can help me out with a question that I've been stuck on for quite a while.
Just to clarify the scenario. There is a show being held in a theatre that can hold 180 people. They allow online bookings that are written to a text file "bookings.txt" Individual bookings are single that only have a seat, contact and payment status record. Whereas group bookings have seats, a contact number, payment status, group name and group size records.
So far I have created the Bookings and GroupBookings classes. I'll show them below:
/**
*
* #author OP
*/
public class Booking
{
public String seat;
public String contact;
public double cost;
public boolean paid;
//Constructor
public Booking(String st, String ct, int cost, boolean pd)
{
seat = st;
contact = ct;
this.cost = cost;
paid = pd;
}//end of Booking
//Getters
public String getSeat()
{
return seat;
}//end of getSeat
public String getContact()
{
return contact;
}//end of getContact
public boolean isPaid()
{
return paid;
}//end of isPaid
public double getCost()
{
//Determining what discount should be applied to their seat location
if (seat.contains("A") || seat.contains("B") ||
seat.contains("C") || seat.contains("D"))
{
cost = 200;
}
else
{
if (seat.contains("E") || seat.contains("F") ||
seat.contains("G") || seat.contains("H"))
{
cost = 160;
}
else
{
if (seat.contains("I") || seat.contains("J") ||
seat.contains("K") || seat.contains("L"))
{
cost = 120;
}
}
}//end of nested if statement
return cost;
}//end of getCost
#Override
public String toString()
{
return seat + "\t" + "R" + cost + "\t" + paid;
}//end of toString
}//end of class booking
/**
*
* #author OP
*/
public class GroupBooking extends Booking
{
private String groupName;
private int groupSize;
public GroupBooking(String st, String ct, boolean pd, String gn, int gs)
{
//Variables from previous class (using inheritance)
super.seat = st;
super.contact = ct;
super.paid = pd;
//New variables for this class
groupName = gn;
groupSize = gs;
}//end of GroupBooking
#Override
public double getCost()
{
cost = super.getCost();
for (int i = 0; groupSize % 4 > i; i++)
{
cost = cost - 60;
i++;
}//end of for loop
return cost;
}//end of getCost
public int getGroupSize()
{
return groupSize;
}//end of getGroupSize
public String getGroupName()
{
return groupName;
}//end of getGroupName
#Override
public String toString()
{
return seat + "\t" + "R" + cost + "\t" + groupName;
}//end of toString
}//end of class GroupBooking
Now for the question that I am stuck on:
A new class has to be created called BookingManager. From there I have to declare two instance variables in the class of one-dimensional array that can be used to store up to 180 Booking or GroupBooking objects. An integer counter must also be created to keep track of how many Bookings are stored in the array. (These two instance variables should not be accessible from outside the class)
I'm still a newbie in coding and I'm unsure of what to do here. The follow-up question is also giving me difficulties:
A contractor then has to be created to read the information from the text file "bookings.txt". Each line either contains a single Booking or a GroupBooking object. Read each line from the file and instantiate the appropriate type of object (Booking or GroupBooking) and add it to the array. (Note in the case of GroupBooking you must create an object in the array for each member of the group. Exp for a group of six you have to have six separate GroupBooking objects in the array.)
I know a file scanner is needed from the second question but I have no idea whether to use a for loop or an if statement to differentiate between a single booking or a group booking.
If anyone can help I would truly appreciate it. This topic is still very new to me.
To prevent a variable being accessible outside a class declare the variable "private". e.g.
private String costtotal="";
An instance variable "is not" static ("is not" a class member variable), and are a global variable only declared at the top of the class code below the import statements, so exist until the class exits.
In your manager class you need a global variable array Booking class
Booking[] bookings;
private String costtotal=""; // e.g.
// in the constructor read the bookings file and find the number of bookings made
//int totalbooked=...whatever reading the file data counts to of bookings made;
bookings=new Booking[totalbooked];
// create and fill each Booking object and assign it to its index on the array in a loop
bookings[loopcount]=new Booking(st,ct,cost,pd);
Different schemes of class systematics of coding
// bean syntax in a java bean framework class type
public void setCosttotal(String costtotal){
this.costtotal=costtotal;
}
//bean syntax
public String getCosttotal(){
return costtotal;
}
// normal non bean syntax 1
public String costTotal(String csttot){
return (String)csttot;
}
// somewhere else in code in scope to global variable
costtotal=costTotal(valuein);
// normal non bean syntax 2
public String costTotal(String csttot){
costtotal=csttot;
return costtotal;
}

Java - Homework - Using the string value of a variable to name an instance of a class

Okay, so I'm working on a homework assignment where I have a staff of 10 salespeople. We have a contest for the greatest number of sales. The assignment wants the user to enter 10 integer values as a number of sales and then once they've all been entered the salesperson with the highest value will be returned.
What she wants:
A Class "Sales" with (String name and Integer sales) values.
A while loop where the user inputs integers for number of sales
What I'm attempting to do. I assume the names of the salespeople at the company are known, so I just created an array strSalesPerson of 10 fictitious names. I created a counter salespersonCounter to create the counter for the while loop for user input. I'm trying to basically create salesperson1, salesperson2, salesperson3, and so on by creating a variable with the string "salesperson" concatenated with the counter. I want to use that as the name of the instance for each salesperson entered into the Sales Class.
Sales Class
Just for reference, the class I've created and trying to create instances of is as follows:
private String salesname;
private Integer numsales;
public Sales(String name, Integer sales) {
this.salesname = name;
if (sales >= 0.0) {
this.numsales = sales;
}
}
// Setter for name
public void setName(String name) {
this.salesname = name;
}
// Getter for name
public String getName() {
return salesname;
}
// Setter for Sales
public void setSales(Integer sales) {
if (sales >=0) {
this.numsales = sales;
}
}
// Getter for Sales
public int getSales() {
return numsales;
}
} // End of Class
TestSales
This is where I will get the user input and save it as an instance of the Sales class. However, right now I'm just going to use the current instance from the array of names and the static integer 3 to ensure that I get the other pieces functioning correctly and then I'll switch over to user inputs from there.
// Import Scanner
import java.util.Scanner;
public class TestSales {
public static void main(String[] args) {
// create scanner to obtain input from command window
Scanner input = new Scanner(System.in);
// Initialize variables
int salespersonCounter = 1;
// Fill Salesperson names
String[] strSalesPerson = new String[]{"Mark Hasselback","Gary Moore","Shelly Hemingway", "Susan Meagre","Nick Pantillo","Craig Grey","Alice Reese","Mickey Greene","Chaz Ramirez","Kelly Southerland"};
while (salespersonCounter <=10) {
String salespersoninstance = ("salesperson"+ salespersonCounter);
String currsalesperson = strSalesPerson[salespersonCounter -1];
System.out.printf("%s");
Sales salespersoninstance = new Sales(strSalesPerson[salespersonCounter -1],);
System.out.printf("%s is %s!%n",salespersoninstance,currsalesperson);
salespersonCounter += 1;
}
}
}
The problem I am running into is here:
Sales salespersoninstance = new Sales(strSalesPerson[salespersonCounter -1],3);
instead of accepting the string value of salespersoninstance (in this case salesperson1) as the name of the instance of the Sales Class, it is telling me that salespersoninstance is a duplicate local variable. It is interpreting it I guess as me trying to define a new variable with the same name as one I've already declared?
Basically what I want is with the while counter, create a string variable salesperson1, salesperson2, salesperson3 and so on with "salesperson" + salespersonCounter, and use that resulting string to name the instance of the Sales class. That way I can then say Sales salespersoninstance = new Sales(strSalesperson[salespersoncCounter -1], userinput)
To help you a bit forward:
String[] salePersonNames = new String[]{"Mark Hasselback", "Gary Moore", "Shelly Hemingway", "Susan Meagre", "Nick Pantillo", "Craig Grey", "Alice Reese", "Mickey Greene", "Chaz Ramirez", "Kelly Southerland"};
for (int i = 0; i < salePersonNames.length; i++) {
Sales salesPerson = new Sales(salePersonNames[i], 3);
System.out.printf("%s is %s!%n", salesPerson.getName(), salesPerson.getSales());
}

Using an ArrayList to display values from another class

I am trying to make a to do list that asks you to enter your tasks one by one then display them in order (as in 1. task1, 2. task 2, 3. task 3 etc). But when it displays the tasks it comes back as "0. null" one time instead of listing any of the tasks entered. Here is the script I am using:
1st class
package todolist;
import java.util.ArrayList;
public class ToDoList1 {
public static void main(String[] args) {
// TODO Auto-generated method stub
ArrayList<ToDoList2> list = new ArrayList<ToDoList2>();
System.out.println("Time to make a digital to-do list!");
ToDoList2 n = new ToDoList2();
list.add(n);
System.out.println(ToDoList2.name + "'s to-do list");
System.out.println(ToDoList2.i + ". " + ToDoList2.l);
for(ToDoList2 enhanced : list)
{
System.out.println(ToDoList2.i + ". " + ToDoList2.m);
}
}
}
2nd class
package todolist;
import java.util.Scanner;
public class ToDoList2 {
public static String name;
public static int i;
public static String l;
public static String m;
{
Scanner s = new Scanner(System.in);
System.out.println("First type your name to identify your list in case you lose it");
name = s.nextLine();
System.out.println("Make sure to type \"end\" when you are finished");
System.out.println("Type in the first item on your to-do list");
String l = s.nextLine();
}
public ToDoList2()
{
Scanner s = new Scanner(System.in);
for(int i = 1; i == i; i++)
{
System.out.println("Type in the next item for your to-do list");
String m = s.nextLine();
if("end".equals(m))
{
break;
}
}
}
}
Your code is not correct. ToDoList2 scanning item list from standard input but not storing it. You should do as follow
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
class TodoList {
public static String name;
List<String> tasks;
public TodoList(String name) {
this.name = name;
this.tasks = new ArrayList<>();
}
public void addTask(String task) {
this.tasks.add(task);
}
public String toString() {
int i = 1;
StringBuilder stringBuilder = new StringBuilder();
for (String task : tasks) {
stringBuilder.append(i + ". " + task);
stringBuilder.append("\n");
i++;
}
return stringBuilder.toString();
}
}
public class Main {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("First type your name to identify your list in case you lose it");
String name = s.nextLine();
System.out.println("Make sure to type \"end\" when you are finished");
System.out.println("Type in the first item on your to-do list");
TodoList todoList = new TodoList(name);
String task = null;
while (!(task = s.nextLine()).equals("end")) {
todoList.addTask(task);
System.out.println("Type in the next item for your to-do list");
}
System.out.println(todoList);
}
}
a) Given that each ToDoList2 object is a separate task, I'm not sure why you've made the object class members static?
b) In your ToDoList2 constructor, you've got a for loop that introduces a local variable i which hides the ToDoList2 member variable i. You'd do well to change one of the variable names.
c) In your ToDoList2 constructor, you've got a for loop which is assigning a string returned by the Scanner to a local variable m. Are you sure you want m to be a local variable or do you actually want to assign the returned string to the member variable, m? I'm thinking the latter since the member variable m is never being assigned a value which explains why the code is printing out null.
d) When writing code, it is good practice to use meaningful variable names. Using names like i is OK as an index in a loop but in all other circumstances, you should go for something more descriptive that tells the reader what the variable is storing.
e) Consider making all your ToDoList2 member variables private (and final if possible). Add a print function to the ToDoList2 class to print out the task details. A key principle is Object Oriented Programming is to hide the internals of a class.

Is there a way i can add multiple variables to one object?

So I've been given the method below and I'm not allowed to change it. What I need is it to create a couple of objects with the variables below but keeps coming up with an error that says "The constructor menu(int, String, String) is undefined." Am I doing something wrong?
import java.util.Scanner;
import java.util.*;
public class menu {
private static void addNewStudent()
{
Scanner scanner = new Scanner(System.in);
System.out.println("Please enter the correct details below");
System.out.println("ID: ");
int userId = scanner.nextInt();
System.out.println("First name: ");
String userFirst = scanner.next();
System.out.println("Last name: ");
String userLast = scanner.next();
System.out.println("English assignment 1 mark: ");
int english1 = scanner.nextInt();
System.out.println("English assignment 2 mark: ");
int english2 = scanner.nextInt();
System.out.println("English assignment 3 mark: ");
int english3 = scanner.nextInt();
System.out.println("Math assignment 1 mark: ");
int math1 = scanner.nextInt();
System.out.println("Math assignment 2 mark: ");
int math2 = scanner.nextInt();;
System.out.println("Math assignment 3 mark: ");
int math3 = scanner.nextInt();
menu userStudentObj = new menu(userId, userFirst, userLast);
menu userEnglishObj = new menu(english1, english2, english3);
menu userMathObj = new menu(math1, math2, math3);
// Asks the user for the student information (ID, First, Last, Assignments)
// Then creates the appropriate objects and adds the students to the student list
I would expect to have created 3 new object that contain the user input variables within the objects if that makes sense.
The main problem is that you didn't specify any non default constructor, to create objects so compiler have no ideas what do you want to create if object is not specified for that. But there is another problem. Your object is designed in not the best way. So if you want to handle it correctly you could change your class design so you handle it in right way.
For example you could make it a bit different, like in this example (it's not perfect, it still can be more separate and better designed):
class User {
int userId;
String userFirstName;
String userSecondName;
private ArrayList<Integer> mathSums = new ArrayList<>();
private ArrayList<Integer> englishSums = new ArrayList<>();
User(int userId, String userFirstName, String userSecondName) {
this.userId = userId;
this.userFirstName = userFirstName;
this.userSecondName = userSecondName;
}
public void addMathSums(int mathSums) {
this.mathSums.add(mathSums);
}
public void addEnglishSums(int englishSums) {
this.englishSums.add(englishSums);
}
}
So by the help of this class you could change the way, how you define and set the values for your object and it would look like that:
1) You define constructor with arguments so you're able to use it for object creation:
User user = new User(userId, userFirst, userLast);
2) Then you can add sums into ArrayLists that are member variables (fields) in User class:
user.addMathSums(math1);
user.addMathSums(math2);
user.addMathSums(math3);
user.addEnglishSums(english1);
user.addEnglishSums(english2);
user.addEnglishSums(english3);
It could be performed in different ways using arrays, lists or other data structure, but you really need to pay attention for your class design. More time you spend on designing object less modifications you will need later.
3) You probably want to interact with this object so you need to get a reference for it somehow. You could change the method signature so you will "return" created object after you finish your input. So you need to make some changes:
On the method change the signature return type to User:
private static User addNewStudent() { ... }
Then add return for that and return created user:
private static User addNewStudent() {
/* code */
User user = new User(userId, userFirst, userLast);
/* add sums */
return user;
}
4) Use this method in your main():
public static void main(String[] args) {
User createdUser = User.addNewStudent();
}

Java - Calling private arraylist from class [duplicate]

This question already has answers here:
Is it possible in Java to access private fields via reflection [duplicate]
(3 answers)
Closed 7 years ago.
My template opens with a menu of options and the user inputs something between 1-3 to select one of the three options.
When the user chooses option 1, it asks them to input a number teamNumber. One must instantiate the class Team, then it writes it to an arraylist.
If there is at least one number in numberList, the user can select option 2. It asks them to input any of the numbers from the arraylist and searches it. If the number they input is found, then you input a String teamMemberFirstName and a char firstInitialLastName. Then it will write the input to a private arraylist located in another class TeamMember.
Once they have input the info in option 1 and 2, they can choose option 3. It allows you to print the list of inputted names based on which team number you put them on.
I am not sure how, in option 3, to call the private arraylist from the TeamMember class teamList. Any guidance on how to proceed with this step? My code is below.
Main class:
public class Main {
public static void main(String[] args) {
int choosing;
Scanner scan = new Scanner(System.in);
String input;
int teamNumber;
boolean stayInLoop;
ArrayList<Team> numberList = new ArrayList<Team>();
do {
stayInLoop = true;
System.out.println("1. Add a new team");
System.out.println("2. Add a new team member");
System.out.println("3. View teams");
input = scan.nextLine();
if (input.equals("1")) {
System.out.println("Enter a team number:");
teamNumber = scan.nextInt();
scan.nextLine();
Team addTeam = new Team(teamNumber);
numberList.add(addTeam);
}
if (input.equals("2")){
boolean foundIt = false;
boolean valid = true;
System.out.println("Team number:");
teamNumber = scan.nextInt();
scan.nextLine();
for (int a = 0; a < numberList.size() && foundIt == false; a++){
Team addTeam = numberList.get(a);
if (addTeam.findTeam() == teamNumber) {
foundIt = true;
System.out.println("Enter first name of team member:");
String teamMemberFirstName = scan.nextLine();
System.out.println("Enter first initial of last name:");
char firstInitialLastName = scan.nextLine().charAt(0);
TeamMember inputTeamMember = new TeamMember(teamMemberFirstName, firstInitialLastName);
inputTeamMember.addMember(inputTeamMember, valid = true);
System.out.println("Success!");
}
}
if (foundIt == false) {
System.out.println("Try again.");
}
}
if (input.equals("3")){
for (int a = 0; a < numberList.size(); a++) {
Team addTeam = numberList.get(a);
//Not sure what to put where there are ????'s - I tried a few ideas and stuff I found online, but nothing worked
//I assume I call the method/class here????
System.out.println("Team: " + addTeam.findTeam() + " Members: " +
"I will put the member called from the arraylist here????");
}
}
}while (stayInLoop == true;)
}}
TeamMember class:
public class TeamMember {
private final String teamMemberFirstName;
private final char firstInitialLastName;
private ArrayList<TeamMember> teamList = new ArrayList<>();
public TeamMember(String teamMemberFirstName, char firstInitialLastName) {
this.teamMemberFirstName = teamMemberFirstName;
this.firstInitialLastName = firstInitialLastName;
}
public int addMember(TeamMember member, boolean valid) {
valid = teamList.add(member);
return teamList.size();
}
}
You cannot directly access private fields from other classes. Either move your list to the Team class or create a getter to retrieve the list.
In a public class, you can return a private object in a public method. This seems like the easiest way in this project. Add a new method to your TeamMember class, and have it return teamList:
//inside your TeamMember class, anywhere after you assign the private variable
public static ArrayList show(){
//the static keyword, in short, will make the method callable without a class instance.
return teamList;
}
Since the TeamMember method show() is now static, you should be able to simply call TeamMember.show() and get the ArrayList.
Important note: In order for this to work, you must make the private arraylist static too. A static object cannot call a non-static object.
This will turn it into private static ArrayList<TeamMember> teamList = new ArrayList<>();
In the Main class, like I said above, simply call TeamMember.show(). You do not need to create an instance.
If you change your teamList to public instead of private your Main class will be able to access the variable. When you make something private in Java you're basically making that instance variable accessible only through the class that it's instantiated in. If you want the variable to be visible to other classes for reference you should make it public
Since the assignment calls for it, you're going to need to define a getter and setter for your 'teamList' variable.
public void setArray(ArrayList newTeamList){
teamList = newTeamList;
}
public ArrayList getArray(){
return teamList;
}
This'll allow you to access the private variable through the methods

Categories

Resources