i have trouble with printing an array after reading it in JAVA - java

i have problem with printing the array after reading it. After printing, the address of memory is printed, not value of the array. What can i do for that ?
public class MyClass
{
Student St = new Student();
Student[]Array1 = new Student[10];
void AddList()
{
Scanner Scan = new Scanner(System.in);
for (int i=0; i<Array1.length & i<ArrayF1.length; i++)
{
System.out.println("Enter Student NAME Number " + (i+1) + ":");
Array1[i] = new Student();
Array1[i].setName(Scan.next());
//System.out.println("Enter Student MARK Number " + (i+1) + ":");
//St.setMark(Scan.nextFloat());
}
}
this is my print method. The result of print is like this
(studentproject.Student#1a758cb)
void PrintList()
{
for (int i=0; i<Array1.length; i++)
{
System.out.println(Array1[i]);
}
}
this is my Student Class that i have all my setter and getter method on that ... So i have 3 Class how can i work with this 3 class and in one of them get the data and in another print the Mark data and in third class print the Student Name data ... how can i do that ... i do some code but i dont know is it correct or not ... thanks for your help ...
public class Student
{
private String Name;
private float Mark;
/**
* #return the Name
*/
public String getName() {
return Name;
}
/**
* #param Name the Name to set
*/
public void setName(String Name) {
this.Name = Name;
}
/**
* #return the Mark
*/
public float getMark() {
return Mark;
}
/**
* #param Mark the Mark to set
*/
public void setMark(float Mark) {
this.Mark = Mark;
}
}

Just override the toString() method in Student class, and return the appropriate string you want to get printed when you print an instance.
It may look like: -
#Override
public String toString() {
return "Name: " + studentName;
}
Currently, the default implementation of toString() method of Object class is invoked, and what you are seeing is the format returned from that method, which is of the form - Type#hashCode

Here I've added some stuff how toString() method can be override
public class Student {
private String name;
private int id;
float mark;
public Student() {
}
public Student(String name, int id) {
this.name = name;
this.id = id;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public float getMark() {
return mark;
}
public void setMark(float mark) {
this.mark = mark;
}
#Override
public String toString() {
return "Student[ID:" + id + ",Name:" + name + ",Mark:"+mark+"]";
}
public void printStudentInfo() {
// print all the details of student
}
public static void main(String[] args) {
Student[] students = new Student[10];
Scanner scanner = new Scanner(System.in);
for (int i = 0; i < students.length; i++) {
System.out.println("Enter Student Name " + (i + 1) + ":");
String name = scanner.nextLine();
Student student = new Student(name, i + 1);
System.out.println("Enter Student MARK Number " + (i + 1) + ":");
float mark = scanner.nextFloat();
student.setMark(mark);
students[i]=student;
}
for(Student student:students) {
// by default toStirng method is called
System.out.println(student);
//or you can call like
//student.printStudentInfo();
}
}
}

Related

I can not increase the studentid value in For

I am doing some coding in Java, but it doesn't work:
import java.util.Scanner;
import java.util.Arrays;
public class Main
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
String [] studentId = new String [3];
Student name;
for (int i = 0; i < 3; i++)
{
System.out.print("Enter Name => ");
name = new Student(input.next());
studentId[i] = name.toString();
}
for (int i = 0; i < 3; i++)
{
System.out.println(studentId[i]);
}
}
}
public class Student
{
private static int studentId;
private String name;
public Student(String name)
{
this.name=name;
setStudentId(studentId++);
}
public int getStudentId()
{
return studentId;
}
public void setStudentId(int studentId)
{
this.studentId = studentId;
}
#Override
public String toString()
{
return (this.studentId +" "+ "student is "+ " " + "(" + this.studentId + ")"+ this.name);
}
}
I need to auto-increment the Id when a new entry is created.
I try everything but still cant increased it.
You are using a static variable for everyone's Ids. You need a separate, non-static field to store each individual Id.
public class Student
{
private static int nextAvailableStudentId = 1;
private String name;
private int studentId;
public Student(String name)
{
this.name=name;
setStudentId(nextAvailableStudentId++);
}
public int getStudentId()
{
return studentId;
}
public void setStudentId(int studentId)
{
this.studentId = studentId;
}
#Override
public String toString()
{
return (this.studentId +" "+ "student is "+ " " + "(" + this.studentId + ")"+ this.name);
}
}
In constructor it should be:
{
public Student(String name)
{
this.name=name;
setStudentId(studentId + 1);
}
}

How to add multiple students to student class?

Im trying to create a student class, a course class and the main class. I am trying to add students to the course, and when students are added to the class the number of students in the course should increase, when the the code is run it should print the course details followed by the students in the course.
I have got the following code:
Main class:
public class JavaLecture3 {
public static final int DEBUG = 0;
public static void main(String [] args){
//Student student = new Student(); // Calling default constructor here.
Course course = new Course();
student = new Student(21, "Joe", "CSE", "07447832342");
course = new Course("CSE", "Tom", 5);
System.out.println("Course Information: ");
System.out.println("-------------------");
System.out.println(course);
System.out.println();
System.out.println("Student contains: "); // calls student.toString());
System.out.println("-------------------");
System.out.println(student);
}
}
Course class:
public class Course {
ArrayList<Student> studentList;
private String courseName;
private String teacher;
private int noOfStudents;
//Getters
public String getCourseName(){
return this.courseName;
}
public int getNoOfStudents(){
return this.noOfStudents;
}
public String getTeacher(){
return this.teacher;
}
//Setters
public void setCourseName(String courseName){
this.courseName = courseName;
}
public void setNoOfStudents(int noOfStudents){
this.noOfStudents = noOfStudents;
}
public void setTeacher(String teacher){
this.teacher = teacher;
}
/**
* Default constructor. Populates course name, number of students with defaults
*
*/
public Course(){
this.noOfStudents = 0;
this.courseName = "Not Set";
this.teacher = "Not Set";
studentList = new ArrayList<Student>();
}
/**
* Constructor with parameters
* #param noOfStudents integer
* #param courseName String with the Course name
* #param teacher String with the teacher
*/
public Course(String courseName, String teacher, int noOfStudents){
this.courseName = courseName;
this.teacher = teacher;
noOfStudents = noOfStudents;
studentList = new ArrayList<Student>();
}
public static void addStudent(Student newStudent){
if(studentList.size()==noOfStudents){
System.out.println("The class is full, you cannot enrol.");
}
else {
studentList.add(newStudent);
}
}
public String toString() {
return "Course Name: " + this.courseName + " Teacher: " + this.teacher
+ " Number of Students: " + this.noOfStudents;
}
}
Student class:
public class Student {
private String name;
private int age;
public String gender = "na";
private String course;
private String phoneNo;
public static int instances = 0;
// Getters
public int getAge(){
return this.age;
}
public String getName(){
return this.name;
}
public String getCourse(){
return this.course;
}
public String getPhoneNo(){
return this.phoneNo;
}
// Setters
public void setAge(int age){
this.age = age;
}
public void setName(String name){
if (JavaLecture3.DEBUG > 3) System.out.println("In Student.setName. Name = "+ name);
this.name = name;
}
public void setCourse(String course){
this.course = course;
}
public void setPhoneNo(String phoneNo){
this.phoneNo = phoneNo;
}
/**
* Default constructor. Populates name,age,gender,course and phone Number
* with defaults
*/
public Student(){
instances++;
this.age = 18;
this.name = "Not Set";
this.gender = "Not Set";
this.course = "Not Set";
this.phoneNo = "Not Set";
}
/**
* Constructor with parameters
* #param age integer
* #param name String with the name
* #param course String with course name
* #param phoneNo String with phone number
*/
public Student(int age, String name, String course, String phoneNo){
this.age = age;
this.name = name;
this.course = course;
this.phoneNo = phoneNo;
}
/**
* Gender constructor
* #param gender
*/
public Student(String gender){
this(); // Must be the first line!
this.gender = gender;
}
protected void finalize() throws Throwable{
//do finalization here
instances--;
super.finalize(); //not necessary if extending Object.
}
public String toString (){
return "Name: " + this.name + " Age: " + this.age + " Gender: "
+ this.gender + " Course: " + this.course + " Phone number: "
+ this.phoneNo;
}
}
Reference:
http://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html?is-external=true
Course.getNoOfStudents should just return studentList.size(). No need to maintain a separate variable.
To print a list of students (from Course):
for(int i=0;i<studentList.size();i++) System.out.println(studentList.get(i));
Since you initialized the array list in the Course class, you should add the students to it. You should create a method in Course that adds an object to the array list such as:
public void addStudent(Student s){
studentList.add(s);
noOfStudents++;
}
To add multiple students:
public void addStudents(Student[] students){
for(int i = 0; i < students.length; i++){
studentList.add(students[i]);
}
}
You're almost there, just use the .add method made for you in the array list.
public class JavaLecture3 {
public static final int DEBUG = 0;
public static void main(String [] args){
Student student = new Student(); // Calling default constructor here.
Course course = new Course();
student = new Student(21, "Joe", "CSE", "07447832342");
course = new Course("CSE", "Tom", 5);
course.addStudent(student);
System.out.println("Course Information: ");
System.out.println("-------------------");
System.out.println(course);
System.out.println();
System.out.println("Student contains: "); // calls student.toString());
System.out.println("-------------------");
System.out.println(student);
}
}
public class Course {
List<Student> studentList;
private String courseName;
private String teacher;
private int noOfStudents;
// Getters
public String getCourseName() {
return this.courseName;
}
public int getNoOfStudents() {
return this.noOfStudents;
}
public String getTeacher() {
return this.teacher;
}
// Setters
public void setCourseName(String courseName) {
this.courseName = courseName;
}
public void setNoOfStudents(int noOfStudents) {
this.noOfStudents = noOfStudents;
}
public void setTeacher(String teacher) {
this.teacher = teacher;
}
/**
* Default constructor. Populates course name, number of students with
* defaults
*
*/
public Course() {
this.noOfStudents = 0;
this.courseName = "Not Set";
this.teacher = "Not Set";
studentList = new ArrayList<Student>();
}
/**
* Constructor with parameters
*
* #param noOfStudents
* integer
* #param courseName
* String with the Course name
* #param teacher
* String with the teacher
*/
public Course(String courseName, String teacher, int noOfStudents) {
this.courseName = courseName;
this.teacher = teacher;
this.noOfStudents = noOfStudents;
studentList = new ArrayList<Student>();
}
public void addStudent(Student newStudent) {
if (studentList.size() == noOfStudents) {
System.out.println("The class is full, you cannot enrol.");
} else {
studentList.add(newStudent);
}
}
#Override
public String toString() {
return "Course Name: " + this.courseName + " Teacher: " + this.teacher
+ " Number of Students: " + studentList.size();
}
}
public class Student {
private String name;
private int age;
public String gender = "na";
private String course;
private String phoneNo;
public static int instances = 0;
// Getters
public int getAge() {
return this.age;
}
public String getName() {
return this.name;
}
public String getCourse() {
return this.course;
}
public String getPhoneNo() {
return this.phoneNo;
}
// Setters
public void setAge(int age) {
this.age = age;
}
public void setName(String name) {
if (JavaLecture3.DEBUG > 3)
System.out.println("In Student.setName. Name = " + name);
this.name = name;
}
public void setCourse(String course) {
this.course = course;
}
public void setPhoneNo(String phoneNo) {
this.phoneNo = phoneNo;
}
/**
* Default constructor. Populates name,age,gender,course and phone Number
* with defaults
*/
public Student() {
instances++;
this.age = 18;
this.name = "Not Set";
this.gender = "Not Set";
this.course = "Not Set";
this.phoneNo = "Not Set";
}
/**
* Constructor with parameters
*
* #param age
* integer
* #param name
* String with the name
* #param course
* String with course name
* #param phoneNo
* String with phone number
*/
public Student(int age, String name, String course, String phoneNo) {
this.age = age;
this.name = name;
this.course = course;
this.phoneNo = phoneNo;
}
/**
* Gender constructor
*
* #param gender
*/
public Student(String gender) {
this(); // Must be the first line!
this.gender = gender;
}
protected void finalize() throws Throwable {
// do finalization here
instances--;
super.finalize(); // not necessary if extending Object.
}
public String toString() {
return "Name: " + this.name + " Age: " + this.age + " Gender: "
+ this.gender + " Course: " + this.course + " Phone number: "
+ this.phoneNo;
}
}
public class JavaLecture3 {
public static final int DEBUG = 0;
public static void main(String [] args){
//Create course object
Course course = new Course("CSE", "Tom", 5);
Scanner scanner = new Scanner(System.in);
String cmd = "Yes";
while(cmd.equals("Yes")){
Student student = new Student();
System.out.print("Enter a new student? ");
cmd = scanner.next();
if (cmd.equals("Yes")){
//Read student name
System.out.print("Enter a student name: ");
String name = scanner.next();
student.setName(name);
//Read student Age
System.out.print("Enter a student age: ");
int age = scanner.nextInt();
student.setAge(age);
//Read student Course
System.out.print("Enter a student course: ");
String stdent_course = scanner.next();
student.setCourse(stdent_course);
//register the student to the class
course.addStudent(student);
}
}
scanner.close();
System.out.println("Course Information: ");
System.out.println("-------------------");
System.out.println(course.toString());
System.out.println();
}
}
I reworked a bit your toString() method from Course class. This should print the list of students attending a class.
public String toString (){
String ret_value = "Name: " + this.name + " Age: " + this.age + " Gender: "
+ this.gender + " Course: " + this.course + " Phone number: "
+ this.phoneNo + " Students attending this course:";
for (Student student: studentList) {
ret_value = ret_value + " " + Student.getName();
}
return ret_value;
}

Getting NullPointerException errors when trying to use multiple classes for the first time

I am trying to get my addStudent() method in the Roster class to work here.
It's supposed to add a given student to this roster. If the student is already on the roster, or the numStudents == stopPoint, it doesn't change the roster and returns false. If it is successful it returns true.
Roster Class:
public class Roster {
Student[] students;
int numStudents;
int stopPoint;
Course course;
//constructor for this class initialize this roster to empty
public Roster(int stopPoint, Course course)
{
this.stopPoint = stopPoint;
this.course = course;
}
//returns a string that represents the object for printing
public String toString()
{
String res = "";
for(int j = 0; j < numStudents; j++)
{
res = res + "\n" + students[j].toString();
}
return course + " " + numStudents + "/" + stopPoint+res;
}
//returns true if and only if the number of students in it is at stopPoint
public boolean isFull(int numStudents, int stopPoint)
{
if (numStudents == stopPoint)
{
return true;
}
else
return false;
}
/*add given student to this roster if student already on roster
or numStudents already == stopPoint, will not change roster and return
false but return true if successful, else false
*/
public boolean addStudent(Student student)
{
if(this.numStudents < this.stopPoint)
{
this.students[numStudents] = student; // here is where I get the error
this.numStudents++;
return true;
}
else
return false;
}
}
Testing Class:
public class TestRoster
{
public static void main(String[] args)
{
Student s1 = new Student("John","Doe");
Course c1 = new Course(198, 111);
Roster r1 = new Roster(4, c1);
System.out.println(r1);
testAdd(r1, s1);
}
private static void testAdd(Roster r, Student s)
{
System.out.println(s.familyName+" "+r.addStudent(s));
System.out.println(r);
}
}
Student Class:
public class Student
{
String personalName;
String familyName;
public Student(String pName, String fName)
{
personalName = pName;
familyName = fName;
}
public String toString( )
{
return "Student: " + familyName + ", "+ personalName;
}
}
Lastly, the Course Class:
public class Course
{
int deptNum;
int courseNum;
public Course(int deptNum, int courseNum)
{
this.deptNum = deptNum;
this.courseNum = courseNum;
}
public String toString( )
{
return deptNum + ":" + courseNum;
}
}
Here is the error:
Exception in thread "main" java.lang.NullPointerException
at assign4.Roster.addStudent(Roster.java:56)
at assign4.TestRoster.testAdd(TestRoster.java:17)
at assign4.TestRoster.main(TestRoster.java:13)
Java Result: 1`
The other answers suggest using an arbitrary number for the array instansiation, this is not a good idea as you never know if it will be enough.
Your Roster class knows how many students there should be (via the constructor), you should initialize the Student array with stopPoint:
Student[] students;
int numStudents;
int stopPoint;
Course course;
public Roster(int stopPoint, Course course)
{
this.stopPoint = stopPoint;
this.course = course;
this.students = new Student[this.stopPoint]
}
Since you can't touch your class variables, you can and should initialize the array within the constructor.

Printing arrays - overriding toString() method

I have two different class, Student and StudentTest - the Student class has;
public class Student {
// Data Members
private String name; // The name of this student
private long idNumber; // The ID number of this student
// Constructs a new Student with passed name and ID number parameters.
public Student(String studentName, long studentIDNumber) {
name = studentName;
idNumber = studentIDNumber;
}
// Returns the name of this student.
public String getName() {
return name;
}
// Returns the ID number of this student.
public long getIDNumber() {
return idNumber;
}
// Sets the name of this student.
public void setName(String studentName) {
name = studentName;
}
// Sets the ID number of this student.
public void setIDNumber(long studentIDNumber) {
idNumber = studentIDNumber;
}
#Override
public String toString(){
return "Name: " + this.name;
}
} // end class
And the StudentTest class has 3 different methods, 1. to ask the user to enter the size of an array and then create an array of type Student, 2. to ask the user to populate the array with names and ID numbers, 3. to display the contents of the array.
import java.util.Scanner;
public class StudentTest {
// Main method.
public static void main(String [] args) {
Student[] students = createArray();
populateArray(students);
displayArray(students);
}
// Method that asks user for size of array.
public static Student[] createArray() {
System.out.println("Enter size of array: ");
Scanner userInputEntry = new Scanner(System.in);
int inputLength = userInputEntry.nextInt();
Student students[] = new Student[inputLength];
return students;
}
// Method that asks user to populate array.
public static void populateArray(Student [] array) {
for(int i = 0; i < array.length; i++) {
array[i] = new Student();
System.out.println("Enter student name: ");
Scanner userInputEntry = new Scanner(System.in);
array[i].setName(userInputEntry.next());
System.out.println("Enter student ID number: ");
array[i].setIDNumber(userInputEntry.nextLong());
}
}
// Method that displays contents of array.
public static void displayArray(Student[] array) {
for(int i = 0; i < array.length; i++){
System.out.println(array[i].toString());
}
}
}
When I try to run it, I get an error about the
array[i] = new Student();
in the for loop in the second method.
How would you expect this to work ?
#Override
public void toString(){
return "Name: " + this.name;
}
It should give you an compile error. You are trying to send a string back and the return type is void.
Change it to
#Override
public String toString(){
return "Name: " + this.name;
}
Change you main method to
// Main method.
public static void main(String [] args) {
Student[] students = createArray();
populateArray(students);
displayArray(students)
}

Mutator methods not storing values for the class that I have just made?

Here is the class:
package employee;
public class Employee
{
private String name, department,position;
private int idNumber;
public Employee(String n, int id, String depart,String pos)
{
n= name;
id=idNumber;
depart=department;
pos=position;
}
public Employee(String n, int id)
{
n= name;
id=idNumber;
department="";
position="";
}
public Employee()
{
name="";
idNumber=0;
department="";
position="";
}
public void setName(String n)
{
n=name;
}
public void setDepartment(String depart)
{
depart=department;
}
public void setPosition(String pos)
{
pos=position;
}
public void setId(int id)
{
id=idNumber;
}
public String getName()
{
System.out.println();
return name;
}
public String getDepartment()
{
return department;
}
public String getPosition()
{
return position;
}
public int getId()
{
return idNumber;
}
}
Here is the program:
package employee;
public class RunEmployee
{
public static void main(String[] args)
{
Employee first= new Employee();
first.setName("Susan Myers");
first.setId(47899);
first.setDepartment("Accounting");
first.setPosition("Vice President");
Employee sec= new Employee("Mark Jones",39119,"IT","Programmer");
Employee third= new Employee("Joy Rogers", 81774);
third.setDepartment("Manfacturing");
third.setPosition("Engineer");
/*Printing employee ones information*/
System.out.print("Employee #1- using the no-arg constructor.");
System.out.println("Name: " + first.getName());
System.out.println("Id Number: "+ first.getId());
System.out.println("Department: " + first.getDepartment());
System.out.println("Position: "+ first.getPosition());
/*Printing employee twos information*/
System.out.println("Name: " + sec.getName());
System.out.println("Id Number: "+ sec.getId());
System.out.println("Department: " + sec.getDepartment());
System.out.println("Position: "+ sec.getPosition());
/*Printing employee threes information*/
System.out.print("Employee #3- using a constructor that accepts the name"
+ "and ID number only.");
System.out.println("Name: " + third.getName());
System.out.println("Id Number: "+ third.getId());
System.out.println("Department:" + third.getDepartment());
System.out.println("Position: "+ third.getPosition());
}
}
For this project, I am simply trying to store values into the constructor in different ways. However, my output is showing that my mutator methods are not storing any values. I tried to post my output but I do not have the reputation points. Basically, all the the values for the things I tried to arguments say zero or null.
You've got your assignments backwards!
n = name; puts the value of name to n, not the other way around.
You are assigning the value from the Employee instance to your passed in parameters. To prevent that, it is probably a good idea to use this -
this.name = n; // <-- assign n to the name field of the current instance.
In your example code, this.n would have given you a compile time error.

Categories