Problems when creating methods in my task - java

The goal is to produce this:
Picture of the task summary here
These are the errors I get when I try to compile:
screen shot
I have changed and fixed most of the more obvious errors I think which was mainly just stupid of me. Sorry.
I have this code
public class Ex5Program {
public void start() {
Tutor[] tutors = createTutorsArray();
printTutors(tutors);
printOnLeaveList(tutors);
updateTutorDetails(tutors[1]);
printNewTutorDetails(tutors[1]);
Tutor tutorWithMostPapers = getTutorWithMostPapers(tutors);
printTutorWithMostPapers(tutorWithMostPapers);
}
private Tutor[] createTutorsArray() {
String[] noPapers = {};
String[] introductoryPapers = {"CompSci101", "CompSci111"};
String[] coreStage1Papers = {"CompSci101", "CompSci105"};
String[] allStageOnePapers = {"CompSci111", "CompSci101", "CompSci105"};
String[] stageTwoPapers = {"CompSci210", "CompSci220", "CompSci225", "CompSci230"};
Tutor[] tutors = new Tutor[7];
tutors[5] = new Tutor("Sad Sack", 86302, introductoryPapers, false);
tutors[4] = new Tutor("Crystal Ball", 49123, introductoryPapers, false);
tutors[2] = new Tutor("Earl Lee Riser", 40879, allStageOnePapers, true);
tutors[3] = new Tutor("Tom Katt", 50876, stageTwoPapers, false);
tutors[1] = new Tutor("Candy Kane", 30869, noPapers, false);
tutors[0] = new Tutor("Carrie Oakey", 30987, coreStage1Papers, true);
tutors[6] = new Tutor("Sonny Day", 49586, stageTwoPapers, true);
return tutors;
}
private void printTutors(Tutor[] tutors) {
System.out.println("Current Tutors");
System.out.println("==============");
for (int i = 0; i < tutors.length; i++) {
System.out.print(i + 1 + ". ");
System.out.println(tutors[i].toString());
}
}
private void printOnLeaveList(Tutor[] tutors) {
System.out.println();
System.out.println("Tutors Currently on Leave");
System.out.println("=========================");
for (int i = 0; i < tutors.length; i++) {
if (tutors[i].isOnLeave()) {
System.out.println(tutors[i].getName());
}
}
}
private void updateTutorDetails(Tutor tutor) {
tutor.setName("Ali Katt");
tutor.setStaffId(23456);
String[] stage1Papers = {"CompSci101", "CompSci105", "CompSci111"};
tutor.setPapers(stage1Papers);
tutor.setOnLeave(true);
}
private void printNewTutorDetails(Tutor tutor) {
System.out.println();
System.out.println("Updated details");
System.out.println("===============");
System.out.println("Name: " + tutor.getName());
System.out.println("Id: " + tutor.getStaffId());
String[] papers = tutor.getPapers();
System.out.print("Papers: ");
if (papers.length > 0) {
for (int i = 0; i < papers.length; i++) {
System.out.print(papers[i] + " ");
}
} else {
System.out.print("None");
}
System.out.println();
if (tutor.isOnLeave()) {
System.out.println("Currently on leave");
}
}
private Tutor getTutorWithMostPapers(Tutor[] tutors) {
Tutor tutorWithMostPapersSoFar = tutors[0];
for (int i = 0; i < tutors.length; i++) {
if (tutors[i].teachesMorePapersThan(tutorWithMostPapersSoFar)) {
tutorWithMostPapersSoFar = tutors[i];
}
}
return tutorWithMostPapersSoFar;
}
private void printTutorWithMostPapers(Tutor tutorWithMostPapers) {
System.out.println();
System.out.println("Most papers");
System.out.println("===========");
System.out.println(tutorWithMostPapers.getName() + " teaches more papers than any other tutor.");
}
}
and I created this code here(It has been changed):
public class Tutor {
// instance variables
private String name;
private int staffId;
private String[] papers;
private boolean onLeave;
public Tutor(String name, int staffId, String[] papers, boolean onLeave) {
// Complete this constructor method
this.name = name;
this.staffId = staffId;
this.papers = papers;
this.onLeave = onLeave;
}
// Insert getName() method here
public String getName(){
return name;
}
// Insert setName() method here
public void setName(String name){
this.name = name;
}
// Insert getStaffId() method here
public int getStaff(){
return staffId;
}
// Insert setStaffId() method here
public void setStaffId(int StaffId){
this.staffId = staffId;
}
// Insert getPapers() method here;
public String[] getPapers(){
return papers;
}
// Insert setPapers() method here
public void setPapers(String[] papers){
this.papers = papers;
}
// Insert isOnLeave() method here
public boolean isOnLeave(){
return onLeave;
}
// Insert setOnLeave() method here
public void setOnLeave(boolean OnLeave){
this.onLeave = onLeave;
}
// Insert toString() method here
public String toString(){
return name + "(Staff id:"+staffId+")";
}
// Insert teachesMorePapersThan() method here
public Tutor teachesMorePapersThan(Tutor other){
return(papers.length>other.papers.length);
}
}

Typo: toString() not tostring(), which results in Object.toString() is being invoked and the intended formatted string is not being returned. Change to:
#Override public String toString()
Using the #Override annotation would have produced a compiler error in the case of tostring() being the method name and alerted you to the error, because no method of that name exists in a superclass.
Several of the setter methods have missing parameters:
// Insert setPapers() method here
public void setPapers(){
this.papers = papers;
}
// Insert setOnLeave() method here
public void setOnLeave(){
this.OnLeave = OnLeave;
}

First error: setStaffID()
You are calling it using an int, but on your method you say it doesn't have any parameter.
Take a look that you have some others errors caused by the same mistake. Correct them first...

You need to look at the error text to find the problems. While a newbie may instinctively just dismiss the error messages as uselesss (as a result of years of clicking the x or cancel or whatever on windows dialogues), The error text is actually the most useful resource for figuring out what the error is, 90% of the time.
For instance, the first error reads
File: F:\course related stuff\101\Lab06\Ex5\Ex5Program.java [line: 54]
Error: method setStaffId in class Tutor cannot be applied to given types;
required: no arguments
found: int
reason: actual and formal argument lists differ in length
If you read it carefully, you can see it tells you the name of the file, the line number, the method call name, the class name containing the method, and some additional information about the exact type of error. It is even telling you what you did wrong in calling the method, by putting an "int" where "no arguments" were required, that the "actual and formal argument lists differ in length".
Read the other error messages, and you will see that they actually tell you what the problem is.
This code also needs newlines inserted to group blocks of stuff, comments added to explain exactly how it works, and a few java style violations fixed - some teachers grade for style and clarity as well as just functionality.
Also, if the reason you are failing your class is because you don't understand how to program, it may be because of excessive use of stack overflow to solve the problems. In the real world, if you can just use somebody else's code, that's great, but the point of a programming class is is to teach you how to come up with your own code, not how to use somebody else's.

Well it's not easy to help, because i think you don't know what you are doing. But first thing when you create a set method like this:
public void setPapers(){
this.papers = papers;
}
you should declare the arguments like this:
public void setPapers(String[] papers){
this.papers = papers;
}
and you should know that variables names is caseSensitive so :
private boolean onLeave;
public boolean isOnLeave(){
//return OnLeave; this variable is not declared
return onLeave;
}
I think you need to study a little more, because you can't read the compilation errors.

Related

Recursion in java with objects of courses and prerequisites

Good day, is there a more efficient way to do this problem with recursion than using a switch statement. In my courses class I have a recursive association of course and a prerequisite then a set the preReqs in the PreReqs class. How can I print out all of preReqs of a class when a user enter a class which has preReqs? Right now I am in the process of using a switch statement and printing each preReq individually but is there a better way to do this still using recursion?
An example out of this: If the user types that course, all of the preReqs will print out too.
ACS-3947 Algorithm Design
prereq: ACS-2947 Data Structures and Algorithms
ACS-2947 Data Structures and Algorithms
prereq: ACS-1904 Programming Fundamentals II
ACS-1904 Programming Fundamentals II
prereq: ACS-1903 Programming Fundamentals I
ACS-1903 Programming Fundamentals I
no prereq
Course class:
import java.util.*;
public class Course
{
protected String courseNumber;
protected String courseName;
protected Course prerequisite;
public Course(){
courseNumber = courseName = "Unknown";
prerequisite= null;
}
public Course (String cn, String num){
this.courseNumber=num;
this.courseName=cn;
}
public String getCourseNumber(){
return courseNumber;
}
public String getCourseName(){
return courseName;
}
public Course getPreReq(){
return prerequisite;
}
public void setCourseNumber(String courseNumber){
this.courseNumber=courseNumber;
}
public void setCourseName(String courseName){
this.courseName=courseName;
}
public void setPreReq(Course pr){
prerequisite =pr;
}
}
PreReq class:
import java.util.*;
import java.io.*;
public class Prereqs
{
public static void main (String [] args){
Scanner kb = new Scanner (System.in);
Course nineteen03 = new Course ("Programming Fundamentals I","ACS-1903");
Course nineteen04 = new Course ("Programming Fundamentals II"," ACS-1904");
Course two47 = new Course ("Data Structures and Algorithms","ACS-2947 ");
Course three47 = new Course ("Algorithm Design","ACS-3947");
Course two09 = new Course ("Internet Programming","ACS-2909");
Course three09 = new Course ("Advanced Internet Programming ","ACS-3909");
nineteen04.setPreReq(nineteen03);
two47.setPreReq(nineteen04);
three47.setPreReq(two47);
two09.setPreReq(nineteen03);
three09.setPreReq(nineteen03);
System.out.println("Enter course number with the format: AAA-999");
String input = kb.next();
validate(input);
}
public static void course(Course nineteen04, Course nineteen03,Course two47, Course three47, Course two09, Course three09, String input ){
Course c1 = nineteen04.getPreReq();
Course c2 = two47.getPreReq();
Course c3 = three47.getPreReq();
Course c4 = two09.getPreReq();
Course c5 = three09.getPreReq();
switch (input){
case "ACS-1904":
System.out.println(nineteen04.getCourseName()+" "+nineteen04.getCourseNumber());
System.out.println("preReq: " + c1.getCourseName()+ " "+ c1.getCourseNumber());
}
}
public static String validate (String input)
{
String arg = input;
boolean valid = arg.length()==7;
if (!valid){
throw new IllegalArgumentException("Not the correct format: AAA-999");
}
valid = arg.charAt(3) == '-';
if(!valid) {
throw new IllegalArgumentException("Not the correct format: AAA-999");
}
for(int i=0; i < 3 && valid; i++){
valid = ((i == 3 && Character.isLetter(arg.charAt(i))));
}
for(int i=3; i < 3 && valid; i++){
valid = ((i==6 && Character.isDigit(arg.charAt(i))));
}
return arg;
}
}
A recursive method needs to contain a condition which terminates the recursion. Your list of courses and their prerequisites remind me of a linked list where each course points to its prerequisite. The list terminates when we reach a course that has no prerequisite. The below code is your Course class with the addition of a main method (imported from your Prereqs class) and the recursive method which I named requirements(). I also added method toString() to make the display of the list of courses and their prerequisites more "human readable". You can experiment by changing the course passed to the initial invocation of method requirements().
public class Course {
protected String courseNumber;
protected String courseName;
protected Course prerequisite;
public Course(){
courseNumber = courseName = "Unknown";
prerequisite= null;
}
public Course (String cn, String num){
this.courseNumber=num;
this.courseName=cn;
}
public String getCourseNumber(){
return courseNumber;
}
public String getCourseName(){
return courseName;
}
public Course getPreReq(){
return prerequisite;
}
public void setCourseNumber(String courseNumber){
this.courseNumber=courseNumber;
}
public void setCourseName(String courseName){
this.courseName=courseName;
}
public void setPreReq(Course pr){
prerequisite =pr;
}
public String toString() {
return courseNumber + " " + courseName;
}
private static void requirements(Course c) {
if (c == null) {
return;
}
else {
System.out.println(c);
requirements(c.getPreReq());
}
}
public static void main(String[] args) {
Course nineteen03 = new Course ("Programming Fundamentals I","ACS-1903");
Course nineteen04 = new Course ("Programming Fundamentals II"," ACS-1904");
Course two47 = new Course ("Data Structures and Algorithms","ACS-2947 ");
Course three47 = new Course ("Algorithm Design","ACS-3947");
Course two09 = new Course ("Internet Programming","ACS-2909");
Course three09 = new Course ("Advanced Internet Programming ","ACS-3909");
nineteen04.setPreReq(nineteen03);
two47.setPreReq(nineteen04);
three47.setPreReq(two47);
two09.setPreReq(nineteen03);
three09.setPreReq(nineteen03);
requirements(three09);
}
}
Running the above code displays the following:
ACS-3909 Advanced Internet Programming
ACS-1903 Programming Fundamentals I

ArrayList not storing a value

In my main, I am asking the user 2 questions. Both questions have 2 correct answers, which is choice number 2 and 4. Whenever I run the Code and select option 2(for both questions), it results in false. If I run the program and select option 4, it results in true. Both options 2 and 4 are correct. I feel as if the issue is due to my UpdateChoices method(located in MultiCheck class), but I don't know why. I used an ArrayList to save the correct choices, but the first correct choice (option 2) is not saved, resulting in it displaying false. Is there a reason why the first option isn't saved in the ArrayList? My output window is posted below the code.
This is the code I have: Main
package pa4_pandeyay;
import java.util.Scanner;
public class MyQuestionDemo {
public static void main(String[] args) {
// TODO code application logic here
MultiCheck first = new MultiCheck();
first.setText("Which number below is prime?");
first.UpdateChoices("4", false);
first.UpdateChoices("3", true);
first.UpdateChoices("12", false);
first.UpdateChoices("7", true);
first.UpdateChoices("8", false);
MultiCheck second = new MultiCheck();
second.setText("Which number below multiplied equals to 12?");
second.UpdateChoices("4 * 4", false);
second.UpdateChoices("12 * 1", true);
second.UpdateChoices("12 * 2", false);
second.UpdateChoices("-6 * -2", true);
second.UpdateChoices("0 * 12", false);
presentQuestion(first);
presentQuestion(second);
}
public static void presentQuestion(MultiCheck x){
x.display();
System.out.print("Your answer: ");
Scanner sc = new Scanner(System.in);
String response = sc.nextLine();
System.out.println(x.checkAnswer(response));
}
}
Java class Question.java
package pa4_pandeyay;
public class Question {
private String text;
private String answer;
// Create a constructor
public Question(){
text = "";
answer = "";
}
// Set the question text
public void setText(String questionText){
text = questionText;
}
//Set the answer text
public void setAnswer(String correctAnswer){
answer = correctAnswer;
}
// Check the respond with the actual correct answer
public boolean checkAnswer(String response){
return response.equals(answer);
}
public String getText(){
return text; // since variable text it private, we need to create a get method in order to access the private variable
}
// Diplay question to the user:
public void display(){
System.out.println(text);
}
}
Java class MultiCheck:
package pa4_pandeyay;
import java.util.ArrayList;
public class MultiCheck extends Question{
private ArrayList<String> answerChoices;
public MultiCheck(){
super();
answerChoices = new ArrayList<String>();
}
public void UpdateChoices (String choice, boolean correct){ // check the asnwers and save the 'true' answers
answerChoices.add(choice);
if (correct == true)
{
//convert choices.size() to string
String choiceString = "" + answerChoices.size();
setAnswer(choiceString);
}
}
// when calling display, this method will be called.
#Override
public void display(){
System.out.println(getText());
// Display the answer choices
for( int i =0; i< answerChoices.size(); i++){
int choiceNumber = i + 1;
System.out.println(choiceNumber + " : " + answerChoices.get(i));
}
}
The Question class can only store one correct answer by setAnswer(). If you have multiple correct answers, then they will override each other so that only the last one is finally in memory.

android studio: having trouble setting global string array

Hi I'm working on an android studio project using global arrays,
I can read from the global arrays fine, and have no problem writing
to the global integers ,But i cannot figure out how to set the global
array from code, this is the important parts of the project:
added this under application tag in the android manifest xml:
android:name=".Globals"
java class Globals:
import android.app.Application;
public class Globals extends Application {
public int empnum=13;
public int getData3() {
return empnum;
}
public void setData3(int empnum) {
this.empnum = empnum;
}
public String[] passw = {"0123","0123","0123","0123","0123","0123","0123","0123","0123","0123","0123","0123","0123"};
public String[] getData4() {
return passw;
}
public void setData4(String[] passw) {
this.passw = passw;
}
public int login=0;
public int getData5() {
return login;
}
public void setData5(int login) {
this.login = login;
}
public String[] empname = {"Name1","Name2","Name3","Name4","Name5","Name6","Name7","Name8","Name9","Name10","Name11","Name12","Name13","Not logged in"};
public String[] getData6() {
return empname;
}
public void setData6(String[] empname) {
this.empname = empname;
}
Here is the block of code I'm having trouble with
inner class of java class TimeIn:
final Globals g = (Globals) getApplication();
final String[] empname = g.getData6();
final String[] passw = g.getData4();
public void onClick(View v) {
i = 0;
String empname = edit2.getText().toString();
int getemn = Integer.parseInt(edit.getText().toString());
if (i == 0 && h == 0) {
g.setData3(getemn);
g.setData6(String[getemn], empname); // This one line right here won't compile, I have tried different combinations but have had 0 luck
i = 1;
h = 1;
}
}
I have no problems getting and using a String array, this is how it works to get
an array value and compare it to a string:
public void onClick(View v) {
i = 0;
String getemp = edit2.getText().toString();
int getemn = Integer.parseInt(edit.getText().toString());
if (i == 0 && getemp.equals(passw[getemn])) { // All of this works perfectly
g.setData3(getemn);
g.setData5(0);
tfone.setText("Empoyee " + getemn);
tftwo.setText("Logged in");
i = 1;
}
if (i == 0 && getemp != (passw[getemn])) {
tfone.setText("No matches found");
edit2.setText("Not logged in");
i = 1;
}
}
So I know this line of code is wrong:
g.setData6(String[getemn], empname);
but for
the life of me I can't figure out how it should be written, the only error hint is I
get from hovering over the line-
array type expected; found 'java.lang.String'
Anyone know what I'm doing wrong?
In Global class, you declare the method with one parameter
public void setData6(String[] empname) {
this.empname = empname;
}
but when you call, you put 2 parameters g.setData6(String[getemn], empname);
You should remove one parameter
or add another method with 2 parameters in Globals class
Also
You are wrong in here
...
String empname = edit2.getText().toString();
int getemn = Integer.parseInt(edit.getText().toString());
...
g.setData6(String[getemn], empname); // This one line right here won't compile, I have tried different combinations but have had 0 luck
The setData6 function now require 2 parameters, one is String array and the other is String
but the way you put the String array to the function is wrong
Here is a simple example that show how to pass the String array to function
public class Test {
public static void setData6(String[] empnameList, String empname) { // with the `String array` you should declare the variable name like `empnameList` or `arrEmpname` NOT `empname` because `empname` make confusing when you read code
this.empnameList = empnameList;
this.empname = empname;
}
public static void main(String[] args) {
String[] strArray = new String[]{"Name1","Name2","Name2"};
String empName = "Na";
setData6(strArray,empName); // call method with 2 parameters here
}
}
Hope this help
Solved!! it turns out I had to modify my setter part of my Globals class, so this first part (the getter method) in the Globals class is correct:
public String[] compname = {"Manager's company", "Company2", "Company3", "Company4", "Company5", "Company6", "Company7", "Company8", "Company9", "Company10", "Company11", "Company12", "Company13", "Not punched in"};
public String[] getData7() {
return compname;
}
I had to change the getter part of my Globals class to this:
public int setcmpn = 0; // <-- Edited, this should equal some integer value
public void setData7(int setcmpn, String compname) { // removed [] from 2nd argument
this.setcmpn = setcmpn;
this.compname[setcmpn] = compname; // added in [] after array's name and fill it with the first argument from setData7 method
}
And to set the value of the desired index from any class just use:
Globals g = (Globals) getApplication();
g.setData7(getemn, getemp);
where getemn is an integer and getemp is a string.

"error: cannot find symbol" regarding on Inheritance-related program

I got a message says error: cannot find symbol regarding on c1.certificateAwarded(grade); statement. I have no idea what is the problem. Really need all the help I can get.
Here's the code:
ExamDetails.java
package Exams;
import javax.swing.JOptionPane;
public class ExamDetails {
public static void main(String[] args) {
StudentResults sr = new StudentResults();
sr.inputStudentName();
sr.inputExamName();
sr.inputScore();
sr.inputGrade();
sr.DisplayDetails();
Certificates c1 = new Certificates();
c1.certificateAwarded(grade);
}
}
StudentResults.java
package Exams;
import javax.swing.JOptionPane;
public class StudentResults {
private String fullname;
private String examName;
private int examScore;
private int examGrade;
public String getStudentName()
{
return fullname;
}
public void setStudentName(String name)
{
fullname = name;
}
public String getExamName()
{
return examName;
}
public void setExamName(String exam)
{
examName = exam;
}
public int getExamScore()
{
return examScore;
}
public void setExamScore(int score)
{
examScore = score;
}
public int getExamGrade()
{
return examGrade;
}
public void setExamGrade(int grade)
{
examGrade = grade;
}
public void inputStudentName()
{
fullname = JOptionPane.showInputDialog("Enter the student's name");
}
public void inputExamName()
{
examName = JOptionPane.showInputDialog("Enter the subject's name");
}
public void inputScore()
{
String scoreString = new String();
JOptionPane.showInputDialog("Enter the student's score");
examScore = Integer.parseInt(scoreString);
}
public void inputGrade()
{
String gradeString = new String();
JOptionPane.showInputDialog("Enter the student's grade");
examGrade = Integer.parseInt(gradeString);
}
public String DisplayDetails()
{
String d;
d = "Student Name : " + fullname + "Exam Name : " + examName + "Score : " + examScore + "Grade : " + examGrade;
return d;
}
}
Certificates.java
package Exams;
public class Certificates extends StudentResults {
private String certificate;
public String Grade;
Certificates()
{
super();
certificate = "No Certificate Awarded";
}
String certificateAwarded(/*int grade*/) {
//StudentResults g = new StudentResults();
//Grade = g.inputGrade();
//Grade = inputGrade(examGrade);
if(Grade.equals("Grade : A"))
{
this.certificate = "Certificate of Excellence";
}
else
if(Grade.equals("Grade : B"))
{
this.certificate = "Certificate of Achievement";
}
else
if(Grade.equals("Grade : C"))
{
this.certificate = "Certificate of Achievement";
}
else
this.certificate = "No Certificate Awardedt";
return this.certificate;
}
}
In the ExamDetails.java class, you don't declare or instantiate the grade variable that you're passing to the certificateAwarded method.
Also, you have parameters commented out in your Certificates.java class. You should uncomment the parameter.
For your code to compile, grade would have to be either
a local variable declared within the main method
a field defined on the ExamDetails class
Neither of these declarations are present so the compiler is telling you that it can't find the grade "symbol".
Try adding int grade = sr.getExamGrade(); above the problem line, or something similar.
As the comment suggested, you need to have "grade" declared. Without it, the compiler can't complete determining what the signature is for Certficates.certificateAwarded, since what goes in the argument list is part of the signature. More importantly, you have this in your code:
String certificateAwarded(/* int grade */)
The parameter, "int grade" is commented out. So the compiler sees this:
String certificateAwarded( )
So, what the compiler might be telling you is that it is looking for a method of Certificates named certificateAwarded that takes 1 argument of type {whatever type "grade" is}. It doesn't find that.
I said "might be" because you are missing two symbols on the line in question: grade and a method with a matching signature.
I can think of two things you can try to fix it:
Change " c1.certificateAwarded(grade);" to "c1.certificateAwarded();"
Declare "grade" to be an int somewhere in main (or in a place that is visible within main) and change "String certificateAwarded(/int grade/)" to "String certificateAwarded(int grade)".
I would start by trying the first option. If it is necessary to try the second, you will need to add additional code in both main (or place where grade is visible to main) and in the certificateAwarded method.

Java - Using an object inside an object

I am working on a project ( I had a problem yesterday and so many people helped me!) so I decided to ask for help again.
My code has 3 classes. ProjectMain,Students,Classroom. I created an array of Classroom objects. Right now I have 3 Classroom objects. But I have to assign student objects to these Classroom objects. For example : classarray[0] is an object from Classroom class and studentobject.get(0) , studentobject.get(1) ... will be students objects inside classarray[0] object. But I have failed on this while coding. Here are my classes :
public class Classroom
{
private String classname;
private String word[] = null;
protected ArrayList<Students> studentobject = new ArrayList<Students>(10);
public String[] getWord()
{
return word;
}
public void setWord(String[] word)
{
this.word = word;
}
public ArrayList<Students> getStudentobject()
{
return studentobject;
}
public void setStudentobject(ArrayList<Students> studentobject)
{
this.studentobject = studentobject;
}
public String getClassname()
{
return classname;
}
public void setClassname(String classname)
{
this.classname = classname;
}
public void classroomreader(String filename)
{
// This method gets the name of Classroom
File text = new File("C:/Users/Lab/Desktop/classlists/" + filename
+ ".txt");
Scanner scan;
try
{
scan = new Scanner(text);
String line = scan.nextLine();
word = line.split("\t");
line = scan.nextLine();
word = line.split("\t");
} catch (FileNotFoundException e1)
{
e1.printStackTrace();
}
}
}
This is my student class :
public class Students extends Classroom
{
private String name,id;
private int age;
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public String getId()
{
return id;
}
public void setId(String id)
{
this.id = id;
}
public int getAge()
{
return age;
}
public void setAge(int age)
{
this.age = age;
}
And my main class :
public class ProjectMain
{
public static void main(String[] args)
{
Classroom[] classarray = new Classroom[3];
//I got 3 Classroom objects here
classarray[0]=new Classroom();
classarray[1]=new Classroom();
classarray[2]=new Classroom();
classarray[0].classroomreader("class1");
classarray[0].studentobject.get(0).setName(classarray[0].getWord()[1]);
//The problem is in here. When my code comes to the line above,
// at java.util.ArrayList.rangeCheck(Unknown Source) error comes out.
// I tried to get first object in studentobject Arraylist, and tried to set it's name
// to the variable which my text reader reads.
How can I write what I have in my mind?
Your classroomreader method reads the file but don't do much of it... maybe you want to create some instance of Students within it.
scan = new Scanner(text);
String line = scan.nextLine();
word = line.split("\t"); // won't be used
line = scan.nextLine();
word = line.split("\t"); // erased here
There you only have the last line (split) of the file in word attribute.
When creating Classroom instance studentobject list is created empty and it stays that way so you can't access first (or any) object in it.
To populate your list you may add to Classroom method like this:
public void addStudent(Student s)
{
studentobject.add(s);
}
classroom contains the following field declaration
String word[] = null;
the main class, incl the classroomreader does not set a value to this field. Yet you are going to invoke
classarray[0].getWord()[1]
which then must fail.
tip: don't use expressions like this, which can be found in your main class (at least not in early stages of development, or learning)
classarray[0].studentobject.get(0).setName(classarray[0].getWord()[1]);
resolve into variables and several steps. Compilers are smart enough to produce the same code if the context is not disturbed, ie the long expression is resolved into a single block.
Never forget that the purpose of programming languages is to make programs readable for humans. :) Code with abbreviations or "tricks" simply shows some philodoxical attitude (imho)

Categories

Resources