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

why is my my class giving me an error for the return?

Now i got it set as a constructor, however I am unsure how to actually use this. I want to be able to store the first name, last name and degree level. I need it to continue to run until I stop it and continue with more of the program.
import javax.swing.*;
import java.util.ArrayList;
public class Tutor
{
public Tutor(String firstName, String firstName, String degreeLevel)
{
firstName = firstName;
lastName = firstName;
degreeLevel = degreeLevel;
}
public static void main (String[] args)
{
String fName;
String lName;
String level;
String ans;
ArrayList<String> listOfTutor = new ArrayList<String>();
for (int i = 0; i<listOfTutor.size(); i++)
{
fName = JOptionPane.showInputDialog(null,"Enter Tutor's First Name: ");
lName = JOptionPane.showInputDialog(null,"Enter Tutor's Last Name: ");
level = JOptionPane.showInputDialog(null,"Enter Tutor's Highest Level of Degree: ");
Tutor t = new Tutor(fName,lName,level);
listOfTutor.add(t);
}
}
}
Edit
import javax.swing.*;
import java.util.ArrayList;
public class Tutor
{
String firstName;
String lastName;
String degreeLevel;
public Tutor(String firstName, String lastName, String degreeLevel)
{
this.firstName = firstName;
this.lastName = firstName;
this.degreeLevel = degreeLevel;
}
public static void main (String[] args)
{
String fName;
String lName;
String level;
String ans;
ArrayList<Tutor> listOfTutor = new ArrayList<Tutor>();
for (int i = 0; i<3; i++)
{
fName = JOptionPane.showInputDialog(null,"Enter Tutor's First Name: ");
lName = JOptionPane.showInputDialog(null,"Enter Tutor's Last Name: ");
level = JOptionPane.showInputDialog(null,"Enter Tutor's Highest Level of Degree: ");
Tutor t = new Tutor(fName,lName,level);
listOfTutor.add(t);
}
}
}
You did a lot of wrong there:
First: If Tutor is a Method:
You have to set a Return Type to your Method. public static String Tutor(...)
This way your Method returns your values correctly.
Second: If Tutor should be your Class:
Then you have to rename either your class to Tutor or your Constructor to CalculateATutor.
A constructor never has a Return Type and never contains a return-Statement. So this way you have to delete your return-Statement in your Constructor.
public CalculateATutor(String firstName, String lastName, String degreeLevel)
{
this.firstName = firstName;
this.lastName = lastName;
this.degreeLevel = degreeLevel;
}
Third:
The usage of your Class Tutor (if it is a class) is wrong
String ans;
List<Tutor> myTutor = new ArrayList<Tutor>(); //You have to specify Tutor in your Template-Class
for (int i = 0; i<myTutor.size; i++)
{
ans = JOptionPane.showInputDialog(null,"Enter Tutor's Last Name, First Name, and Highest Level of Degree:");
//Here you have a lot to do because you get one inputstring with all 3 Elements
//You have to split the input or get 3 seperate inputs
// We assume you have your correct input here right now with Strings fname, lname, level
Tutor t = new Tutor(lname,fname,level);
myTutor.add(t);
}
}
EDIT:
To your new Question:
You have to declare local variables into the class.
public class TestClass{
String lastName;
public TestClass(String lastName){// this is the Constructor
this.lastName = lastName;
}
}
This way you can store the Variables.
You need getting the error because the Tutor() function is returning a value, but no return type is given in the method declaration.
If you want your function to return a String:
public String Tutor(String firstName, String lastName, String degreeLevel)
^^^^^^
There are actually many problems in the code currently. I believe what you're trying to do is make Tutor() a constructor. If that's the case, it's declaration should be:
public CalculateATutor(String firstName, String lastName, String degreeLevel)
because CalculateATutor is the name of the class. It should not return anything. Additionally, these lines:
this.firstName = firstName;
this.lastName = lastName;
this.degreeLevel = degreeLevel;
will not work the way you want. If you're attempting to set class fields, you need to declare the fields in your class first. Like this:
public class CalculateATutor
{
String firstName;
String lastName;
String degreeLevel;
...
}
public String Tutor(String firstName, String lastName, String degreeLevel)
^ missing
as you are returning String
return(lastName +", "+ firstName +" "+ degreeLevel);
Instead our answers try to understand compiler's error message:
error: invalid method declaration; return type required
^ function declaration is wrong
Also says return type required So you forgot return type of function.
Where function name is public Tutor()
public Tutor(String firstName, String lastName, String degreeLevel)
should be
public String Tutor(String firstName, String lastName, String degreeLevel)
The error message is telling you what to do. all Java methods/functions have to be declared with a return type.
In this case it appears to be a String, so it becomes
public String Tutor()
If you dont want it to return anything then it is
public void getMiau()
Add return type to method. As you posted you are returning String without giving return type of method. So add String as return type of method.
If you try to return a value from a method that is declared void, you will get a compiler error.
public String Tutor(String firstName, String lastName, String degreeLevel) {
.....
return(lastName +", "+ firstName +" "+ degreeLevel);
}
You're treating Tutor like a method. If Tutor is indeed a method, you don't have a return type associated with it.
Also where are firstName, lastName, and degreeLevel getting declared at in the class? It looks to me like there maybe other issues than just that -- keep in mind.
Your code is really messed.
You have a class named CalculateATutor, inside it something looks like a constructor but named Tutor and you use it inside your main function as a regular class.
First, you need to understand what you want to do (and maybe read about classes and constructors).
But for your question:
If you want to have a method named Tutor, you need to add return type to the method signature;
public String Tutor(String firstName, String lastName, String degreeLevel)
{
this.firstName = firstName;
this.lastName = lastName;
this.degreeLevel = degreeLevel;
return(lastName +", "+ firstName +" "+ degreeLevel);
}
If you're trying to create a constructor, you need to use the class name and remove the return statement:
public CalculateATutor(String firstName, String lastName, String degreeLevel)
{
this.firstName = firstName;
this.lastName = lastName;
this.degreeLevel = degreeLevel;
}
Your Tutor method is returning a string, but you haven't declared it as having a return type. Try:
public String Tutor(String firstName, String lastName, String degreeLevel)
It's not clear if Tutor is supposed to be a method or a constructor. If it is supposed to be a constructor, you are declaring it in a class named CalculateATutor, which won't work. You also did not write the constructor as a constructor (it should not have a return statement). You can fix this in several ways:
Change the class name to Tutor.
Change the constructor name to CalculateATutor.
Move the Tutor constructor to an inner class of CalculateATutor named Tutor.
1) you're using the this. keywork to refer to class variables that you haven't defined
2) you seem to have called the class CalculateATutor but the constructor for the class Tutor, they should be the same, so something like this:
import javax.swing.*;
public class Tutor //NOTE CORRECTED CLASS NAME
{
String firstName;
String lastName;
String degreeLevel
public Tutor(String firstName, String lastName, String degreeLevel)
{
this.firstName = firstName;
this.lastName = lastName;
this.degreeLevel = degreeLevel;
}
public static void main (String[] args)
{
String ans;
List<Tutor> Tutor = new ArrayList<>();
for (int i = 0; i<Tutor.size; i++) //Tutor.size==0, will never run, I can't correct as I have no idea what you want to happen
{
ans = JOptionPane.showInputDialog(null,"Enter Tutor's Last Name, First Name, and Highest Level of Degree:");
Tutor = ans; //I have no idea whats going on here but Tutor should be initialised like new Tutor(string,string,string)
}
}
}

Unable to display object array using get(index)

I am trying to display the different objects in an ArrayList. In my project context, one student is one object.
I used an ArrayList to store all the different student objects and I am having problems reading the ArrayList.
<%
String student_name = request.getParameter("studentName");
ArrayList<Object[]> studentList = new ArrayList<Object[]>();
if(student_name != null && student_name.length() > 0) {
PreparedStatement preparedStatement = con.prepareStatement("Select * from users where firstname LIKE ? ");
preparedStatement.setString(1, "%" +student_name+ "%");
ResultSet resultSet = preparedStatement.executeQuery();
while (resultSet.next()) {
String first_name = resultSet.getString("firstname");
String last_name = resultSet.getString("lastname");
String email = resultSet.getString("email");
Object[] student = {first_name,last_name,email};
studentList.add(student);
session.setAttribute("studentObject",studentList);
//System.out.println("First Name: " + first_name + "," + "Last Name: " + last_name);
System.out.println(studentList.get(0));
}
When I try to display (studentList.get(0)), all I see is "[Ljava.lang.String;#XXXX"
How do i get it to display the different student objects based on the index ?
At first, It will be more idiomatic in Java to define your own class Student. Write an extractor to that class, define toString method and it will be great.
Java requires you to define toString method to any type of object that will be printed. So, you have to define toString for your Student class.
But you are using an array. Java doesn't have toString method defined for Arrays. So I would propose you to do something like this. (I'm a bit on rush so code may contain some mistakes:
// At first it could be better to define a structure
// that represents a student
// class must be defined in separate file like Student.java
// Student.java
public class Student {
// constructor for the Student object
public Student(final String firstName,
final String lastName,
final String email) {
this.firstName = firstName;
this.lastName = lastName;
this.email = email;
}
private String firstName;
private String lastName;
private String email;
#override String toString() {
return firstName + " " + lastName + " " + email;
}
// getters
public String getFirstName() { return firstName; }
public String getLastName() { return lastName; }
public String getEmail() { return email; }
// setters
public void setFirstName(final String firstName) {
this.firstName = firstName;
}
public void setLastName(final String lastName) {
this.lastName = lastName;
}
public void setEmail(final String email) {
this.email = email;
}
} // end of Student.java file
///////////////////////////////////////////
final ArrayList<Student> studentList = new ArrayList<Student>();
.... // your code
ResultSet resultSet = preparedStatement.executeQuery();
while (resultSet.next()) {
// creating a new student with new keyword
final Student currentStudent = new Student(
resultSet.getString("firstname"),
resultSet.getString("lastname"),
resultSet.getString("email")
)
// you are adding a student object to the list
studentList.add(currentStudent);
session.setAttribute("studentObject",studentList);
// that should work
// toString method will be called implicitly
System.out.println(studentList.get(0));
}
// So you will have a list of students
// that will be accessable in the following manner:
studentList.get(0).getFirstName;
studentList.get(1).setFirstName("New name");
If you want a different behaviour you may call those fields directly, or modify
the behavior of toString method
Java also assumes that you're using camelCase notation, you may find in in the style guide.
Hope it helps.
Try java.util.Arrays class:
System.out.println(Arrays.toString(studentList.get(0)));
Currently you are printing out the Object[] which is not exactly human readable. I would suggest creating a new class called Student. Then have three member variables firstName, lastName, and email. Also create a toString() method for this new class. Then you can have an ArrayList of Students. This should simplify everything for you.
You have at least two options:
Implement an object corresponding to Object[] student:
In this class you may override Object's toString(), and implement it as to wish to present the data.
NOTE: this is very relevant to you because when printing studentList.get(0) you actually print call Object's default toString() which returns the reference to the object.
For more information regarding default Object.toString() here.
The simplestway is to use Arrays.toString():
System.out.println(Arrays.toString(studentList.get(0)));
It looks like you're not trying to display a String as you expect, you're trying to display an array of Objects.
You could try : System.out.println(studentList.get(0)[0]);
You'll have an idea

JAVA - HELP adding comparable interface and arrays into my class

I got a lab assignment dealing with arrays, sorting them and adding comparable interface to my two classes. I have to modify a Customer class so it implements a comparable interface. Then I have to sort an array of objects created by this class.
These are the steps outlined by my worksheet:
open the customer and SortedCustomersApp java files (see below):
public class Customer
{
private String email;
private String firstName;
private String lastName;
public Customer(String email, String firstName, String lastName)
{
this.email = email;
this.firstName = firstName;
this.lastName = lastName;
}
public void setEmail(String email)
{
this.email = email;
}
public String getEmail()
{
return email;
}
public void setFirstName(String firstName)
{
this.firstName = firstName;
}
public String getFirstName()
{
return firstName;
}
public void setLastName(String lastName)
{
this.lastName = lastName;
}
public String getLastName()
{
return lastName;
}
}
This is the sorted customers app:
import java.util.Arrays;
public class SortedCustomersApp
{
public static void main(String[] args)
{
}
}
add code to the customer class to implement the comparable interface. The compareTo method you create should compare the email field of the current customer with the email field of another customer. To do that you cant use the < or > operators because the email field is a string. Instead, use the compareToIgnoreCase method of the string class. This method compares the string it's executed on with the string that's passed to it as an argument. If the first string is less than the 2nd string, this methods returns a negative integer. if the first string is greater than the second string, it returns a positive integer. And if the 2 strings are equal, it returns 0.
3.Add code to the SortedCustomersApp class that creates an array of Customer objects that can hold 3 elements, and create and assign Customer objects to those elements. Be sure that the email values you assign to the objects aren't in alphabetical order. Sort the array.
code a "for each" loop that prints the email, firstName, and lastName fields of each Customer object on a separate line.
compile and test the program
This program needs to have user input for email, firstName, and lastName but when I tried adding user input to the customer app I got errors saying I cant convert a string to scanner type, but the user inputs need to be a string so that's also a problem.
you implement Comaprable in order to define for Collections.sort() what criteria you use compare instances.For example if I was to compare students by their grades:
public class Student implements Comparable<Student>{
int age;
int grade;
//this method is used in Collections.sort() to determine what is bigger
//for me its grades that matter so that's what I do in code
#override
compareTo(Student other){
if(this.grade>other.grade){
return 1;
}else if(grade<other.grade){
return -1;
}
return 0;
}
}
then you just create an ArrayList students for example and call
Collections.sort(students)
EDIT: to answer you question in comments. If you use a Collection like ArrayList you would call Collections.sort() , if you use a regular array, then Arrays.sort(). In both cases the Objects to be sorted need to implement Comparable just like I showed you.
You can compare two String's lexicographically calling compareTo method on String object, code looks like this
public class Customer implements Comparable<Customer>{
private String email;
public Customer(String email) {
this.email = email;
}
public void setEmail(String email) {
this.email = email;
}
public String getEmail() {
return email;
}
#Override
public int compareTo(Customer otherCustomer) {
return this.email.compareToIgnoreCase(otherCustomer.email);
}
#Override
public String toString() {
return "Customer{" +
"email='" + email + '\'' +
'}';
}
}
You can sort list of objects using Collections.sort method
List<Customer> list = new ArrayList<>();
list.add(new Customer("abc#bc.com"));
list.add(new Customer("des#bc.com"));
list.add(new Customer("bbc#bc.com"));
list.add(new Customer("aec#bc.com"));
Collections.sort(list);
modified customer class
public class Customer implements Comparable<Customer>{
:
public int compareTo(Object obj)
{
Customer cus = (Customer) obj;
// write your comparison code here
// return 1, 0, or -1 on the basis of your requirement
}
:
}
Then perform
Collection.sort(customerList);
in main method to sort the data.
There is two ways to take String as an input from user:
1) Buffered Reader
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String email = reader.readLine(); // email, firstname etc.
2) Scanner Class
Scanner input = new Scanner(System.in);
String email = input.next();
Now create an Customer object and add setter method to set the value.

Why won't this print anything but null?

Why won't this print anything but null?
I am attempting to add new objects that are created as you answer the question and then add them to an array which I can access at a later time.
public static void main(String[] args) {
// TODO code application logic here
addastudent();
}
private static void addastudent(){
ArrayList<Object> students = new <Object> ArrayList();
Scanner user = new Scanner(System.in);
System.out.println("First Name: " );
String fname = user.next();
System.out.println("Last Name: ");
String lname = user.next();
System.out.println("Major: ");
String major = user.next();
System.out.println("GPA: ");
double gpa = user.nextDouble();
student a = new student (fname,lname,major,gpa);
students.add(a);
System.out.println(students);
}
Edit: Thank you for pointing out the toString() problem. That was it. I had forgot I told the toString() to return Null. I hate it when you miss something that simple... Thanks guys again
There are several problematic items in this code.
You should overwrite toString in the Student class. Otherwise it will use toString of Object, which will print something like "Student#148ccb8".
Ensure the constructor of Student assigns all its field with the given parameters. You didn't provide the code, but it should look something like this:
public class Student {
private String firstname;
private String lastname;
private String major;
private double gpa;
public Student(
String firstname,
String lastname,
String major,
double gpa) {
this.firstname = firstname;
this.lastname = lastname;
this.major = major;
this.gpa = gpa;
}
#Override
public String toString() {
return "Student [firstname=" + firstname + ", lastname=" + lastname + ", major="
+ major + ", gpa=" + gpa + "]";
}
}
And some minors:
Class names in Java should start with a capital letter. So it's Student and not student.
Creating an ArrayList for when creating a single Student instance is not appropiate (yet), but makes sense when you extend the code to severeal Student instances.
Using generics with Object is not using them at all!
When using Collection classes, usually declare your variable to the common supertype.
With the last two points it's:
List<Student> students = new <Student>ArrayList();
Change
ArrayList<Object> students = new <Object> ArrayList();
To
ArrayList<student> students = new ArrayList<student>();
Add overided
toString
method in Student class.
Hint! If you are using eclipse IDE then select your student class and go to Source menu and select generate toString method from there.
First of all, please follow Java Naming Conventions and rename your method to addStudent, also please change student class to Student.
In this line,
ArrayList<Object> students = new <Object> ArrayList();
you're creating an ArrayList object, which's called students, Object is very generic, try to be more specific and change it to:
ArrayList<Student> students = new <> ArrayList();
Finally, you're printing the object, and not the content. In order to print the content, you need to iterate on students array list and print each object, after you override equals in Student class.
If that is the full code the issue is that you have no student class. In order to use the student class you have to tell your program what it is.
Here is a simple student class to start you off.
public class Student {
private String fname;
private String lname;
private String major;
private double gpa;
public Student(String fname, String lname, String major, double gpa) {
this.fname = fname;
this.lname = lname;
this.major = major;
this.gpa = gpa;
}
}
I haven't compiled this code but it looks like it should work.
NOTE: You will need to change
new student (fname,lname,major,gpa);
to
new Student (fname,lname,major,gpa);
(Notice the case change)
students variable (ArrayList) should be an instance variable, not local variable.
According to above code, you will always end up with only single student in the list because you re-create the ArrayList each time when the method addastudent is called.

How to load an ArrayList with instances of an Object I created

NOTE: I edited my code to how I think people are trying to tell me but it still doesn't give me my desired output. Now my output is "examples.search.Person#55acc1c2" however many times I enter new first and last names. At least it's making it through the code with out crashing lol
I am learning how to use ArrayLists and need to load an Array list with instances of an Object I created. I know how to do this with an array but for this assignment I need to do it with an ArrayList. Here's an example of what I need to do.
// my "main" class
package examples.search;
import java.util.ArrayList;
import dmit104.Util;
public class MyPeople {
public static void main(String[] args) {
ArrayList<Person> people = new ArrayList<Person>();
Person tempPerson = new Person();
String firstName;
String lastName;
char choice = 'y';
int count = 1;
// fill my ArrayList
do {
people.add(tempPerson);
// I have a Util class that has a prompt method in it
firstName = Util.prompt("Enter First Name: ");
lastName = Util.prompt("Enter Last Name: ");
tempPerson.setFirstName(firstName);
tempPerson.setLastName(lastName);
count++;
choice = Util.prompt(
"Enter another person? [y or n]: ")
.toLowerCase().charAt(0);
} while (choice == 'y');
// display my list of people
for(int i = 0; i < people.size(); i += 1) {
System.out.print(people.get(i));
}
}
}
// my Person class which I am trying to build from
public class Person {
// instance variables
private String firstName;
private String lastName;
// default constructor
public Person() {
}
public String getFirstName(){
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}
I've tried it a number of ways but no matter what my ArrayList doesn't fill up. Like I mentioned I can do it no problem with an array or even if I had a loaded constructor method but I don't. In my actual assignment I am supposed to do it with the set methods.
I have looked everywhere and cannot find the solution for my problem and being friday my instructor isn't in.
Thank you so much in advance
Leo
You have an ArrayList<Person>, but that alone only defines a list of potential Person instances. But so far, each of the list entries is null. The get(i) returns null, and the following null.setFirstName(..) causes a NullPointerException.
So you need to create the instances of Person that are supposed to go into the list:
firstName = Util.prompt("Enter First Name: ");
Person p = new Person(); //create the instance
people.add(p); //add the instance to the list
p.setFirstName("..."); //set any values
You'll have to create a Person and then add it to the ArrayList.
for (int i = 0; i < count; i++) {
Person person = new Person();
person.setFirstName("Foo");
person.setLastName("Bar");
people.add(person);
}
Its crashing because your line people.get(i).setFirstName(firstName); is first trying to what is at index i, but you have not set anything yet.
Either first set people[i] to a empty Person, or make a person using firstName and lastName, and add it to people using people.add(person);
Now you are storing the Person Object into an ArrayList and printing that Object.
To print the firstname and lastName when you print the Person object, you will have to override toString method.
Add the following code in your Person class
public String toString(){
return String.format("[Personn: firstName:%s ,lastName: %s]", firstName,lastName);
}
As for the second question you had, you have to override the toString() method in the Person class. The outputs you are getting, such as examples.search.Person#55acc1c2 is the default toString() method from the Object class, which is defined as class#hashCode

Resources