I created a three-class program. In the third class, I should fill the array with the values "name", "surname", "code", and "age". What happens though is that my array is always "null", and I can't fill it. Thank you all for your help.
First class:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String name, surname;
int code, age, i=0, min=150;
System.out.println("How many teachers do you want to enter information?");
i=in.nextInt();
for(int j=0; j<i; j++)
{
System.out.println("Enter the teacher's name");
name=in.next();
System.out.println("Enter the teacher's surname");
surname=in.next();
System.out.println("Enter the teacher's code");
code=in.nextInt();
System.out.println("Enter the teacher's age");
age=in.nextInt();
Teacher d = new Teacher(name, surname, code, age);
System.out.println(d.getCode());
System.out.println(d.getSurname());
System.out.println(d.getAge());
University c = new University(name, surname, code, age);
min=c.MinimumAge(age, min);
}
System.out.println(min);
}
}
Second class:
public class Teacher
{
protected String name;
protected String surname;
protected int code;
protected int age;
public Teacher(String name, String surname, int code, int age)
{
this.name=name;
this.surname=surname;
this.code=code;
this.age=age;
}
public String getName()
{
return name;
}
public int getCode()
{
return code;
}
public String getSurname()
{
return surname;
}
public int getAge()
{
return age;
}
}
Third class (I put "0" as a location for filling the array just to do tests.):
public class University
{
private Teacher[] array=new Teacher[4];;
public University(String name, String surname, int code, int age)
{
array[0] = new Teacher(name, surname, code, age);
}
public int MinimumAge(int age, int min)
{
if (age<min)
min=age;
return min;
}
}
The class University has not been implemented correctly. You can implement it as:
class University {
private int counter = 0;
private final int MAX = 4;
private Teacher[] array = new Teacher[MAX];
public void addTeacher(Teacher teacher) {
if (counter < MAX) {
array[counter++] = teacher;
}
}
public int minimumAge() {
if (counter == 0) {
return 0;
}
int min = array[0].getAge();
for (int i = 1; i < counter; i++) {
if (array[i].getAge() < min) {
min = array[i].getAge();
}
}
return min;
}
}
Accordingly, you need to change your code in main as shown below:
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String name, surname;
int code, age, i = 0, min = 150;
University university = new University();
System.out.print("How many teachers do you want to enter information?: ");
i = in.nextInt();
for (int j = 0; j < i; j++) {
System.out.print("Enter the teacher's name: ");
name = in.next();
System.out.print("Enter the teacher's surname: ");
surname = in.next();
System.out.print("Enter the teacher's code: ");
code = in.nextInt();
System.out.print("Enter the teacher's age: ");
age = in.nextInt();
university.addTeacher(new Teacher(name, surname, code, age));
}
System.out.println(university.minimumAge());
}
}
A sample run:
How many teachers do you want to enter information?: 2
Enter the teacher's name: a
Enter the teacher's surname: b
Enter the teacher's code: 1
Enter the teacher's age: 23
Enter the teacher's name: x
Enter the teacher's surname: y
Enter the teacher's code: 2
Enter the teacher's age: 15
15
Related
I'm trying to write this Registration Program for Sports Teams, but when I input a name and age which qualifies for a team, an java.lang.ArrayOutOfBoundsException occurs. Any idea why? The code and classes can be seen below.
The objective of the code is to fill out arrays in the Team Class, and print it out once the user inputs '3' in the Test Class.
public class Member {
public String name;
public int age;
public Member(String name, int age){
this.name = name;
this.age = age;
}
}
public class Test {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Scanner myScan = new Scanner(System.in);
int choi;
Team basketball = new Team("Basketball", 2, 18, 21);
Team volleyball = new Team("Volleyball", 3, 17, 19);
do{
//MENU
System.out.println("Select Team");
System.out.println("--------------");
System.out.println("[1] Basketball");
System.out.println("[2] Volleyball");
System.out.println("[3] Exit");
System.out.println("---------------");
System.out.print("Choice: ");
choi = myScan.nextInt();
myScan.nextLine();
//SWITCH START
switch(pili){
//BASKETBALL CASE
case 1:
String name;
int age;
System.out.println("Basketball");
System.out.print("Enter Name: ");
name = myScan.nextLine();
System.out.print("Enter Age: ");
age = myScan.nextInt();
myScan.nextLine();
Member bball = new Member(name,age);
basketball.addMember(bball);
break;
//END CASE 1
//VOLLEYBALL CASE
case 2:
String name1;
int age1;
System.out.println("Volleyball");
System.out.print("Enter Name: ");
name1 = myScan.nextLine();
System.out.print("Enter Age: ");
age1 = myScan.nextInt();
Member vball = new Member(name1, age1);
volleyball.addMember(vball);
break;
//END CASE 2
//EXIT CASE
case 3:
System.out.println("Basketball Team Members");
for(int i = 0; i<2; i++){
System.out.println(basketball.members[i]);
}
System.out.println("Volleyball Team Members");
for(int i = 0; i<3; i++){
System.out.println(volleyball.members[i]);
}
break;
//CASE 3 END
} //END SWITCH
} //END DO
while(choi > 0 && pili < 3);
}
public class Team {
public String name;
public int memberCnt;
public int maxMember;
public Member [] members = new Member[maxMember];
public int minAge;
public int maxAge;
public Team(String name, int maxMember, int minAge, int maxAge){
this.name = name;
this.maxMember = maxMember;
this.minAge = minAge;
this.maxAge = maxAge;
}
public void addMember(Member memb){
boolean result = checkQualification(memb);
if(memberCnt < maxMember){
if (result){
members[memberCnt]=memb;
memberCnt++;
System.out.println("Welcome to the " + name);
}
else{
System.out.println("You are not qualified!");
}
}
else{
System.out.println(name + " Team is no longer accepting applicants");
}
}
public boolean checkQualification(Member memb){
return memb.age >= minAge && memb.age <= maxAge;
}
}
The error is because of
public int maxMember;
public Member[] members = new Member[maxMember];
Because at this moment maxMember values 0, so you're creating an empty array
Do the instantiation when you have the real value of maxMembers, in the constructor
public int maxMember;
public Member[] members;
public Team(String name, int maxMember, int minAge, int maxAge) {
this.name = name;
this.maxMember = maxMember;
this.members = new Member[maxMember];
this.minAge = minAge;
this.maxAge = maxAge;
}
Attribut maxMembers could not be an attribut, and you would use array's length in condition
if (memberCnt < members.length) {
I need to fix my addQuiz() in my student class. Then, with that class, I pull all the info into my main of prog2. I have everything working except two things. I need to get the formula fixed for my addQuiz() so it totals the amount of points entered, and fix the while statement in my main so that I can enter a word to tell the program that I am done entering my quizzes.
Here is my main file.
import java.util.Scanner;
public class Prog2 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
Student student = new Student();
//creates array for quizzes
double[] grades = new double[99];
//counter for total number of quizzes
int num = 0;
//requests user to enter students name
System.out.print("Enter name of student: ");
String name = in .nextLine();
//requests user to enter students quizzes
System.out.print("Enter students quiz grades: ");
int quiz = in .nextInt();
while (quiz >= 1) {
System.out.print("Enter students quiz grades: ");
quiz = in .nextInt();
grades[num] = quiz;
num++;
}
//prints the name, total, and average of students grades
System.out.println();
System.out.println(name);
System.out.printf("\nTotal: ", student.addQuiz(grades, num));
System.out.printf("\nAverage: %1.2f", student.Average(grades, num));
}
}
here is my student file:
public class Student {
private String name;
private int total;
private int quiz;
static int num;
public Student() {
super();
}
public String getName(){
return name;
}
public void setName(String name){
this.name = name;
}
public int getTotal() {
return total;
}
public void setTotal(int total) {
this.total = total;
}
public int getQuiz() {
return quiz;
}
public void setQuiz(int quiz) {
this.quiz = quiz;
}
public static double addQuiz( double[] grades, int num){
int totalQuiz = 0;
for( int x = 0; x < num; x++){
totalQuiz += grades[x];
}
return totalQuiz;
}
public static double Average( double[] grades, int num){
double sum = 0;
for( int x = 0; x < num; x++){
sum += grades [x];
}
return (double) sum / num;
}
}
Any help would be much appreciated!
Your requirement is not clear but as I guess it should be something like this.
Prog2 class:
public static void main(String[] args) {
// requests user to enter students name
System.out.print("Enter name of student: ");
Scanner in = new Scanner(System.in);
String name = in.nextLine();
Student student = new Student(name);
System.out.print("Enter number of quiz: ");
int count = in.nextInt();
for (int i = 0; i < count; i++) {
// requests user to enter students quizzes
System.out.print("Enter students quiz grades: ");
int quiz = in.nextInt();
student.addGrade(quiz);
}
// prints the name, total, and average of students grades
System.out.println(name);
System.out.println("Total: " + student.getTotal());
System.out.println("Average: " + student.getAverage());
}
Student class:
private String name;
private List<Double> grades = new ArrayList<Double>();
public Student(String name) {
super();
this.name= name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void addGrade(double grade) {
this.grades.add(grade);
}
public double getTotal() {
double total = 0;
for (double grade : grades) {
total += grade;
}
return total;
}
public double getAverage() {
return (double) getTotal() / grades.size();
}
Accept the answer if it helps.
Well for the stop condition you could try something like this
String stopFrase="stop";
String userInput="";
int quiz;
//Other code
for(;;) //This basically means loop until I stop you
{
System.out.print("Enter students quiz grades type 'stop' to finish:");
userInput=in.nextLine();
if(userInput.equals(stopFrace))
{
break;//Stop the loop
}
quiz= Integer.parseInt(userInput);
//The rest of your code
}
Your addQuiz() method seems fine, if you are not getting the desired result please check your parameters, specifically make sure that number matches the number of quiz entered.
So i have 3 classes, and one that runs all the code. A student class, a Graduate student class and an undergraduate class, and a class called lab 4 that runs the code. The code asks for how many grad students and how many undergrad students there are, then asks the user to input all the information for that number of each. After all the info is inputed, the under grad or grad student objects are added to an array list of students. after all the students are added, then prints all the information. However when i input all the information, the array does not print, the program terminates. How do i get the array to print out?
Code:
Lab 4: creates the student objects, array list, adds them to the array, and the prints all information for objects added to the array list
import java.util.ArrayList;
import java.util.Scanner;
public class Lab04 {
public static void main(String[] args) {
ArrayList <Student> studentList = new ArrayList <Student>();
Scanner s = new Scanner(System.in);
System.out.println("How many Graduate Students do you want to store?");
int numOfStudents = s.nextInt();
s.nextLine();
for (int i = 0; i < numOfStudents; i++) {
System.out.println("What is the student's name?");
String name = s.nextLine();
System.out.println("What is the student's GPA?");
double GPA = s.nextDouble();
s.nextLine();
System.out.println("What is the student's ID?");
String ID = s.nextLine();
System.out.println("What is the student's High School?");
String highSchool = s.nextLine();
System.out.println("What is the student's graduate major?");
String gradMajor = s.nextLine();
System.out.println("What is the student's undergraduate major?");
String underMajor = s.nextLine();
System.out.println("What is the student's undergradute school? ");
String underSchool = s.nextLine();
GraduateStudent gradStu = new GraduateStudent(name, GPA, ID, highSchool, gradMajor, underMajor,
underSchool);
studentList.add(gradStu);
}
System.out.println("How many UnderGraduate students are there?");
int numOfUnder = s.nextInt();
s.nextLine();
for (int j = 0; j < numOfUnder; j++) {
System.out.println("What is the student's name?");
String name = s.nextLine();
System.out.println("What is the student's GPA?");
double GPA = s.nextDouble();
s.nextLine();
System.out.println("What is the student's ID?");
String ID = s.nextLine();
System.out.println("What is the student's High School?");
String highSchool = s.nextLine();
System.out.println("What is the student's major?");
String major = s.nextLine();
System.out.println("What the student's minor?");
String minor = s.nextLine();
UnderGraduate UnderGrad = new UnderGraduate(name, GPA, ID, highSchool, major, minor);
studentList.add(UnderGrad);
}
for (int j = 0; j < studentList.size(); j++) {
(studentList.get(j)).getStudentInformation();
}
}
}
Student Class:
public class Student {
private String name;
private double gpa;
private String id;
private String highSchool;
//private String major;
//private String minor;
public Student() {
name = "";
gpa = 0.0;
id = "";
highSchool = "";
//major = "";
//minor = "";
}
public Student(String name, double gpa, String id, String highSchool){
this.name = name;
this.gpa = gpa;
this.id = id;
this.highSchool = highSchool;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getGpa() {
return gpa;
}
public void setGpa(double gpa) {
this.gpa = gpa;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getHighSchool() {
return highSchool;
}
public void setHighSchool(String highSchool) {
this.highSchool = highSchool;
}
public String getStudentInformation() {
String result = "Name: " + name + " GPA: " + gpa + " ID: " + id
+ " High School: " + highSchool;
return result;
}
}
graduate Class:
public class GraduateStudent extends Student {
private String gradMajor;
private String underMajor;
private String underSchool;
public GraduateStudent(String name, double gpa, String id, String highSchool,
String gradMajor, String underMajor, String underSchool) {
super(name, gpa, id, highSchool);
this.gradMajor = gradMajor;
this.underMajor = underMajor;
this.underSchool = underSchool;
}
public String getGradMajor() {
return gradMajor;
}
public void setGradMajor(String gradMajor) {
this.gradMajor = gradMajor;
}
public String getUnderMajor() {
return underMajor;
}
public void setUnderMajor(String underMajor) {
this.underMajor = underMajor;
}
public String getUnderSchool() {
return underSchool;
}
public void setUnderSchool(String underSchool) {
this.underSchool = underSchool;
}
#Override
public String getStudentInformation() {
String result = super.getStudentInformation()+
"Graduate Major: " + gradMajor + "Undergraduate Major: " + underMajor +
"Undergraduate School: " + underSchool;
return result;
}
}
Because you're not printing anything. Change
for (int j = 0; j < studentList.size(); j++) {
(studentList.get(j)).getStudentInformation();
}
to
for (int j = 0; j < studentList.size(); j++) {
System.out.println((studentList.get(j)).getStudentInformation());
}
When you ask getStudentInformation, it returns a String, what you want to do now is to System.out.println(...) this String object
Could anybody tell me how to list some data in an arrayList according to the integer value that each component of the ArrayList has? This is my main class
import java.util.Scanner;
import java.io.*;
import java.util.Collections;
import java.util.ArrayList;
public class StudentDriver {
public static void main(String[] args) throws IOException {
Scanner scan, urlScan, fileScan;
String url, file;
int count = 0;
scan = new Scanner(System.in);
System.out.println("Enter the name of the file");
fileScan = new Scanner(new File("Data.csv"));
ArrayList<Student> studentList = new ArrayList<Student>();
while(fileScan.hasNext()){
url = fileScan.nextLine();
urlScan = new Scanner(url);
urlScan.useDelimiter(",");
count++;
while(urlScan.hasNext()){
String name = urlScan.next();
String last = urlScan.next();
int score = urlScan.nextInt();
Student e = new Student(name,last, score);
studentList.add(e);
}
}
System.out.println("The file has data for" +count+ "instances");
int option;
do{
System.out.println("********");
System.out.println("Options:");
System.out.println("********\n1. List \n2. Add Student \n3.Delete Student \n4. Exit \n******** ");
System.out.print("Select option: ");
option = scan.nextInt();
if(option == 1){
int index = 0;
while(index<studentList.size()){
System.out.println(studentList.get(index));
index++;
}
}
else if(option == 2){
System.out.print("Enter the name of the student: ");
String newName = scan.next();
System.out.print("Enter the last name of the student: ");
String newLastName = scan.next();
System.out.print("Enter the exam score of the student: ");
int newScore = scan.nextInt();
Student b = new Student(newName, newLastName, newScore);
studentList.add(b);}
else if(option == 3){
System.out.print("Enter the name of the student to remove: ");
String remove = scan.next();
System.out.print("Enter the last name of the student: ");
String remove1 = scan.next();
int location = studentList.indexOf(remove);
location = studentList.indexOf(remove1);
studentList.remove(location);
}
}while(option!=4 && option <4);
}//main
}//class
And this is the other class
public class Student implements Comparable<Student>{
String firstName, lastName;
int score;
public Student(String firstName, String lastName, int score){
this.firstName = firstName;
this.lastName = lastName;
this.score = score;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public int getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
public String toString(){
return firstName + " " + lastName + ", exam score is "+ score;
}
#Override
public int compareTo(Student c) {
return score-c.getScore();
}
}
As you can see, up to now I have created the class where my compare method is but I have difficulties on using it. Also I have had difficulties on deleting one of the Array List parts by just writing the name and last name of the student. If somebody would help me, I would be very thankful.
well you can change your compareTo method as
public int compareTo(Student another)
{
if (this.score > another.score)
return -1;
if (this.score < another.score)
return 1;
else
return 0;
}
this should show it as decreasing order you can change the operator
than use whereever you want to sort it
Collections.sort(studentList)
Also if you don't want to use Collections.sort() method I can show you how you can write it with for loop under add option
Student newStd = new Student(name, last, score);
for(int i=0;studentList.size()>i;i++)
{
int size = studentList.size();
if(newStd.compareToCustom(studentList.get(i))>0)
{
studentList.add(i, newStd);
break;
}
else if(newStd.compareToCustom(studentList.get(size-1))<0)
{
studentList.add(studentList.size(), newStd);
break;
}
else if(newStd.compareToCustom(studentList.get(i))==0)
{
studentList.add(i++, newStd);
break;
}
}
for the remove part you can use
else if ( option == 3)
{
System.out.print("Enter the first name of student will be deleted: ");
String removeName = scan.next();
System.out.print("Enter the last name of student will be deleted: ");
String removeLastName = scan.next();
for ( int i = 0; i < studentList.size(); i++)
{
Student deleted = studentList.get(i);
if ( deleted.getFirstName().toLowerCase().equals(removeName.toLowerCase()) && deleted.getLastName().toLowerCase().equals(removeLastName.toLowerCase()))
{
studentList.remove(i);
System.out.println("The student has been deleted.");
break;
}
else
{
System.out.println("This student is not found");
break;
}
}
}
Basically what you want is an ordered collection. As #duffymo has stated, think about a creating a custom Comparator using your score.
There is plenty of info here
In terms of deleting students from the list.
The studentList is a list containing Student objects.
This means that the follow code:
System.out.print("Enter the name of the student to remove: ");
String remove = scan.next();
System.out.print("Enter the last name of the student: ");
String remove1 = scan.next();
int location = studentList.indexOf(remove);
Tries to find the index of a Student given the first name. This will return -1 as you're searching for a String and not a Student object.
Instead you have to iterate through your studentList and compare the first and last name of each Student element with the values of remove and remove1.
for(Student student : studentList) {
if(student.getFirstName.equals(remove) && student.getLastName.equals(remove1)) {
// remove the student.
}
}
Also you could consider giving each Student an ID as an unique identifier.
try this to sort studentList
Collections.sort(studentList, new Comparator<Student>()
{
#Override
public int compare(Student x, Student y)
{
if(x.score >= y.score)
return 1;
else
return -1;
}
});
My code is not compiling and my biggest issue is that line 32 compiles but 42 does not and the methods they come from are written exactly the same. The error message is error cannot find symbol.
import java.util.*;
import java.text.*;
public class CourseApp{
public static void main(String[] args){
Scanner s = new Scanner (System.in);
DecimalFormat df = new DecimalFormat("$0.00");
int initialSize;
boolean q = true;
System.out.println("Enter how many courses you would like to enter info rmation for? ");
try{initialSize = s.nextInt();}
catch(NumberFormatException sonic){
while(initialSize <= 0){
System.out.println("Please enter an integer greater than 0 (ie5). ");
initialSize = s.nextInt();}}
ArrayList <Course> courseArrayList = new ArrayList<Course> (initialSize);
String number="";
String name="";
String instr="";
String text="";
for (int i = 0; i < initialSize; i++){
courseArrayList.add(new Course(number, name, instr, text));
System.out.println("Enter in course information. ");
do{
courseArrayList.get(i).setNumber("");
System.out.println("Please enter the course number: ");
courseArrayList.get(i).setNumber(s.nextLine());
}while(courseArrayList.get(i).getNumber().equals(""));
do{
courseArrayList.get(i).setName("");
System.out.println("Please enter the course name: ");
courseArrayList.get(i).setName(s.nextLine());
}while(courseArrayList.get(i).getName().equals(""));
do{
courseArrayList.get(i).setLastName("");
System.out.println("Please enter the Instructor's last name: ");
courseArrayList.get(i).setLastName(s.nextLine());
}while(courseArrayList.get(i).getLastName().equals(""));
do{
courseArrayList.get(i).setFirstName("");
System.out.println("Please enter the Instructor's first name: ");
courseArrayList.get(i).setFirstName(s.nextLine());
}while(courseArrayList.get(i).getFirstName().equals(""));
do{
courseArrayList.get(i).setUserName("");
System.out.println("Please enter the Instructor's user name: ");
courseArrayList.get(i).setUserName(s.nextLine());
}while(courseArrayList.get(i).getUserName().equals(""));
String[] instrr = new String[3];
instrr[0]=courseArrayList.get(i).getLastName()+", ";
instrr[1]=courseArrayList.get(i).getFirstName()+"\n";
instrr[2]=courseArrayList.get(i).getUserName()+"#K-State.ksu";
instr = instrr[0]+instrr[1]+instrr[2];
System.out.println("Please enter the required text book's title: ");
courseArrayList.get(i).setTitle(s.nextLine());
System.out.println("Please enter the required text book's author: ");
courseArrayList.get(i).setAuthor(s.nextLine());
System.out.println("Please enter the required text book's price: ");
try{courseArrayList.get(i).setPrice(s.nextDouble());}
catch(NumberFormatException shadow){
while(courseArrayList.get(i).setPrice(s.nextDouble()) < 0){
System.out.println("Please enter a positive numerical value. ");
courseArrayList.get(i).setPrice(s.nextDouble());}}
String[] textt = new String[3];
textt[0]=courseArrayList.get(i).getTitle()+"\n";
textt[1]=courseArrayList.get(i).getAuthor()+"\n";
textt[2]=df.format(courseArrayList.get(i).getPrice())+"\n";
text = textt[0]+textt[1]+textt[2];}
for (int i = 0; i < initialSize; i++){
System.out.println("Press enter to display each of the courses");
s.nextLine();
courseArrayList.get(i).toString();}
System.out.println("Please enter a course number");
String a = s.nextLine();
for (int i = 0; i < initialSize; i++){
if (a.equals(courseArrayList.get(i).getNumber())){
courseArrayList.remove(i);}
else if (! a.equals(courseArrayList.get(initialSize-1).getNumber())){
do {
System.out.println("Course number not found.");
System.out.println("Please enter a valid course number: ");
a = s.nextLine();
for (int j = 0; j < initialSize; j++){
if (a.equals(courseArrayList.get(j).getNumber())){
q=false;
courseArrayList.remove(j);}}
} while (q=true);}
else {}}
for (int i = 0; i < initialSize; i++){
System.out.println("Press enter to display each of the courses");
s.nextLine();
courseArrayList.get(i).toString();}}}
this is from a different class and this part does not compile
public void setLastName(String lname){
lastName=lname;}
the instructor class is:
public class Instructor
{
private String lastName; // Last name
private String firstName; // First name
private String userName; // Username ID
public Instructor(String lname, String fname, String un){
lastName = lname;
firstName = fname;
userName = un;}
public Instructor(Instructor object2){
lastName = object2.lastName;
firstName = object2.firstName;
userName = object2.userName;}
public void setLastName(String lname){
lastName=lname;}
public String getLastName(){
return lastName;}
public void setFirstName(String fname){
firstName=fname;}
public String getFirstName(){
return firstName;}
public void setUserName(String un){
userName=un;}
public String getUserName(){
return userName;}
public String toString()
{
return str;
}
}
this is from a different class and this part does compile
public void setName(String name){
courseName=name;}
the course class is:
public class Course
{
private String courseNumber; // e.g. CIS 200
private String courseName; // e.g. Programming Fundamentals
private Instructor instructor; // Course instructor (object)
private TextBook textBook; // Required Course textbook (object)
public Course(String number, String name, String instr, String text){
courseNumber = number;
courseName = name;
instructor = new Instructor(instr);
textBook = new TextBook(text);}
public String getName(){
return courseName;}
public void setName(String name){
courseName=name;}
public String getNumber(){
return courseNumber;}
public void setNumber(String number){
courseNumber=number;}
public Instructor getInstructor(){return new Instructor(instructor);}
/**getTextBook method
#return A reference to a copy of this course's TextBook object.*/
public TextBook getTextBook(){return new TextBook(textBook);}
/**toString method
#return A string containing the course information.*/
public String toString(){
String str = courseNumber + " " + courseName+ "\n"+
instr+"\n" +
text;
return str;}}
And finally the TextBook class:
import java.text.*;
import java.util.*;
public class TextBook
{
DecimalFormat df = new DecimalFormat("$0.00");
private String title; // Title of the book
private String author; // Author's last name
private double price; // Wholesale cost of the book
public TextBook(String t, String a, double p){
title = t;
author = a;
price = p;}
public TextBook(TextBook object2){
title = object2.title;
author = object2.author;
price = object2.price;}
public void setTitle(String t){
title=t;}
public void setAuthor(String a){
author=a;}
public void setPrice(String p){
price=p;}
public void getTitle(){
return title;}
public void getAuthor(){
return author;}
public void getPrice(){
return price;}
public String toString(){
String str = "Required Textbook: \n" + " " + title+", " + author + ", " + df.format(price);
return str;}}
why does .setLastName() not work but .setName() does
In your class that has this
public void setLastName(String lname){
lastName=lname;
}
Make sure lastName exists as class variable. I am guessing this should be like:
private String lastName;
If you post your Course.java code, we all would be better equipped to explain what might be missing.