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());
}
}
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 have a program I am working with to help me practice my coding skills. The program has the following scenario: there is a classroom of 20 students, where the record is taken of the students' names, surnames, and age. Half of these students take part in the school's athletics. Here, record is kept of their races that they have done and the ones they've won.
In this program, I have three classes:
runStudents - class with main method
Students (String name, String surname, int age) - parental class
AthleticStudents (String name, String surname, int age, int races, int victories) - sub class
The user should be able to add another race (and win) to the object. As seen by the code provided, an Array is created to store the 20 Students objects. I have to be able to access a method to alter the object in the array, but this method is not in the parental class (the class the objects are created from.
public class Students
{
private String name;
private String surname;
private int age;
public Students()
{
}
public Students(String name, String surname, int age)
{
this.name = name;
this.surname = surname;
this.age = age;
}
public String getName()
{
return this.name;
}
public String getSurname()
{
return this.surname;
}
public double getAge()
{
return this.age;
}
public void setName(String name)
{
this.name = name;
}
public void setSurname(String surname)
{
this.surname = surname;
}
public void setAge(int age)
{
this.age = age;
}
public String toString()
{
return String.format("name\t\t: %s\nsurname\t\t: %s\nage\t\t: %s",
this.name, this.surname, this.age);
}
}
public class AthleticStudents extends Students
{
private int races;
private int victories;
public AthleticStudents()
{
}
public AthleticStudents(String name, String surname, int age, int
races, int victories)
{
super(name, surname, age);
this.races = races;
this.victories = victories;
}
public int getRaces()
{
return this.races;
}
public int getVictories()
{
return this.victories;
}
public void setRaces(int races)
{
this.races = races;
}
public void setVictories(int victories)
{
this.victories = victories;
}
public void anotherRace()
{
this.races = this.races + 1;
}
public void anotherWin()
{
this.victories = this.victories + 1;
}
public String toString()
{
return super.toString() + String.format("\nnumber of races\t:
%s\nnumber of wins\t: %s", this.races, this.victories);
}
}
public class runStudents
{
public static void main(String[]args)
{
Students[] myStudents = new Students[20];
myStudents[0] = new Students("John", "Richards", 15);
myStudents[1] = new AthleticStudents("Eva", "Grey", 14, 3, 1);
myStudents[2] = new Students("Lena", "Brie", 15);
for (int i = 0; i < 3; i++)
System.out.println(myStudents[i].toString() + "\n\n");
}
}
I want to be able to do the following:
AthleticStudents[1].anotherRace();
but cannot do so as the array object is derived from the parental class, and I declared the method in the sub class. How can I link the two?
I assume that you create an array of the parent class instances. Just cast the instance this way (you better check whether the element is the instance of a subclass):
if (AthleticStudents[1] instanceof AthleticStudents)
((AthleticStudents) AthleticStudents[1]).anotherRace();
I'm not sure if this is exactly what you're looking for but it worked well for me. Instead of trying to access AthleticStudents method anotherRace() like that, try this in your main method.
Students[] myStudents = new Students[20];
myStudents[0] = new Students("John", "Richards", 15);
myStudents[1] = new AthleticStudents("Eva", "Grey", 14, 3, 1);
myStudents[2] = new Students("Lena", "Brie", 15);
AthleticStudents addRace= (AthleticStudents)myStudents[1];
addRace.anotherRace(); //This will increment Eva's race count to 4
for (int i = 0; i < 3; i++)
System.out.println(myStudents[i].toString() + "\n\n");
All I did was cast the element into an object AthleticStudents named 'addRace'. By casting myStudents[1] to this new object you are able to access all of AthleticStudents methods.
I just saw the other answer posted which works just as well!
Hope this helps!
I’m not sure that i understand your question, because you are a bit inconsistent with your capitalization. runStudents is a class, while AthleticStudents is both a class and an array. But i’ll try.
IF i did understand your question, you have an array Student[] studentArray. Some Student objects in studentArray are AthleticStudents, others are not. You have a specific AthleticStudent eva which is in studentArray[] having let’s say index 1, and you want to add to her anotherRace(). Your call studentArray[1].anotherRace does not compile because the compiler treats that element as a Student and not as a AthleticStudent.
The trick is to cast the element to AthleticStudent. I omit the test of the element of being really an AthleticStudent; you will have to do that test in your code.
((AthleticStudent) studentArray[1]).anotherRace();
I'm making a program to display the names, ages and gpa's of a class which has been stored in an array. I made the Student class with a constructor, accessors and a method to print out the details.
In the main method, I populate the array and want to display all of the items in the array (this is what I'm having trouble with).
This is what I have so far:
public class Student {
private String name;
private int age;
private double gpa;
public Student(String studentName, int studentAge, double studentGpa) {
this.name = studentName;
this.age = studentAge;
this.gpa = studentGpa;
}
//Normal accessors, not going to bother putting them on here.
public void printStudents() {
System.out.println("Name: " + name + ", Age: " + age + ", GPA: " + gpa);
}
//New class, imagine it's on a different file
public class MyClass {
private static Student [] students = new Student[3];
System.out.println("Students in my class");
students[0] = new Student("Mark",16,77.6);
students[1] = new Student("Sam",17,56.9);
students[2] = new Student("Polly",16,97.4);
for (int g = 0; g < students.length; g++) {
//This is where I'm stuck, I'm not sure how to call printStudents here. students.printStudents didn't work for some reason.
class Student {
private String name;
private int age;
private double gpa;
public Student(String studentName, int studentAge, double studentGpa) {
this.name = studentName;
this.age = studentAge;
this.gpa = studentGpa;
}
public void printStudent() {
System.out.println("Name : "+this.name);
System.out.println("Age : "+this.age);
System.out.println("GPA : "+this.gpa);
}
}
public class MyClass {
public static void main(String s[])
{
Student [] students = new Student[3];
System.out.println("Students in my class");
students[0] = new Student("Mark",16,77.6);
students[1] = new Student("Sam",17,56.9);
students[2] = new Student("Polly",16,97.4);
for (int i = 0; i <=(students.length-1); i++) {
students[i].printStudent();
}
}
}
As #Hello_World mentioned in the comments - change printStudents method name to printStudent to make more sense. It is a public method of the Student object, which means you access it directly from the instance of the object (for example students[0].printStudent()). Also you can iterate through an Array with a foreach cycle, which is a bit easier to read.
students[0] = new Student("Mark", 16, 77.6);
students[1] = new Student("Sam", 17, 56.9);
students[2] = new Student("Polly", 16, 97.4);
for (Student student : students) {
student.printStudent();
}
I am trying to solve an assignment in my Java class. I am stuck and need a little help.
I am trying to create a method in my Group class that will display the group name and the 4 students in the group. My code currently displays the group name and the memory location of my student inside my array.
public class Group {
/**-------Declaring attributes----*/
String groupName;
int newStudentCount;
/**----------------------------*/
/**--------Constructor------------*/
public Group(String givenGroupName) {
groupName = givenGroupName;
}
Student[] students = new Student[4];
/**----------------------------*/
/**--------Method------------*/
void addStudent(Student st) {
students[newStudentCount] = st;
++newStudentCount;
System.out.println("New student: " +st.getName());
}
public String getGroup() {
return "Group = " + groupName;
}
public Student getStudent(){
return students[0];
}
}
In my App class I have this:
public class App {
public static void main(String[] args) {
Group g1 = new Group("Pink Pony Princesses");
Student st1 = new Student("Joshua Mathews");
st1.getName();
g1.addStudent(st1);
Student st2 = new Student("Jame Brooks");
g1.addStudent(st2);
Student st3 = new Student("Mike Myers");
g1.addStudent(st3);
Student st4 = new Student("Christie Richie");
g1.addStudent(st4);
System.out.println(g1.getGroup()+ " " + g1.getStudent());
}
This is my Student class:
public class Student {
/**-------Declaring attributes----*/
String name;
String degree;
int age;
/**----------------------------*/
/**--------Constructor------------*/
Student(String givenName){
name = givenName;
}
Student(String givenName, String givenDegree, int givenAge) {
name = givenName;
degree = givenDegree;
age = givenAge;
}
/**--------- METHODS --------*/
//Array
public final String [] activities = {
"Working on Homework", "Playing a Game", "Taking a Nap"
};
String getInfo(){
return name + age + degree;
}
String getName() {
return name;
}
int getAge(){
return age;
}
String getDegree() {
return degree;
}
String whatsUp(){
Random rand = new Random();
int randomIndex = rand.nextInt(activities.length);
String returnActivity = activities[randomIndex];
return returnActivity;
}
I'm not sure how to call my array to display the 4 names, and not the memory location of them. Any help would be greatly appreciated.
I can deduce a couple of things from your question.
First, you are returning only the student at index 0 of the Student array held within your Group object. If you want to return all students your method signature should have a Student[] as the return type rather than a Student object.
If you follow the above prompt then you will have to iterate through the returned array printing each Student object.
Regardless of which implementation you choose the reason you print out a memory reference rather than a String object is that you have not overridden toString within your Student class.
Something like this will print out Student data when passed to a System.out call:
#Override
public String toString() {
return someStudentData;
}
You can go with what andrewdleach said by implementing toString(). OR
To print all student names your method should be something like:
public String getStudent(){
String studentNames = "";
for(Student stu: students){
studentNames+= stu.getName() + ",";
}
return studentNames;
}
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.