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.
Related
the student and teacher class inherited from person class, because inheritance is not flexible the object will either be one of the two. to solve this i added an abstract class Role and make association between person and role and student and teacher inherits from Role class so that an instance can has a role of both student and teacher.The question is to make instance of the Teacher class can also be a student or a student also teaches how to test in the main class?
public class Person {
private int ssn;
private String name;
private List<PersonRole> roles;
public Person(int ssn, String name) {
this.ssn = ssn;
this.name = name;
roles = new ArrayList<PersonRole>();
}
public int getSsn() {
return ssn;
}
public String getName() {
return name;
}
}
/////////////// PersonRole /////////////////
public abstract class PersonRole {
private List<PersonRole> learning;
private List<PersonRole> teaching;
public PersonRole(List<PersonRole> learning, List<PersonRole> teaching) {
this.learning = learning;
this.teaching = teaching;
}
public List<PersonRole> getLearning() {
return learning;
}
public List<PersonRole> getTeaching() {
return teaching;
}
public void addAsStudent(PersonRole p) {
learning.add(p);
}
public void addAsTeacher(PersonRole p) {
learning.add(p);
}
}
///////////// Teacher //////////////
public class Teacher extends PersonRole {
private String faultyName;
private int yearsOfExperence;
public Teacher(String faultyName, int yearsOfExperence) {
super();
this.faultyName = faultyName;
this.yearsOfExperence = yearsOfExperence;
}
public String getFaultyName() {
return faultyName;
}
public int getYearsOfExperence() {
return yearsOfExperence;
}
}
/////////// Student ////////////////
public class Student extends PersonRole {
private String collegeName;
private String major;
public Student(String collegeName, String major) {
super();
this.collegeName = collegeName;
this.major = major;
}
public String getCollegeName() {
return collegeName;
}
public String getMajor() {
return major;
}
}
////// Main ///////////////
public class Main {
public static void main(String[] args) {
PersonRole p1 = new Student("univ of Michigan", "CS");
PersonRole p3 = new Student("Iowa state univ", "managemnt");
PersonRole p2 = new Teacher("computer science", 3);
PersonRole p4 = new Teacher("Management", 2);
Person person = new Person(1042327867, "Mike Rose");
person.addRole(p1);
person.addRole(p2);
person.addRole(p3);
person.addRole(p4);
for (PersonRole c: roles) {
System.out.println(c);
}
}
}
I would test it exactly as you would but the hierarchy of inheritance looks good. Why not give PersonRole a constructor and attributes so that the children can use super() in their constructors and reuse some code?
Try this to print your roles:
List<PersonRole> roles = person.getRole();
for(PersonRole role: roles) {
System.out.println(role);
}
Then add a toString method in the Student and Teacher classes:
public String toString() {
return "Student {" + "collegeName=" + collegeName + ", major=" + major + '}';
}
public String toString() {
return "Teacher {" + "faultyName=" + faultyName + ", yearsOfExperence=" + yearsOfExperence + '}';
}
The result will be this:
Student {collegeName=maharashi univ, major=compro}
Teacher {faultyName=computer science, yearsOfExperence=3}
Student {collegeName=Iowa state univ, major=managemnt}
Teacher {faultyName=Management, yearsOfExperence=2}
Hi I have created a toStringmethod in one of my classes which can be seen below.
Student Class:
package Practical5;
public class Student extends Person {
//instance variables
private static int MAX_MODULES = 6;
private StudentMode modeOfStudy;
private boolean studentLoan;
private int numEnrolledModules;
//constructor
public Student(String name, String dob, Address address, StudentMode modeOfStudy, boolean studentLoan) {
super(name, dob, address);
this.modeOfStudy = modeOfStudy;
this.studentLoan = studentLoan;
this.numEnrolledModules = 0;
}
//accessors & mutators
public StudentMode getMode() {
return modeOfStudy;
}
public boolean isStudentLoan() {
return studentLoan;
}
public int getNumEnrolledModules() {
return numEnrolledModules;
}
public void setMode(StudentMode modeOfStudy) {
this.modeOfStudy = modeOfStudy;
}
public void setStudentLoan(boolean studentLoan) {
this.studentLoan = studentLoan;
}
public void setNumEnrolledModules(int numEnrolledModules) {
this.numEnrolledModules = numEnrolledModules;
}
#Override
public void purchaseParkingPass() {
System.out.println(getName() + " just purchased a parking pass with student discount.");
}
#Override
public void addModule(String moduleCode) {
if (getNumEnrolledModules() < MAX_MODULES) {
System.out.println(getName() + " successfully registered for the module: " + moduleCode);
}
else {
System.out.println("You are unable to register for " + moduleCode + " as the maximum number of permitted module enrolments has been reached.");
}
}
public String toString() {
return "Student [ ID: " + getId() + "; Name: " + getName() +
"; DOB: " + getDob() + "; Study Mode: " + getMode() +
"; Number of Enrolled Modules: " + getNumEnrolledModules();
}
}
Person Class:
package Practical5;
public abstract class Person {
//instance variables
private static int LAST_ID = 1000 + 1;
private int id;
private String name;
private String dob;
private Address address;
//constructor
public Person(String name, String dob, Address address) {
super();
LAST_ID ++;
this.id = LAST_ID;
}
//accessors & mutators
public int getId() {
return id;
}
public String getName() {
return name;
}
public String getDob() {
return dob;
}
public Address getAddress() {
return address;
}
public void setName(String name) {
this.name = name;
}
public void setDob(String dob) {
this.dob = dob;
}
public void setAddress(Address address) {
this.address = address;
}
//methods
public abstract void purchaseParkingPass();
public abstract void addModule(String moduleCode);
}
I then created a tester class and created a new ArrayList and added these elements to it.
I then created a for loop in order to loop through each element and call the toString method to print out the details of each element but it is returning null values.
Tester Class:
package Practical5;
import java.util.ArrayList;
import java.util.Scanner;
public class UIS_Tester {
public static void main(String[] args) {
Student student1 = new Student("James Black", "07/09/1995" , new Address("Wheeler's Road",10,"Belfast", "BT12 5EG", "Co.Antrim"),StudentMode.Fulltime, false);
Student student2 = new Student("Adam Smith", "12/11/1979" , new Address("Ivy Hill",67,"Belfast", "BT17 7BN", "Co.Antrim"),StudentMode.Parttime, true);
ArrayList<Person> uniPeople = new ArrayList<Person>();
uniPeople.add(student1);
uniPeople.add(student2);
printMenu(uniPeople);
}
public static void printAllDetails(ArrayList<Person> uniPeople) {
for (int i = 0; i < uniPeople.size(); i++) {
System.out.println(uniPeople.get(i).toString());
}
}
}
Output:
Student [ ID: 1002; Name: null; DOB: null; Study Mode: Fulltime; Number of Enrolled Modules: 0
Student [ ID: 1003; Name: null; DOB: null; Study Mode: Parttime; Number of Enrolled Modules: 0
Can anyone help me with this problem? Thanks
public Person(String name, String dob, Address address) {
super();
LAST_ID ++;
this.id = LAST_ID;
}
The constructor completely ignores its three arguments. It doesn't assign them to the corresponding fields, so these fields keep their default value: null.
You have to store the name value in the constructor. Your version did not use the name value.
public Person(String name, String dob, Address address) {
super();
this.name = name; // <== important line
this.dob = dob; // <== important line
this.address = address; // <== important line
LAST_ID ++;
this.id = LAST_ID;
}
Look at the constructor in person and in student, Should use the parameters in the method header.
super(name,dob,address)
So my Java teacher wants us to write a program that simply says "Ben Barcomb is 19 years old" That's it, nothing more, nothing less.
Instead of using System.out.println like a normal person he wants us to use an instance variable in the Person class for the full name and age that must be private, he also wants a getter and setter method for the fullname and variable as well. This is the tester code I have, but I'm kind of stuck on the variable and getter/setter methods.
public class PersonTester {
public static void main(String[] args) {
Person p1 = new Person();
p1.setFullname("Bilal Gonen");
p1.setAge(76);
String myFullname = p1.getFullname();
int myAge = p1.getAge();
System.out.println(myFullname + " is " + myAge + " years old.");
}
}
public class Person{
private String myFullname;
private int myAge;
public String getFullname()
{
return myFullname;
}
public int getAge()
{
return myAge;
}
public Person(String aFullname)
{
myFullname = aFullname;
}
public void setFullname()
{
myFullname = aFullname;
}
}
Here is an example of a getter and setter. I am sure you can use this as a guide.
public class Person
{
private String firstName;
private String lastName;
public void setName(String f, String l)
{
firstName = f;
lastName = l;
}
public String getFirstName()
{
return firstName;
}
}
Short tutorial on setters and getters.
Not doing your homework for you, but I will provide some help on the getters and setters. Here's an example person class with one variable, add the others you need yourself.
public class Person {
int age;
public void setAge(int age) { // notice how the setter returns void and has an int parameter
this.age = age; // this.age means the age we declared earlier, while age is the age from the parameter
}
public int getAge() { // notice the return type, int? this is because the var we're getting is an int
return age;
}
Thanks to the help of everyone, as well as some of the research I did myself, I got the program to compile and run correctly, here is the source code. Thanks again to everyone who assisted!
public class PersonTester {
public static void main(String[] args) {
Person p1 = new Person();
p1.setFullname("Ben Barcomb");
p1.setAge(19);
String myFullname = p1.getFullname();
int myAge = p1.getAge();
System.out.println(myFullname + " is " + myAge + " years old.");
}
}
public class Person
{
private String myFullname;
private int myAge;
public String getFullname()
{
return myFullname;
}
public int getAge()
{
return myAge;
}
public void setAge(int newAge)
{
myAge = newAge;
}
public void setFullname(String aFullname)
{
myFullname = aFullname;
}
}
The valid code is as below, use getters for the String input of System.out.println()
Full test code is as below;
public class PersonTester {
public static void main(String[] args) {
Person p1 = new Person();
p1.setMyFullname("Bilal Gonen");
p1.setMyAge(76);
System.out.println(p1.getMyFullname() + " is " + p1.getMyAge() + " years old.");
}
}
class Person {
private String myFullname;
private int myAge;
public String getMyFullname() {
return myFullname;
}
public void setMyFullname(String myFullname) {
this.myFullname = myFullname;
}
public int getMyAge() {
return myAge;
}
public void setMyAge(int myAge) {
this.myAge = myAge;
}
}
And the output is as below;
Bilal Gonen is 76 years old.
Note: And it will make your job easier whenever a similiar project comes, when making a POJO class (in this example the Person class), use eclipse's (or any IDE's) "generate getters/setters" shortcut (on Eclipse, you can use it with Alt+Shift+S)
This is my student class.
public class Student {
private String name;
private long id;
private double gpa;
private PersonalData pd;
public Student(String name, long id, double gpa, PersonalData pd){
this.name= name;
this.id=id;
this.gpa= gpa;
this.pd= pd;
}
public String getName(){
return name;
}
public long getID(){
return id;
}
public double getGPA(){
return gpa;
}
public PersonalData getPersonalData(){
return pd;
}
public String toString(){
String result= "Name: "+ name+ ", ID: "+ id+ ", GPA: "+gpa+", Personal Data: "+ pd;
return result;
}
}
Here is the test class:
public class Test {
public static void main(String[] args) {
// TODO, add your application code
PersonalData a= new PersonalData(80,4,1,1232154687);
Student b= new Student(Ali,123,20,a);
}
}
It gives this error:
cannot find symbol
Student b= new Student(Ali,123,20,a);
^
symbol: variable Ali
location: class Test
1 error
I don't know what is wrong. Is there anyone can see?
Make it like below
student b= new Student("Ali",123,20,a);
Your Student class constructor requires String as name either you have to pass it as in "" or Make a String variable like String Ali="" then pass Ali as
student b= new Student(Ali,123,20,a);
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.