Print ArrayList from another Class - java

Evening everyone,
I am writing a code to allow students to search for internships. I have a class for Semesters, a class for Students(where student input is taken and stored into an ArrayList and the actual iSearch class. My code is basically doing everything I need it to do, except I have hit a brain block in trying to figure out the best way to output my ArrayList from the Student class out at the end of my program in the iSearch Class.
I am fairly new to Java, so if I haven't explained this correctly please let me know. I am trying to get the ArrayList's of student information to output at the end of the while loop in the iSearch Class.....so
To make this easy. Is it possible to print an Arraylist from another class.

A better way to solve this is to create a Student object for each student. In your current class the ArrayLists you are creating are deleted after every method call, since it is not referenced anymore.
Here is how I would do it:
Student Class:
public class Student {
String firstName;
String lastName;
String interest;
public Student(String firstName, String lastName, String interest) {
this.firstName = firstName;
this.lastName = lastName;
this.interest = interest;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public String getInterest() {
return interest;
}
}
In your iSearch class you create an ArrayList of students, which lets you add your students:
ArrayList<Student> students = new ArrayList<Student>();
do {
String firstName = input.next();
String lastName = input.next();
String interest = input.next();
students.add(new Student(firstName, lastName, interest));
} while (YOUR_CONDITION);
Then you can display each student by iterating through the ArrayList and accessing the getter and setter methods:
students.foreach(student -> {
System.out.println(student.getFirstName());
System.out.println(student.getLastName());
System.out.println(student.getInterest());
});
Editing this a little will help you to solve your problem, but this is the basic solution.

Related

How to access an array and assign data to each object in Java?

Problem:
I'm trying to figure out how to access the Student Array class in order to create four entries for each Student object, but I'm not sure how to do so, while also allowing the program to create more than just one Student.
public class ClassRoster<T> {
public static void main(String[]args) {
ClassRoster<Student> classroster = new ClassRoster<Student>();
Scanner keyboard = new Scanner(System.in);
System.out.println("Add/Drop/Search?");
String action = keyboard.nextLine();
boolean done = false;
Object temp, c, d, e;
int fresh, soph, jun, sen;
Student test = new Student();
while(!done) {
if(action.equalsIgnoreCase("Add"))
{
int counter = 0;
System.out.print("Enter Student ID");
temp = test.setID(keyboard.nextInt());
System.out.println("First name?");
c = test.setFirstName(keyboard.nextLine());
System.out.println("Last name?");
d = test.setLastName(keyboard.nextLine());
System.out.println("Academic Level?");
e = test.setLevel(keyboard.nextLine());
...
}
And I have another class called Student, where there are four different data entries (ID, FirstName, LastName, Academic Level).
I'm not sure how to access the object which I have created in the correct way. It just gives me an error in this Driver class, and I don't know how to correctly access the array bag.
but I'm not sure how to do so while also allowing the program to create more than just one Student
Currently you are only creating one specific instance of student with Student test = new Student(); To actually create more than one student, you will have to iterate the whole process of reading all four data entries (ID, FirstName, LastName, Academic Level). Instead of having to initialize the fields (your four data entries) with specific set methods, I would recommend you letting the Student class initialize them with the class constructor. Meaning the Student class should look something like this:
public class Student{
private final int ID;
private final String firstname;
private final String lastname;
private String level;
public Student(int ID, String firstname, String lastname, String level){
this.ID = ID;
this.firstname = firstname;
this.lastname = lastname;
this.level = level;
}
ID, firstname and lastname are set to final as you foresee them not to change. However the academic level is ought to change and therefore is not set to final. Now that you have set up a constructor for your Student class, we can get to how to allow the program to insert multiple students at once.
public static void main(String[]args) {
ClassRoster<Student> classroster = new ClassRoster<Student>();
Scanner keyboard = new Scanner(System.in);
System.out.println("Add/Drop/Search?");
String action = keyboard.nextLine();
boolean done = false;
while(!done) {
if(action.equalsIgnoreCase("Add")) {
System.out.print("Enter Student ID");
int ID = keyboard.nextInt();
System.out.println("First name?");
String firstname = keyboard.nextLine();
System.out.println("Last name?");
String lastname = keyboard.nextLine();
System.out.println("Academic Level?");
String level = keyboard.nextLine();
Student student = new Student(ID, firstname, lastname, level);
//we have now created a new instance of Student, now we have to save it in your classroster
classroster.add(student);
}
System.out.println("Next action?");
action = keyboard.nextLine();
if(action.equals("done") done = true; //if you write 'done', your loop will finish executing
}
I don't know about your implementation of classroster, but I assume you have implemented it with some kind of list or map, which is why I call the add(Student s) method after creating an instance of Student. To actually then access all students, you will have to implement a method in classroster that returns the saved list of classroster and then iterate through the returned list in the main loop. To actually see what the students look like, you will also have to implement methods for the student instances to for example print out their full names.
I see that you are having a little trouble with arrays, maps and lists as you don't know how to access your students yet. I recommend you reading up on the difference between these three data structure types and simply try to implement them in a small example to see how they work.

How to reconstruct a name with a split String in Java?

First some info about my project,
I'm following a tutorial task where the main goal is to learn to work with error handling,
but I'm not at that part quite yet, I am working with establishing the main classes.
Thats what I need a little help and guidance with,(but errors are supposed to come up and be detected
so that I can learn to fix them later, but that's not the main question here, just information.)
Here's 3 of the classes which I've completed.
Student with two private fields: Name name and CourseCollection course.
Name with two fields String firstName and String surname.
CourseCollection with ArrayList courses.
(Info: Later, I will work with class UserDatabase to collect and load a collection of students,
+ class DatavaseFormatException which will represent errors, but I think it would be easier to finish those 3 classes above first? Correct me if
I'm wrong.)
QUESTION:I need a little help with class Name, I don't think my work is correct.
My main issue is with the method String encode, and constructor Name(String encodedIdentity)
where I want to return the names, split by a ;. Here's what I have
enter code here
public class Name
//instanciating the persons first and last name as Strings.
private String firstName;
private String surname;
/**
* Constructor for objects of class Name- setting the text values for a name
*/
public Name(String firstName, String surname)
{
firstName = this.firstName;
surname = this.surname;
}
/**
* Constructor for objects of class Name- reconstructing the fields
* from a coded name
*/
public Name(String encodedIdentity)
{
//Here, the name is supposed to be coded as a text value, with the first
//and last names split with a ;
this.encodedIdentity=encodedIdentity;
//I am getting my first error here
}
//getters for firstname and surname here
/**
* This method will return the name, with the first and last name split
* by a ;
*/
public String encode()
{
//Could I use a split String here? If so how?
return firstName + ";" + surname;
}
}
I can guarantee I will need further help with my work. Thanks in advance, I find
people on StackOverflow to be very helpful as I don't have anyone (other than my books)
to ask for help. (I know you guys are not free teachers. But if anyone would voulenteer to help me outside of this I would highly appreciate it.
(Sorry if that's not allowed to ask for!))
EDIT: Thanks to you guys, my class is now compiling. I am not sure how to test it yet, but this is what I have now. Does it look correct?
public class Name
{
/**
* Constructor for objects of class Name- setting the text values for a name
*/
public Name(String firstName, String surname)
{
this.firstName = firstName;
this.surname = surname;
}
/**
* Constructor for objects of class Name- reconstructing the fields
* from a coded name
*/
public Name(String encodedIdentity)
{
String names = firstName + surname;
String[] fullname = names.split( "\\;");
if(fullname.length != 2 )
{
System.out.println(fullname);
}
}
/**
* Getting the firstname of the person
* #return firstName
*/
public String getFirstName()
{
return firstName;
}
/**
* Getting the surname of the person
* #return surname
*/
public String getSurname()
{
return surname;
}
/**
* This method will return the name, with the first and last name split
* by a ;
*/
public String encode()
{
String encode = (firstName + ";" + surname);
return encode;
}
}
If you are given an "encoded id", split it to get the names:
public Name(String encodedIdentity){
String[] names = split( ";", encodedIdentity );
if( names.length != 2 ) throw new IllegalArgumentError("...");
firstName = names[0];
surname = names[1];
}
One does not store all the variants with which an object's attributes may be specified. Therefore, there shouldn't be a field encodedIdentity.
First correct your name constructor with two fields
replace this
public Name(String firstName, String surname)
{
firstName = this.firstName;
surname = this.surname;
}
with
public Name(String firstName, String surname)
{
this.firstName = firstName;
this.surname = surname;
}
Also, can you paste the error from console here. so that it will be easier to find the exact problem.

Link ArrayLists and save data on file

I am working on a Java app for a school project where we have to enter user information: Name, Student ID and their points. How can I store all the data for each user on an ArrayList (or an Array or really whatever type) so I can keep track of all the data.
Example:
John Doe - 401712 - 20 points
Jack Young - 664611 - 30 points
The I want to be able to call methods like setPoints to change the point values for whatever the student selected is.
Here's the problem: How can I link the ArrayList together. If I have three ArrayLists, how does Java know what name, student id and points are associated together?
All the ArrayLists are stored in a class called Data.
Data data = new Data();
Also, all the ArrayLists in the Data class should be outputted to a file which will be loaded next time the app is opened.
I will try to answer any questions.
You need to define a class which contain 3 data fields as follows
Name
Student ID
their points
But not to forget, the class has to have other necessary elements of a class like:
Constructor
Overloaded Constructors if they are necessary
Accessors
Mutators
Note: For accessing each part of an object in your arrayList, you can use accessors. For manipulating each part of an object in your arrayList, you can use mustators.
After having such a class, you can define a arrayList that contain elements with type of class you have already define
Like:
List<Your Type of class > students = new ArrayList<Your Type of class>;
After Java 7, you can do
List<Your Type of class > students = new ArrayList<>;
which is diamond inference.
If you are looking for a specific id number in your arrayList, you can do something like:
public boolean findIdNumber(int idNumber){
for(int i=0; i< students.size; i++)
if(students.get(i).getID() == idNumber)
return true;
else
return false;
}
Warning:
what I have done are suggestions for you to be able to look for what you want smoother. You need to do necessary changes in order to comply what you were
asked to do
You need to create a class named Student, and then declare an array/ArrayList of the Student type. Your Student class must have a constructor that sets the fields of an instance of the Student class (the created instance is now called an object).
So first create a Student class in the same package in which your other class is (the class in which your main method is):
public class Student {
private String firstName;
private String lastName;
private String studentId;
private int points;
public Student(String firstName, String lastName, String studentId, int points) {
this.firstName = firstName;
this.lastName = lastName;
this.studentId = studentId;
this.points = points;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public int getPoints() {
return points;
}
public void setPoints(int points) {
this.points = points;
}
}
Then in your main method or wherever you like, create a Hashmap to hold your Student objects. A map/hashmap is a collection just like an ArrayList to hold a set of objects. In your use case, it is better to use a hashmap because finding/retrieving a specific student object is much faster and easier when you use a hashmap.
import java.util.HashMap;
import java.util.Map;
public class Main {
public static void main(String[] args) {
// a map is a "key-value" store which helps you search items quickly
// (by only one lookup)
// here you consider a unique value of each object as its 'key' in the map,
// and you store the whole object as the value for that key.
// that is why we defined Student as the second type in the following
// HashMap, it is the type of the "value" we are going to store
// in each entry of this map.
Map<String, Student> students = new HashMap<String, Student>();
Student john = new Student("John", "Doe", "401712", 20);
Student jack = new Student("Jack", "Young", "664611", 30);
students.put("401712", john);
students.put("664611", jack);
Student johnRetrieved = students.get("401712");
// each hashmap has a get() method that retrieves the object with this
// specific "key".
// The following line retrieves the student object with the key "664611".
Student jackRetrieved = students.get("664611");
// set/overwrite the points "field" of this specific student "object" to 40
johnRetrieved.setPoints(40);
int johnsPoints = johnRetrieved.getPoints();
// the value of johnsPoints "local variable" should now be 40
}
}
The classical object-oriented approach would be to create a Student class including name, ID and points and storing list of Student objects in a single ArrayList.
class Student{
private String id;
private String name;
private int points;
public Student(String id, String, name, int points){
this.id = id;
this.name = name;
this.points = points;
}
}
..
ArrayList<Student> students = new ArrayList<Student>();
students.add(new Student(1, 'John Doe', 1000));
String id = students.get(0).id;

Integer.toString(argument) or toString(argument)

I've written up some code for a Credit card class, pasted below. I have a constructor that takes in the said variables, and am working on some methods to format these variable's into strings such that the end output will be something along the lines of
Number: 1234 5678 9012 3456
Expiration date: 10/14
Account holder: Bob Jones
Is valid: true
(Won't format correctly - I'm unsure how to do it, would be greatful of someone can edit for me :) )
My question is, in the line
String shortYear = Integer.toString(expiryYear).substring(2,4);
Why won't the following work:
toString(argument).substring(2,4)
I would have imagined it wound have worked (expiryYear is essentially declared as an instance variable of type int). I've consulted my book (The official Java Tutorial also found online), and can't seem to find anything. I didn't even know about Integer.toString, a friend told me about that after trying to play with toString(), so it would be even more greatly appreciated if someone could also tell me where I can find these sorts of methods (I don't think they're in my book)
public class CreditCard {
private int expiryMonth;
private int expiryYear;
private String firstName;
private String lastName;
private String ccNumber;
public CreditCard(int expiryMonth, int expiryYear, String firstName, String lastName, String ccNumber) {
this.expiryMonth = expiryMonth;
this.expiryYear = expiryYear;
this.firstName = firstName;
this.lastName = lastName;
this.ccNumber = ccNumber;
}
public String formatExpiryDate() {
String shortYear = Integer.toString(expiryYear).substring(2, 4);
String expiryDate = expiryMonth + "/" + shortYear;
return expiryDate;
}
public static void main(String[] args) {
CreditCard cc1 = new CreditCard(10, 2014, "Bob", "Jones", "1234567890123456");
System.out.print(cc1.formatExpiryDate());
}
}
Try String.valueOf(expiryYear).substring(2,4)

Creating objects from data entered by user

I'm working on a homework project that requires me to create an object from data entered by a user. I have a class called Person which takes the basic information, a class called Customer which extends the Person class and includes a customer number and a class called Employee which extends the Person class and returns a social security number.
I have pasted the code from my main program below. I'm a little confused on a couple of things. First when I'm collecting the information (first name, last name etc) amd I supposed to be accessing my Person class in there somehow?
Second I guess more plainly, how do I create the object? so far in all of the examples I have read online I find they seem to enter the information already like if I were to have it say
Person firstName = new Person(Jack);
Although I am collecting the information from the user so I don't see how to tell it like
Person firstName = new Person (enter info from user here);
Finally and again this is a really dumb question but I have to create a static method that accepts a Person object.
To create the static method I'm assuming it is
Public Static print()
but how do I tell it to print something from the person class? how does it know?
Most of my examples in the book include a class that contains all of the information instead of making the user enter it which is confusing because now I'm being told the user has the freedom to type what they want and I need to collect that information.
import java.util.Scanner;
public class PersonApp
{
public static void main(String[] args)
{
//welcome user to person tester
System.out.println("Welcome to the Person Tester Application");
System.out.println();
Scanner in = new Scanner(System.in);
//set choice to y
String choice = "y";
while (choice.equalsIgnoreCase("y"))
{
//prompt user to enter customer or employee
System.out.println("Create customer or employee (c/e): ");
String input = in.nextLine();
if (input.equalsIgnoreCase("c"))
{
String firstName = Validator.getString(in, "Enter first name: ");
String lastName = Validator.getString(in, "Enter last name: ");
String email = Validator.getEmail(in, "Enter email address: ");
String custNumber = Validator.getString(in, "Customer number: ");
}
else if(input.equalsIgnoreCase("e"))
{
String firstName = Validator.getString(in, "Enter first name: ");
String lastName = Validator.getString(in, "Enter last name: ");
String email = Validator.getEmail(in, "Enter email address: ");
int empSoc = Validator.getInt(in, "Social security number: ");
}
}
System.out.println("Continue? y/n: ");
choice = in.next();
}
}
First, I observe that there isn't a Person object. I assume you'll get around to creating that, so I'm not going to concern myself too much with it.
Insofar as actually getting the data, you're halfway there. Depending on how you want to frame the Person object, you can create a new Customer or Employee object by passing the values which you received from the user.
Customer customer = new Customer(firstName, lastName, email, custNumber);
or
Employee employee = new Employee(firstName, lastName, email, empSoc);
Here's the snippet of both:
public class Person {
public Person (String first, String last, String email) {
// You'd fill in code here for handling the variables
}
// ...
}
public class Customer extends Person {
public Customer (String first, String last, String email, String custNo) {
super(first, last, email);
// You'd fill in code here for handling the variables
}
// ...
}
public class Employee extends Person {
public Employee (int social) {
super(first, last, email);
// You'd fill in code here for handling the variables
}
// ...
}
To print something from the Person class, using that static method (why? You could override toString() instead), you frame it such that your Person object has accessors to each of the fields relevant to a Person. This would mean you have a getFirstName(), getLastName(), and so forth, relevant to the object if it's an employee or a customer. (I leave that as an exercise to you.)
In that sense, one would then only require calls to those accessors to print the value.
public static void print(Person p) {
System.out.println(p.getFirstName()) + " " + p.getLastName()); // You can get the trend from here.
}
To print the Person object you can just use the System.out.println() if you just want to print it to the command line, but you'll get some unreadable nonsense.
What the println() method does is, if the object is not a String call it's toString() method, because all objects have one, it is defined in java.lang.Object. But that method gives us unreadable things mentioned above, so you have to override it to do something like
public class Person
{
String firstName;
String Lastname;
public Person(String firstName, String lastName)
{
this.firstName = firstName;
this.lastName = lastName;
}
public String toString()
{
// Create a String that represents this object
return "This person is called " + firstName + " " + lastName;
}
}
To create an object you can read the Strings from the commandline and then pass them into the constructor as Makoto suggests.

Categories

Resources