I've created the class Course which contains the array students. This array contains student names which are in string form.
My new goal is to convert from an Array to an ArrayList. I'm not really sure how to go about this. I've read up on ArrayList and I believe it's resize-able which I think would work well in this case given the fact that the number of students might change constantly with my dropSutdent and addStudent method as opposed to setting an array size to 100, but only having 20 students.
I'd really appreciate and explanations/suggestions of how exactly to change to an ArrayList instead of an Array.
Note I apologize for any mistakes or if I left something unclear. This is my first question on StackOverflow and I know you guys are pretty strict on question asking, so I apologize in advance.*
class Course {
private String courseName;
private String[] students = new String[100];
private int numberOfStudents;
public Course(String courseName) {
this.courseName = courseName;
}
public void addStudent(String student) {
int add = numberOfStudents - students.length; //Create integer to find how many slots we need
if (numberOfStudents > students.length) { //if # of students is bigger then size of array,
String[] array = new String[students.length + add]; //then we add slots to the array.
System.arraycopy(students, 0, array, 0, students.length); //copy array
students = array;
}
students[numberOfStudents++] = student; //add student.
}
public String[] getStudents() {
return students;
}
public int getNumberOfStudents() {
return numberOfStudents;
}
public String getCourseName() {
return courseName;
}
public void dropStudent(String student) {
for (int i = 0; i < students.length; i++) {
if (student == (students[i])) { //If student matches the student we want to remove.
numberOfStudents--; //remove student
while (i < numberOfStudents) {
students[i] = students[i+1];
i++;
}
}
}
}
public void clear() {
students = new String[1]; //set size to 1
numberOfStudents--; //remove all students
}
}
List handles resizing internally, which means you can remove most of the boilerplate by using it instead of an array.
class Course {
private String courseName;
private List<String> students = new ArrayList<>();
public Course(String courseName) {
this.courseName = courseName;
}
public void addStudent(String student) {
students.add(student);
}
public List<String> getStudents() {
return students;
}
public int getNumberOfStudents() {
return students.size();
}
public String getCourseName() {
return courseName;
}
public void dropStudent(String student) {
while (students.remove(student));
}
public void clear() {
students.clear();
}
}
ArrayLists are really usefull, but if you need more options, you can always create a class that works like list and implement all the methods as you wish.
Example for students:
public class studentList{
int size;
Student [] list;
public studentList()
{
size = 0;
list = new Student[size];
}
public studentList(int size)
{
this.size = size;
list = new Student[size];
}
public void add(Student s)
{
}
public void remove(Student s)
{
}
public void sort()
{
}
}
You can implement as you wish.
Related
public class pro1{
static ArrayList <String> student = new ArrayList<String>();
static ArrayList <Integer> id = new ArrayList<Integer>();
String name;
int ID;
public pro1() {
this.name = "";
this.ID = 0;
}
public pro1(String name, int ID) {
this.name = name;
this.ID = ID;
}
public boolean addStudent(String name, int ID) {
student.add(name);
id.add(ID);
return true;
}
/*#Override
public String toString() {
return name + ID;
}*/
public static void main(String args[]) {
pro1 stu = new pro1();
stu.addStudent("john", 1);
stu.addStudent("johnny", 2);
System.out.println(stu);
}
}
I want to print out both the name of the student and the student id using ArrayList. however, I'm not sure how to do that since in this class I can only print out the ArrayList of names or the ArrayList of id. I'm thinking of maybe using another class to create a student object, but I'm not sure how to do so.
great question, I think the best solution for this would be to create a Student object just like you thought!
public static class Student {
private final String name;
private final int id;
public Student(String name, int id) {
this.name = name;
this.id = id;
}
#Override
public String toString() {
return String.format("name=%s, id=%s", name, id);
}
}
public static class School {
private final List<Student> students;
public School(List<Student> students) {
this.students = students;
}
public void add(Student student) {
students.add(student);
}
public List<Student> getStudents() {
return students;
}
}
public static void main(String... args) {
School school = new School(new ArrayList<>());
school.add(new Student("jason", 1));
school.add(new Student("jonny", 2));
school.getStudents().forEach(System.out::println);
}
Non-OOP
Loop the pair of lists.
First sanity-check: Are the two lists the same size?
if( students.size() != ids.size() ) { … Houston, we have a problem }
Then loop. Use one index number to pull from both lists.
for( int index = 0 ;
index < students.size() ;
index ++
)
{
System.out.println(
students.get( index ) +
" | " +
ids.get( index )
) ;
}
OOP
The object-oriented approach would be to define a class. The class would have two member fields, the name and the id of the particular student.
Then create a method that outputs a String with your desired output.
All this has been covered many times on Stack Overflow. So search to learn more. For example: Creating simple Student class and How to override toString() properly in Java?
Uncomment and modify your toString() method as below. It will print both student and id.
#Override
public String toString() {
return student.toString() + id.toString();
}
If you want to have Student to Id mapping, best is to have them in Map collection. Id as key and student name as value.
I want to add values to the objects with out looping because if there are 1000 of objects then I don't want to loop all of them.I want to add age randomly to the students based on the Name of the student.Is there are any way to add values
Here is the code
import java.util.*;
import java.io.*;
class Student{
Student(String Name){
this.Name=Name;
}
String Name;
int age;
}
public class HelloWorld{
public static void main(String []args){
String a []={"Ram","Krishna","Sam","Tom"};
ArrayList<Student> al = new ArrayList<Student>();
for(int i=0;i<a.length;i++){
Student c;
c=new Student(a[i]);
al.add(c);
}
for(Student obj:al){
if(obj.Name.equals("Krishna")){
obj.age=24;
}
System.out.println("Name = "+ obj.Name + " Age = " + obj.age);
}
}
}
First some minor points:
You should never use the fields directly but create getter and setters instead. The fields should be private. Variable names should start with a lower case letter by convention. So this would be the adjusted Student class:
public class Student {
private String name;
private int age;
public Student(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
To store the Student objects you can use a map with names as keys and Student instances as values.
It is good practice to declare the variable only with the interface type Map and not with the concrete implementation HashMap. A hash map has O(1) complexity for searching by key. So you don't need a loop to iterate through all Student instances. (The HashMap.get() implementation doesn't use a loop internally.)
public static void main(String[] args) {
String a [] = {"Ram", "Krishna", "Sam", "Tom"};
// Keys: student names
Map<String, Student> al = new HashMap<String, Student>();
// Fill the Student's map
for(int i = 0; i < a.length; i++){
String name = a[i];
al.put(name, new Student(name));
}
// Manipulate one student by name. If there is no entry for that name we get null.
// So we better check for null before using it.
Student student = al.get("Krishna");
if(student != null) {
student.setAge(24);
}
// Output the all students
for(Student obj: al.values()){
System.out.println("Name = "+ obj.getName() + " Age = " + obj.getAge());
}
}
i have for loop where i get data to send to other method in different class
UserManagerImpl.java
for (User user: userList) {
surveyModel survey = new SurveyModel();
survey.setSurveyData(Id, comment, serveyScore, grade);
}
In other class i have set and get to create list of datas and then want to fetch it by get method.
surveyModel.java
public class SurveySentimentModel {
public static String delimiter = "|||";
private List scores = new ArrayList();
private List negativeData = new ArrayList();
private List PositiveData = new ArrayList();
public void setSurveyData(String Id, String comment, double Score, String grade) {
//want to add score to scores list
//if grade positive add to positive list or else negative after delimiting
}
public double getTotalScore() {
//calculate the sum of scores
return totalScore;
}
public String getTotalSentimentgrade() {
if (totalScore> 0) {
return "Positive";
}
return "Negative";
}
public List getSurveyData() {
//Want to merge list - first negative and then positive
return new ArrayList();
}
}
SurveyModel.java
private String grade;
private Number Score;
private String Id;
private String comment;
public SurveyModel(String Id, String comment, double Score, String grade) {
this.grade= grade;
this.Score= Score;
this.comment = comment;
this.Id = Id;
}
public SurveyModel() {
// TODO Auto-generated constructor stub
}
// getters and setters
IN here i want to
1.) Add score to scores list
2.) want to add graddes to list by negative first with delimiter then positive.
3.) want to get total score.
How could i achive my requirement. I am new to java please help me on this.
Here's a suggestion:
This is the Model class:
public class SurveySentimentModel {
public static String delimiter = "|||";
private List<SurveyModel> scores = new ArrayList();
private List<SurveyModel> negativeData = new ArrayList();
private List<SurveyModel> positiveData = new ArrayList();
public void setSurveyData(String Id, String comment, double score, String grade) {
SurveyModel survey = new SurveyModel(id, comment, score, grade );
scores.add(survey)
if(score >= 0){
positiveData.add(survey);
}else{
negativeData.add(survey);
}
}
public double getTotalScore() {
double sum = 0;
for(SurveyModel s: scores){
sum += s.getScore();
}
return sum;
}
public List getSurveyData() {
List<SurveyModel> joined = new ArrayList(negativeData);
joined.addAll(positiveData)
return joined;
}
}
This is the loop:
SurveySentimentModel sentiments = new SurveySentimentModel();
for (User user: userList) {
sentiments.setSurveyData(user.getId(), user.getComment(), user.getSurveryScore(), user.getGrade());
}
package student;
import javax.swing.JOptionPane;
public class Student
{
private Name name;
String idNUM, course;
public Student(Name n, String idNum){
this.name = n;
this.idNUM = idNum;
}
public Name getName(){
return name;
}
public String getId(){
return idNUM;
}
}
package student;
public class StudentCourse
{
Student studInfo, studentInfo;
String studentCourses, studentCourse;
StudentCourse(String sc)
{
studentCourses = sc;
}
public String getCourses(){
return studentCourses;
}
}
package student;
public class StudentAccounts
{
private Student stud;
private String addedClass;
String courses;
public StudentAccounts (Student s, String course)
{
stud = s;
courses = course;
}
public Student getStudent()
{
return stud;
}
public void insertClass(String cla)
{
courses = cla;
}
public String getCourses()
{
return courses;
}
}
Sorry for posting a lot of code. But right here is where the problem is. in the Database class below. The method "void addCourses(StudentCourse e)". When running the test class. It crashes right after entering a course name, it won't store it like the student name. Im a little new with programming cohesively. Can someone please explain what I am missing?
package student;
import java.util.ArrayList;
public class DataBase
{
ArrayList <StudentAccounts> list;
ArrayList <StudentCourse> courseList;
StudentAccounts sa ;
StudentCourse sc;
int index;
boolean found = false;
DataBase()
{
list = new ArrayList<> ();
}
ArrayList getList()
{
return list;
}
ArrayList getCourseList()
{
return courseList;
}
StudentCourse getCourse(){
return sc;
}
StudentAccounts getAccount()
{
return sa;
}
StudentAccounts delete (int d)
{
return list.remove(d);
}
boolean inList() //Looks in the ArrayList
{
return found;
}
boolean isEmpty()
{
return list.isEmpty();
}
int getIndex()
{
return index;
}
int getSize() // return the amount of strings in the Array
{
return list.size();
}
void add(StudentAccounts s)
{
list.add(s);
}
void addCourse(StudentCourse e)
{
courseList.addCourse(e);
}
void search(String key)
{
found = false;
int i = 0;
while (!found && i < list.size() )
{
StudentAccounts sl = list.get(i);
if(sl.getStudent().getId().equalsIgnoreCase(key))
{
sa =sl;
found = true;
index = i;
}
else
i++;
}
}
}
You have not initialized your courseList variable. You have initialized only the one list variable in the constructor Database. When you add a course, the addCourse() method will throw a null pointer exception.
Add the following line in your Database constructor:
courseList = new ArrayList<>();
Also, the line courseList.addCourse(e) should be a compilation error (so silly of me). courseList is an object of type ArrayList. ArrayList class does not have a method called addCourse(Studentcourse e). It only has a method add() which will take an object of type StudentCourse in your case. So you will see a cannot find symbol error.
Change that line to:
courseList.add(e);
Let say I have an ArrayList<Student> contains 4 Students(name , city, school).
For example:
1. John Nevada BBBB
2. Mary Ander AAAA
3. Winn Arcata CCCC
4. Ty Artes BBBB
If user enter “BBBB” then it displays: :
1. John Nevada BBBB
2. Ty Artes BBBB
My question is that how do I compare a input string “BBBB” with the schools in the above ArrayList?
Thank you for any help that you guys would provide!
public class Student
{
private String name;
private String city;
private String school;
/**
* Constructor for objects of class Student
*/
public Student(String name, String city, String school)
{
this.name = name;
this.city = city;
this.school = school;
}
public String getSchool(String school)
{
return this.school = school;
}
public String toString()
{
return "Name: " + name + "\tCity: " +city+ "\tSchool: "+school;
}
}
public class AllStudent
{
// instance variables - replace the example below with your own
private ArrayList<Student> listStudent = new ArrayList<Student>();
/**
* Constructor for objects of class AllStudent
*/
public AllStudent() throws IOException
{
//variables
// read an input file and save it as an Arraylist
fileScan = new Scanner (new File("students.txt");
while(fileScan.hasNext())
{
//.......
listStudent.add(new Student(name,city,school);
}
//now let user enter a school, the display name, city, school of that student.
//i am expecting something like below...
public void displayStudentBasedOnSchool(String school)
{
for (i = 0; i < listStudent.size(); i++)
{
//what should i put i here to comapre in input School with school in the listStudent>
}
}
}
Assuming your student is modelled like this (AAAA, BBBB values are stored in blah field):
public class Student {
private String name;
private String state;
private String blah;
//getters & setters..
}
The simplest (not most efficient way) is just to loop the array list and compare the query string with value of blah field
for(Student s : studentList) {
if(s.getBlah().equals(queryString)) {
// match!..
}
}
I believe Student is class and you are creating list of Student
The ArrayList uses the equals method implemented in the class (your case Student class) to do the equals comparison.
You can call contains methods of list to get matching object
Like,
public class Student {
private String name;
private String city;
private String school;
....
public Student(String name, String city, String school) {
this.name = name;
this.city = city;
this.school = school;
}
//getters & setters..
public String setSchool(String school) {
this.school = school;
}
public String getSchool() {
return this.school;
}
public boolean equals(Object other) {
if (other == null) return false;
if (other == this) return true;
if (!(other instanceof Student)) return false;
Student s = (Student)other;
if (s.getSchool().equals(this.getSchool())) {
return true; // here you compare school name
}
return false;
}
public String toString() {
return "Name: " + this.name + "\tCity: " + this.city + "\tSchool: "+ this.school;
}
}
Your array list would be like this
ArrayList<Student> studentList = new ArrayList<Student>();
Student s1 = new Student(x, y, z);
Student s2 = new Student(a, b, c);
studentList.add(s1);
studentList.add(s2);
Student s3 = new Student(x, y, z); //object to search
if(studentList.contains(s3)) {
System.out.println(s3.toString()); //print object if object exists;
} // check if `studentList` contains `student3` with city `y`.It will internally call your equals method to compare items in list.
Or,
You can simply iterate object in studentList and compare items
for(Student s : studentList) {
if(s.getSchool().equals(schoolToSearch)) {
// print object here!..
}
}
Or, as you commented ,
public void displayStudentBasedOnSchool(String school){
for(int i = 0; i < studentList.size(); ++i) {
if(studentList.get(i).getSchool().equals(school)) {
System.out.println(studentList.get(i).toString()); // here studentList.get(i) returns Student Object.
}
}
}
Or,
ListIterator<Student> listIterator = studentList.listIterator(); //use list Iterator
while(listIterator.hasNext()) {
if(iterator.next().getSchool().equals(school)) {
System.out.println(listIterator.next());
break;
}
}
or even,
int j = 0;
while (studentList.size() > j) {
if(studentList.get(j).getSchool().equals(school)){
System.out.println(studentList.get(j));
break;
}
j++;
}
So now you have set of options
for-loop
for-each loop
while loop
iterator
I would probably use Guava library from Google.
Take a look at this question: What is the best way to filter a Java Collection? It provides many excelent solutions for your problem.