cannot set the value of string from the main class into setter - java

public class StudentTest{
public static void main(String args[]){
UnderGrad uG1 = new UnderGrad();
uG1.setName("John");
uG1.setMatric("0192345");
System.out.println("Undergarduate Student Info");
uG1.setCourse(new Course("CS1103",3));
uG1.setCourse(new Course("IT4504",3));
uG1.displayStudentInfo();
System.out.println(" ");
PostGrad pG1 = new PostGrad();
pG1.setName("Sam");
pG1.setMatric("G015466");
pG1.setResearch("Empirical Software Engineering");
pG1.setResearch("Data Mining");
System.out.println("Postgrad Student Info");
pG1.displayStudentInfo();
}
}
public class Course{
private String courseName;
private int crhour;
public Course(String n, int c){
courseName = n;
crhour = c;
}
public void setCourseName(String course){
courseName = course;
}
public String getCourseName(){
return courseName;
}
public void setCreditH(int c){
crhour = c;
}
}
public class Student{
private String matric ="-matric required-";
private String name="-name required-";
public Student(){
}
public void setName(String n){
if (n.matches("[a-zA-Z]+") == false)
System.out.println("Invalid Name");
else
name = n;
}
public String getName(){
return name;}
public void setMatric(String m){
matric = m;}
public String getMatric(){
return matric;}
}
public class UnderGrad extends Student{
private Course courseList[];
private int index = 0;
public UnderGrad(){
Course courseList[] =new Course[7];}
public void setCourse(Course courseName){
//Course courseList[]= new Course[2];
}
public Course[] getCourse(){
return courseList;}
public void displayStudentInfo(){
System.out.println("Name: "+getName());
System.out.println("Matric: "+getMatric());
System.out.println("Course List: "+getCourse());
}}
public class PostGrad extends Student{
private String researchArea[];
private int index = 0;
public PostGrad()
{
researchArea = new String[5];
}
public void setResearch(String research){
for(index=0;index<2;index++){
researchArea[index]=research;}
}
public String[] getResearch(){
return researchArea;}
public void displayStudentInfo(){
System.out.println("Name: "+getName());
System.out.println("Matric: "+getMatric());
System.out.println("Research List: "+getResearch());
}}
Output:
Undergarduate Student Info
Name: John
Matric: 0192345
Course List: null
Postgrad Student Info
Name: Sam
Matric: G015466
Course List: [Ljava.lang.String;#2ac9fefa
The problem I cant get the value of String of the course an the research. What should I do?Should I use super reference?

Here:
System.out.println("Course List: "+getCourse());
You're printing out the default toString() returned by an array of String. Don't do that. Iterate through the array and print each item or else use java.util.Arrays.toString(...).
System.out.println("Course List: "+ java.util.Arrays.toString(getCourse()));
You will also need to give your Course class a valid toString() method, one that returns the courseName and perhaps the credit hours. Also I would change the course field to courses or courseList to reflect that it does not represent one single course but rather a collection of courses. Likewise the getter method should reflect the field name change.

Related

adding multiple objects to ArrayList is not printing very well

import java.util.ArrayList;
import java.util.Scanner;
public class Student {
static String studentNum;
static int age;
static String Name;
Student(int Age, String Name){
this.Name = Name;
this.age = Age;
}
public static String input_read() {
Scanner sc = new Scanner(System.in);
if (sc.hasNext()) {
studentNum = sc.next();
} else {
sc.close();
}
return studentNum;
}
public static int setAge() {
System.out.println("Enter the age of the Student");
return Integer.valueOf(input_read());
}
public static String setName() {
System.out.println("Enter the name of the Student");
return input_read();
}
public static int getAge() {
return age;
}
public static String getName() {
return Name;
}
public static void main(String[] args) {
ArrayList<Student> ar = new ArrayList();
for (int i=0; i<2; i++) {
Student s1= new Student(setAge(), setName());
ar.add(s1);
}
for (Student each :ar){
System.out.println(each.getName());
System.out.println(each.getAge());
}
}
}
I am new guy in Java. I created a program to add student age and name. This program output is printing only last object 2 times. It is not printing all the objects in the list. Anybody know why?
You should remove the keyword static from your member variables.
That is causing them to be shared across all instances.
See here: What does the 'static' keyword do in a class?

Sort ArrayList in Java

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;
}
}

java - Student Class Compile Errror

i have written this java code and i get an error can anyone tell me why? the code is to create a student class and will be tested.
i am new to java so any help will be appreciated
this is the code:
import java.io.*;
import java.util.*;
public class Student {
private static void main(String[] args)
{
private String forName;
private String surName;
private String studentID;
private String degreeScheme;
//This is the Constructor of the
class Student
public Student(String name) {
this.forName = forName;
}
//Assign the surname of the student
public void stuSurname (String
stuSurname){
surName = stuSurname;
}
//Assign the student ID to the
student
public void stuID (String stuID){
studentID = stuID;
}
//Assign the Degree of the Student
public void stuDegree (String
stuDegree){
degreeScheme = stuDegree;
}
//Print the student details
public void printStudent(){
System.out.println("Forname:"+ forName);
System.out.println("Surename:"+ surName);
System.out.println("Student
ID:"+ studentID);
System.out.println("Degree
Scheme:"+ degreeScheme);
}
// setter
public void setForName(String
forName) {
this.forName = forName;
}
// getter
public String getForName() {
return forName;
}
}
}
and this is the error that i get:
TheRealFawcett:lab8 therealfawcett$ javac
Student.java
Student.java:8: error: illegal start of
expression
private String forName;
^
Student.java:49: error: class, interface, or enum
expected
}
^
2 errors
TheRealFawcett:lab8 therealfawcett$
i don't understand why i get this error as i thought my main method was correct.
Fields belong to the Class and not to to the method. Also methods have to be at class level.
In your code all fields and methods are in the main method, which is not correct.
The following snippet shows a correct version:
public class Student {
private static void main(String[] args) {
Student student = new Student("Charles");
}
private String forName;
private String surName;
private String studentID;
private String degreeScheme;
//This is the Constructor of the
public Student(String name) {
this.forName = forName;
}
//Assign the surname of the student
public void stuSurname(String stuSurname) {
surName = stuSurname;
}
//Assign the student ID to the student
public void stuID(String stuID) {
studentID = stuID;
}
//Assign the Degree of the Student
public void stuDegree(String stuDegree) {
degreeScheme = stuDegree;
}
//Print the student details
public void printStudent() {
System.out.println("Forname:" + forName);
System.out.println("Surename:" + surName);
System.out.println("Student ID:" + studentID);
System.out.println("Degree Scheme:" + degreeScheme);
}
// setter
public void setForName(String forName) {
this.forName = forName;
}
// getter
public String getForName() {
return forName;
}
}
To learn more about the Java Classes and Objects you can follow this official tutorial.

How to work with array,a value to hold an array of elements

public class Student implements Comparable<Student> {
String fName;
String sName;
String subject[];
int subjectValuation;
public Student(String fName, String sName, String[] subject, int subjectValuation) {
this.fName = fName;
this.sName = sName;
this.subject = subject;
this.subjectValuation = subjectValuation;
}
public String[] getSubject() {
return subject;
}
public String getfName(){
return fName;
}
public String getsName(){
return sName;
}
public void setSubject(String[] subject) {
this.subject = subject;
}
public int getSubjectValuation(){
return subjectValuation;
}
public void setSubjectValuation(int subjectValuation){
this.subjectValuation=subjectValuation;
}
public String toString(){
return " fname "+getfName()+ " sname " +getsName()+ " subjects "+subject+ " valuation "+subjectValuation;
}
public boolean equals(Object o){
if(o!=null && o instanceof Student){
Student s=(Student) o;
if(this.getfName().equalsIgnoreCase(s.fName) && this.getsName().equalsIgnoreCase(s.sName))
return true;
else
return false;
}
return false;
}
public int compareTo(Student o){
return this.subjectValuation-o.subjectValuation;
}
}
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
public class Catalogue {
private ArrayList<Student> s=new ArrayList<>();
//performing 1.
void add(String firstName,String secondName){
s.add(new Student(firstName,secondName,[0],0));
}
//performing 2
void add2(String firstname,String secondName,String subject[],int valuation){
Student accSearch=search(firstname,secondName);
if(accSearch!=null) {
accSearch.setSubject(subject);
accSearch.setSubjectValuation(valuation);
}
else{
System.out.println("couldn't find it");
}
}
//performing 3
void delete(String firstName,String secondName){
Student n=new Student(firstName,secondName,[0],0);
while(s.contains(n)) {
s.remove(n);
}
}
//searching my Student
public Student search(String firstName,String secondName){
for(Student m:s){
if(m.getfName().equalsIgnoreCase(firstName) && m.getsName().equalsIgnoreCase(secondName))
return m;
}
return null;
}
public void listInformation(String firstName,String secondName){
for(Student m:s){
if(m.getfName().equalsIgnoreCase(firstName) &&
m.getsName().equalsIgnoreCase(secondName))
System.out.println(m);
}
}
void printall(){
for(Student m:s){
System.out.println(m);
}
}
//performing 4.
void listValuation(String firstName,String secondName) {
Student searchingFor = search(firstName, secondName);
Iterator<Student> i = s.iterator();
while (i.hasNext()) {
Student s = i.next();
if (s.getfName().equalsIgnoreCase(firstName) && s.getsName().equalsIgnoreCase(secondName))
System.out.println(s.getSubjectValuation());
}
``}
//the average not sure how am i going to do it
void average(String firstName,String secondName){
Student s=search(firstName,secondName);
}
void sort(){
Collections.sort(s);
}
}
public static void main(String[] args) {
Catalogue c=new Catalogue();
c.add("a","b");
c.add("b","c");
c.add("d","f");
c.add("a","b");
// c.listInformation("a","b");
c.delete("a","b");
System.out.println("+");
c.printall();
c.add2("d","f","math",9);
c.printall();
c.add2("f","a","asdsdfd",1);
System.out.println("++");
c.printall();
System.out.println("++++");
c.listValuation("d","f");
}
}
The above class was my Catalogue class.
I have to perform these tasks:
Add a student;
Add for a student subjects and notes;
Delete a student;
Search a student after name and print every grade for every subject;
search a student after name and calculate the average of subject;
I don't know how to assign an array of subjects and grades for student for example I have a student named Jon Jon he can have multiple subjects like Math1,Math2,Math3.... and grades like Math1 grade is 1 Mah2 grade is 2 .....
The 5. is not implemented but I am more interested in how to implement the array of subjects and notes
If I understood your question right you're asking how to combine subjects and grades and put these into an array.
One way you could solve this is implementing a seperate class Subject which also got grades as a attribute.
public class Subject {
private String subject;
private float grade;
//getter and setter methods
}
You can use this class in your class Student:
public class Student implements Comparable<Student> {
String fName;
String sName;
Subject subject[]; //array which can contain multiple subjects. each
//entry got two attributes: the subject itself as String; the grade
//your code
}

Adding objects of a class to an ArrayList in another class

Im trying to add Objects of a Class called Student to an Arraylist in another class called StudentClass. I have initialised the list, but am having trouble working out how to add objects to the ArrayList
Code for StudentClass
public class StudentClass
{
List<Student> studentList;
private String studentName;
private int lengthOfString;
public StudentClass()
{
super();
studentList = new ArrayList<>();
}
public void addStudent(String aName)
{
String objt = new String(name, mark);
studentList.add(Student);
}
Code for Student
public class Student
{
private String name;
private int mark;
public Student(String aName)
{
super();
this.name = aName;
this.mark = -1;
Try this:
public void addStudent(String aName) {
studentList.add(new String(aName));
}
Also, Student class constructor does not accept marks as second parameter, at least the code what you have posted.
This should work.
import java.util.*;
public class StudentClass
{
List<Student> studentList;
private String studentName;
private int lengthOfString;
public StudentClass()
{
super();
studentList = new ArrayList<>();
}
public void addStudent(String aName) {
Student student = new Student(aName);
studentList.add(student);
}
}
public class Student
{
private String name;
private int mark;
public Student(String aName)
{
super();
this.name = aName;
this.mark = -1;
}
}
I'm not clear what you're trying to do with the mark?
Seems that your mistake is here:
String objt = new String(name, mark);
studentList.add(Student);
Write this instead:
Student objt = new Student(name, mark);
studentList.add(objt);
You need to create a new Student object and then add that to your list:
public void addStudent(String aName) {
Student student = new Student(aName);
studentList.add(student);
}
It's not really clear from your provided code how the mark field is set, but either pass it through the Student construction and/or add getters and setters.

Categories

Resources