Question will be below.
public class University {
ArrayList<Student> students;
public University() {
students = new ArrayList<Student>();
}
public void addStudent(Student students) {
this.students.add(students);
}}
public class Student {
String name;
String studentID;
static int studentNumber = 0;
Student(String name, String sID){
this.name = name;
this.studentID = sID;
studentNumber++;
}}
public class TestUniversity {
public static void main(String[] args) {
University universityRegister = new University();
Student studentRegister = new Student("Rachel Green", "a1234");
universityRegister.addStudent(studentRegister);
studentRegister = new Student("Monica Geller", "a12345");
universityRegister.addStudent(studentRegister);
studentRegister = new Student("Ross Geller", "a1111");
universityRegister.addStudent(studentRegister);
System.out.println("Number of student in University: " + Student.studentNumber);
}}
A. I created 3 classes, 1.Student, 2.University, 3.UniversityTester, in 3 different files.
B. I created 3 objects of type Studnet, and stored them in the University class as an ArrayList.
I would like to know how I can print the ArrayList of the students including all information from the UniversityTester class? In the future, I will create another object called Stuff and I will store it in the University class as an ArrayList stuffList. Therefore, I don't want to print the students list from class Student.
Override toString() method in Student class as follows:
import java.util.StringJoiner;
public class Student {
String name;
String studentID;
static int studentNumber = 0;
Student(String name, String sID) {
this.name = name;
this.studentID = sID;
studentNumber++;
}
#Override
public String toString() {
return new StringJoiner(", ", Student.class.getSimpleName() + "[", "]")
.add("name='" + name + "'")
.add("studentID='" + studentID + "'")
.toString();
}
}
Now you can print the array list as follows in TestUniversity:
System.out.println("Student Details: " + universityRegister.students);
Add this to your student class:
#Override
public String toString() {
return String.format("Student: %s , StudentID: %s", name, studentID);
}
And then you can print the entire array like this:
System.out.println("Students: " universityRegister.students);
//Or like this:
for(Student st: universityRegister.students){
System.out.println(st);
}
Related
I have created a class employee in Java, where each object of the class stands for a staff. The objects take 3 parameters - Name, Dept. and Salary. The program looks like this:
public class employee
{
String name;
int salary;
String dept;
employee staff1 = new employee("x","IT",100000);
employee staff2 = new employee("y", "HR", 200000);
public employee(String n, String d, int s)
{
this.name= n;
this.salary= s;
this.dept = d;
}
public static void main (String args [])
{
}
public void Display()
{
}
}
I want to make a method (the Display method in the code) which takes the object name as a parameter (the code does not have a parameter) and returns (or prints) its data values. Please also tell me what should come in the main method. Thanks in advance.
You can use this -
public class employee {
String name;
int salary;
String dept;
public employee(String n, String d, int s) {
this.name = n;
this.salary = s;
this.dept = d;
}
public static void main(String args[]) {
employee staff1 = new employee("x", "IT", 100000);
employee staff2 = new employee("y", "HR", 200000);
Display(staff1);
Display(staff2);
}
public static void Display(employee object) {
System.out.println("name='" + object.name + '\'' +
", salary=" + object.salary +
", dept='" + object.dept + '\'');
}
}
I am designing a group generator that takes in preferences such as “mix gender”, “mix nationality”... I am putting a list of student names, followed by nationality and gene set, in an arraylist. What is the easiest way to generate groups, based on user input, that each group consists of people from different nationalities, or balanced gender.
public ArrayList<String> readEachWord(String className)
{
ArrayList<String> readword = new ArrayList<String>();
Scanner sc2 = null;
try {
sc2 = new Scanner(new File(className + ".txt"));
} catch (FileNotFoundException e) {
System.out.println("error, didnt find file");
e.printStackTrace();
}
while (sc2.hasNextLine()) {
Scanner s2 = new Scanner(sc2.nextLine());
while (s2.hasNext()) {
String s = s2.next();
readword.add(s);
}
}
return readword;
}
I am using this to read a text file, and on each line, I have each student's name nationality and gender. I put them into an ArrayList and am right now trying to figure out how to evenly distribute them based on the user-desired group numbers.
I am using a txt file to store all the information since this group generator is customized for my school.
You can use the groupinBy method
basic tutorial
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
class Scratch {
public static void main(String[] args) {
String student1 = "Macie American Female";
String student2 = "Yago Brazilian Male";
String student3 = "Tom American Male";
List<String> students = Arrays.asList(student1, student2, student3);
System.out.println(groupByGender(students));
System.out.println(groupByNationality(students));
}
private static Map<String, List<Student>> groupByNationality(List<String> students) {
return students.stream().map(s -> mapToStudent(s)).collect(Collectors.groupingBy(Student::getNationality));
}
private static Map<String, List<Student>> groupByGender(List<String> students) {
return students.stream().map(s -> mapToStudent(s)).collect(Collectors.groupingBy(Student::getGender));
}
private static Student mapToStudent(String s) {
String[] ss = s.split(" ");
Student student = new Student();
student.setName(ss[0]);
student.setNationality(ss[1]);
student.setGender(ss[2]);
return student;
}
private static class Student {
String name;
String nationality;
String gender;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getNationality() {
return nationality;
}
public void setNationality(String nationality) {
this.nationality = nationality;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
#Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", nationality='" + nationality + '\'' +
", gender='" + gender + '\'' +
'}';
}
}
}
First of all, it would be better if you put your while loop inside the try block because you don't want to get there if the file hasn't been found.
Second, you don't need to create a new instance of Scanner just to read every line. You can simply read your file word by word:
while (sc2.hasNext())
readword.add(sc2.next());
To group the students according to their nationality, you can do something like that:
String nationality = [UserInput] ;
List<String> group = new ArrayList<>();
for (int i = 0; i < readword.size(); i++)
if (readword.get(i + 1).equals(nationality)
group.add(readword.get(i));
class Student {
int rollno;
String name, address;
// Constructor
public Student(int rollno, String name, String address) {
this.rollno = rollno;
this.name = name;
this.address = address;
}
// Used to print student details in main()
public String toString() {
return this.rollno + " " + this.name +
" " + this.address;
}
}
class tools {
class Sortbyroll implements Comparator<Student>{
// Used for sorting in ascending order of
// roll number
public int compare(Student a, Student b) {
return a.rollno - b.rollno;
}
}
public ArrayList<Student> sort(ArrayList<Student> arr){
Collections.sort(arr, new Sortbyroll());
return arr;
}
}
class Main
{
public static void main (String[] args) {
ArrayList<Student> ar = new ArrayList<Student>();
ar.add(new Student(111, "bbbb", "london"));
ar.add(new Student(131, "aaaa", "nyc"));
ar.add(new Student(121, "cccc", "jaipur"));
System.out.println("Unsorted");
for (int i=0; i<ar.size(); i++)
System.out.println(ar.get(i));
ar = tools.sort(ar);
System.out.println("\nSorted by rollno");
for (int i=0; i<ar.size(); i++)
System.out.println(ar.get(i));
}
}
I can sort it if i put the Sortbyroll outside the tools
But i can only submit the student.java file and the tool.java file
so basically i have to do everything inside student class and tool class
and main function cannot be edited...
if i put the sort function static
it said "error: non-static variable this cannot be referenced from a static context"
what should i do ...
you can use compareTo method inside of Student class. change your student model:
class Student implements Comparable<Student>{
int rollno;
String name, address;
// Constructor
public Student(int rollno, String name, String address) {
this.rollno = rollno;
this.name = name;
this.address = address;
}
// Used to print student details in main()
public String toString() {
return this.rollno + " " + this.name +
" " + this.address;
}
public int compareTo(Student model) {
return model.rollno.compareTo(rollno);
}
}
and in main use Collections.sort(response); to sort Array List
Replace your Tools class with the following code.
class tools {
static public ArrayList<Student> sort(ArrayList<Student> arr){
Collections.sort(arr, new Comparator(){
#Override
public int compare(Object s1, Object s2) {
return Integer.compare(((Student)s1).rollno, ((Student)s2).rollno);
}
});
return arr;
}
}
Here, I have a superclass called 'Staff'. My main method is in a separate class called 'Program_2A'. The filename given is Program_2A.java. Eclipse is showing an error in the second line of the program saying
Link all references for a local rename (does not change references in other files)
I don't understand what's wrong by having the main class, not as a superclass.
Here is the code:
import java.util.*;
public class Staff {
private int Staff_ID;
private String Name;
private int Phone;
private int Salary;
public Staff(int staff_id, String name, int phone, int salary)
{
Staff_ID = staff_id;
Name = name;
Phone = phone;
Salary = salary;
}
public void display()
{
System.out.println("\t" + Staff_ID + "\t" + Name + "\t" + Phone + "\t" + Salary);
}
}
class Teaching extends Staff
{
private String Domain;
private int Publication;
public Teaching(int staff_id, String name, int phone, int salary, String domain, int publication) {
super(staff_id,name,phone,salary);
Domain = domain;
Publication = publication;
}
public void display() {
super.display();
System.out.println("\t" + Domain + "\t" + Publication);
}
}
class Technical extends Staff
{
private String Skills;
public Technical(int staff_id, String name, int phone, int salary, String skills) {
super(staff_id,name,phone,salary);
Skills = skills;
}
public void display() {
super.display();
System.out.println("\t" + Skills);
}
}
class Contract extends Staff
{
private int Contract;
public Contract(int staff_id, String name, int phone, int salary, int contract) {
super(staff_id,name,phone,salary);
Contract = contract;
}
public void display() {
super.display();
System.out.println("\t" + Contract);
}
}
class Program_2A {
public static void main(String[] args) {
Staff St[] = new Staff[3];
St[0] = new Teaching(1, "ABC", 1234, 10000, "CSE", 3);
St[1] = new Technical(2, "DEF", 5678, 200000, "C++");
St[2] = new Contract(3, "GHI", 9012, 50000, 3);
System.out.println("STAFF ID \t NAME \t PHONE \t SALARY \t DOMAIN \t PUBLICATIONS \t SKILLS \t PERIOD");
for(int i=0;i<3;i++) {
St[i].display();
System.out.println();
}
}
}
In Java, one file can only contain one public class.
So please change class Program_2A to public class Program_2A and remove public keyword before Staff class.
This question already has answers here:
How do I print my Java object without getting "SomeType#2f92e0f4"?
(13 answers)
Closed 7 years ago.
I need to be able to print out the Student objects(all variables) in my array list. Is this possible? When i try to print it outputs this sort of thing e.g student.Student#82701e. I think it's hexadecimal or something
This is my code:
package student;
public class Student {
private String studentName;
private String studentNo;
private String email;
private int year;
public Student() {
this.studentName = null;
this.studentNo = null;
this.email = null;
this.year = -1;
}
public Student(String nName, String nNum, String nEmail, int nYr) {
this.studentName = nName;
this.studentNo = nNum;
this.email = nEmail;
this.year = nYr;
}
public void setStudentName(String newStudentName) {
this.studentName = newStudentName;
}
public void setStudentNo(String newStudentNo) {
this.studentNo = newStudentNo;
}
public void setEmail(String newEmail) {
this.email = newEmail;
}
public void setYear(int newYear) {
this.year = newYear;
}
public String getStudentName() {
return studentName;
}
public String getStudentNo() {
return studentNo;
}
public String getEmail() {
return email;
}
public int getYear() {
return year;
}
}
package student;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class studentTest {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
List<Student> Students = new ArrayList();
Student student1 = new Student();
student1.setStudentName("Bob Marley");
student1.setStudentNo("N0002");
student1.setEmail("student2#student.com");
student1.setYear(2);
Students.add(student1);
Student student2 = new Student();
student2.setStudentName("Bill Harvey");
student2.setStudentNo("N0003");
student2.setEmail("student3#student.com");
student2.setYear(2);
Students.add(student2);
Student student3 = new Student();
student3.setStudentName("John Beans");
student3.setStudentNo("N0004");
student3.setEmail("student4#student.com");
student3.setYear(2);
Students.add(student3);
System.out.println("Add new students: ");
System.out.println("Enter number of students to add: ");
int countStudents = input.nextInt();
for (int i = 0; i < countStudents; i++) {
Student newStudents = new Student();
System.out.println("Enter details for student: " + (i + 1));
System.out.println("Enter name: ");
newStudents.setStudentName(input.next());
System.out.println("Enter Number: ");
newStudents.setStudentNo(input.next());System.out.println("Search by student number: ");
System.out.println("Enter email: ");
newStudents.setEmail(input.next());
System.out.println("Enter year: ");
newStudents.setYear(input.nextInt());
Students.add(newStudents);
}
}
}
Override toString() method in Student class as below:
#Override
public String toString() {
return ("StudentName:"+this.getStudentName()+
" Student No: "+ this.getStudentNo() +
" Email: "+ this.getEmail() +
" Year : " + this.getYear());
}
Whenever you print any instance of your class, the default toString implementation of Object class is called, which returns the representation that you are getting.
It contains two parts: - Type and Hashcode
So, in student.Student#82701e that you get as output ->
student.Student is the Type, and
82701e is the HashCode
So, you need to override a toString method in your Student class to get required String representation: -
#Override
public String toString() {
return "Student No: " + this.getStudentNo() +
", Student Name: " + this.getStudentName();
}
So, when from your main class, you print your ArrayList, it will invoke the toString method for each instance, that you overrided rather than the one in Object class: -
List<Student> students = new ArrayList();
// You can directly print your ArrayList
System.out.println(students);
// Or, iterate through it to print each instance
for(Student student: students) {
System.out.println(student); // Will invoke overrided `toString()` method
}
In both the above cases, the toString method overrided in Student class will be invoked and appropriate representation of each instance will be printed.
You have to define public String toString() method in your Student class. For example:
public String toString() {
return "Student: " + studentName + ", " + studentNo;
}