Comparing user inputted string to an array variable Java - java

I've included my program below, basically my question is if I input a surname to allow me to find the student I want to delete how can I compare the inputted string to the surname variable in the array?
When I enter the surname and try and compare this to the entries already in the array instead of comparing the surnames it's comparing the inputted string to everything in that instance of it. This is being done in the findStudent method.
I think because i'm passing the entire array here surname contains everything I've entered for that student (surname, forename, exam marks). If I try and just pass the surname parameter i'm getting error messages.
I've searched to see if this was answered already but all I can find is comparing an inputted string to an array that is already defined not an array created from user input.
Any help would be appreciated!
Thanks
import java.util.Scanner;
/**
*
* #author Connor
*/
public class Student {
//declare student variables
private String surname;
private String forename;
private int mark1, mark2, mark3;
private double dblScore;
private static String course = "French";
//constructor
//===========================================================
//
// MODULE : Student
// RETURN TYPE : None
// PARAMETERS : args : String newForename, String newSurname, int newMark1, int newMark2, int newMark3
// DESCRIPTION : Construct Student object
//============================================================
public Student(String newForename, String newSurname, int newMark1, int newMark2, int newMark3) {
this.forename = newForename;
this.surname = newSurname;
this.mark1 = newMark1;
this.mark2 = newMark2;
this.mark3 = newMark3;
this.dblScore = (this.mark1 + this.mark2 + this.mark3) / 3;
}
//===========================================================
//
// MODULE : getCourse
// RETURN TYPE : String course
// PARAMETERS : args :
// DESCRIPTION : get course name
//============================================================
public static String getCourse() {
return course;
}
//===========================================================
//
// MODULE : setCourse
// RETURN TYPE : course
// PARAMETERS : args :
// DESCRIPTION : set course name
//============================================================
public static String setCourse(String newCourse) {
course = newCourse;
return course;
}
//display student details method
//===========================================================
//
// MODULE : displaydetails
// RETURN TYPE : None
// PARAMETERS : args : [DEFAULT]
// DESCRIPTION : write out student details -
// name, course and exam marks
//============================================================
public void displaydetails() {
System.out.println(" ");
System.out.println("Student details - ");
System.out.println("Name - " + surname + " " + forename);
System.out.println("Course - " + course);
System.out.println("exam scores - " + mark1 + " " + mark2 + " " + mark3);
System.out.println("Overall score - " + dblScore);
System.out.println(" ");
}
}
class StudentMenu {
//===========================================================
//
// MODULE : add student
// RETURN TYPE : None
// PARAMETERS : args : studentArray, numStudents
// DESCRIPTION : requests user input to add student to array.
// Upto 6 students can be entered
//============================================================
public static void addStudent(Student[] studentArray, int numStudents) {
String newSurname, newForename;
int newMark1, newMark2, newMark3;
Scanner input = new Scanner(System.in);
System.out.println("1. Add a student");
System.out.println(" ");
System.out.println("Student surname - ");
newSurname = input.next();
input.nextLine();
System.out.println("Student forename - ");
newForename = input.next();
input.nextLine();
System.out.println("First exam mark - ");
newMark1 = input.nextInt();
input.nextLine();
System.out.println("Second exam mark - ");
newMark2 = input.nextInt();
input.nextLine();
System.out.println("Third exam mark - ");
newMark3 = input.nextInt();
input.nextLine();
studentArray[numStudents] = new Student(newSurname, newForename, newMark1, newMark2, newMark3);
}
//===========================================================
//
// MODULE : find student
// RETURN TYPE : int position
// PARAMETERS : args : surname, delSurname, position
// DESCRIPTION : finds the position of the selected student
// in the array
//============================================================
public static void findStudent(Student[] surname,String delSurname, int position, int totalStudents) {
int index;
for (index = 0; index < totalStudents; index++) {
// if (surname[index].equals(delSurname)) {
if (surname[index].equals(delSurname)) {
position = index;
} else {
index++;
}
}
}
//===========================================================
//
// MODULE : delete student
// RETURN TYPE : None
// PARAMETERS : args : myClass, position, NUM_STUDENTS
// DESCRIPTION : deletes chosen student from array. Moves
// all other entries down by one
//============================================================
public static void deleteStudent(Student[] myClass, int position, int NUM_STUDENTS) {
int index = 0;
for (index = position + 1; index < NUM_STUDENTS; index++) {
myClass[index - 1] = myClass[index];
}
}
//===========================================================
//
// MODULE : main method
// RETURN TYPE : None
// PARAMETERS : args : myClass, position, NUM_STUDENTS
// DESCRIPTION : runs menu program allowing user input
// to add/modify/delete student information
//============================================================
public static void main(String[] args) {
//declare scanner
Scanner input = new Scanner(System.in);
//declare variables
boolean menu = true;
int option;
int totalStudents = 0;
final int NUM_STUDENTS = 6;
int position = 0;
String delSurname, newCourse;
//array
Student[] myClass;
myClass = new Student[NUM_STUDENTS];
//main method
//menu
while (menu != false) {
System.out.println("1. Add a student");
System.out.println("2. Delete student");
System.out.println("3. Display all students");
System.out.println("4. Change course details");
System.out.println("5. Search for student");
System.out.println("6. Exit program");
// enter choice
System.out.print("Please enter selection - ");
option = input.nextInt();
System.out.println(" ");
// calling methods using switch
if ((option > 6) || (option < 1)) {
System.out.println("Invalid selection made - reenter. Between options 1-6 only.");
} else {
switch (option) {
case 1:
//option 1 - add student
addStudent(myClass, totalStudents);
totalStudents++;
break;
case 2:
//option 2 - delete student
System.out.println("Student surname to delete - ");
delSurname = input.next();
input.nextLine();
findStudent(myClass,delSurname, position, totalStudents);
if (position >= 0 && position < NUM_STUDENTS) {
deleteStudent(myClass, position, NUM_STUDENTS);
}
totalStudents--;
break;
case 3:
//option 3 - display details
Student.getCourse();
for (int index = 0; index < totalStudents; index++) {
myClass[index].displaydetails();
}
break;
case 4:
//option 4 - change course
Student.getCourse();
System.out.println();
System.out.println("Enter new course details - ");
newCourse = input.next();
input.nextLine();
Student.setCourse(newCourse);
break;
case 5:
//option 5 - search for student by name
System.out.println("Student surname to display - ");
delSurname = input.next();
input.nextLine();
findStudent(myClass,delSurname, position, totalStudents);
if (position >= 0 && position < NUM_STUDENTS) {
myClass[position].displaydetails();
}
break;
case 6:
//option 6 - exit program
menu = false;
break;
}
}
}
}
}

you'll have to check if surname[index].surname.euqals(delSurname) because in your surname array you have Students and not the strings
Right now your code checks if an instance of the class Student is equal to an instance of the class String, which cannot.

Related

Issue dropping credits from course in Java dropCourse Method

What I have is a two snippets of code. The question I have in particular is about my dropCourse method within the student driver. Everything in my code seems to work fine except when I drop a course it does not drop the courses credits. For example, if I drop a course named "Computer101" which had four credits, it will remove "Computer101" From the schedule, but will not remove the "4" credits when I choose option 5 to print the total credits. So if we have a full schedule of:
Computer101 in position 0 worth 4 credits
Physics105 in position 1 worth 4 credits
Art101 in position 2 worth 4 credits
Chem101 in position 3 worth 4 credits
And I decide to drop Computer101 from the schedule, all other classes will move up in their position in the array as they are supposed to, when printing the schedule that class will no longer show up and when it is searched for it will not be found, but the amount of credits it was worth will still be there. I feel like the solution is right in front of me, but I am so burned out I am not seeing it. I would really appreciate any help and I hope I was clear with what I am asking.
Here is where my dropCourse method will be found:
public class Student
{
//Instance Data
String studentName;
String studentID;
String streetAddress;
String city;
String state;
String zipCode;
String major;
final int MAX_CREDITS = 18;
int courseNumber = 0; //start out with no courses
int totalCredits;
final int SIZE = 6;
String [ ] schedule = new String [SIZE];
//Create Constructor:
//Initializes the student data at instantiation time.
//-------------------------------------------------------
// Sets up the student's information.
//-------------------------------------------------------
public Student (String name, String id, String address, String cityName, String stateName, String zip, String area )
{
studentName = name;
studentID = id;
streetAddress = address;
city = cityName;
state = stateName;
zipCode = zip;
major = area;
}//end Student Constructor
//Method to Return student information as string:
//-------------------------------------------------------
// Returns the student information as a formatted string.
//-------------------------------------------------------
public String toString()
{
String studentInfo;
studentInfo = "Name:\t\t\t" + studentName + "\n" + "ID:\t\t\t" + studentID + "\n" + "Address:\t\t" + streetAddress
+ "\n" + "City:\t\t\t" + city + "\n" + "State:\t\t\t" + state + "\n" + "Zip Code:\t\t" + zipCode
+ "\n" + "Major:\t\t\t" + major + "\n";
return studentInfo;
}// end toString
//Method to determine if maximum allowed credits have been exceeded
//-------------------------------------------------------
// Returns true if total credits does not exceed 18.
//-------------------------------------------------------
private boolean checkCredits(int numCredits)
{
if (numCredits + totalCredits <= MAX_CREDITS) //make sure max credits not exceeded
{
return true; //return a true if still less than 18 credits
}
else
{
return false; //return a false if 18 credit limit is exceeded
}//end numCredits
}//checkCredits
//Method to add a course to the student’s schedule
//-------------------------------------------------------
// Adds a course to the array if total credits does not exceed 18.
//-------------------------------------------------------
public void addCourse(String course, int numCredits)
{
if (courseNumber < SIZE ) //make sure array is not full.
{
if (checkCredits(numCredits) == true) //if we’re under 18 credits
{
//add course
schedule [courseNumber] = course + ":\t\t" + numCredits + "\tCredits\n";
//increment number of credits
totalCredits = totalCredits + numCredits;
//increment number of courses
courseNumber = courseNumber + 1;
System.out.println("The course has been added!");
}
else //oops – can’t do more than 18 credits
{
System.out.println("You have exceeded the maximum allowed credits.");
}//end checkCredits
}
else //oops – can’t do more than 6 courses
{
System.out.println("You have exceeded 6 courses.");
}//end courseNumber
}//addCourse
public void displaySchedule( )
{
for (int index = 0; index < courseNumber; index++)
{
System.out.println("Course #" + (index + 1) + " " + schedule[index] + "\n");
}//end for
}//end display schedule
public int searchCourse(String courseName)
{
String course;
boolean flag = false;
int index = 0;
while(index < courseNumber && flag == false)
{
String extract = schedule[index].substring(0,6);
if (extract.contains(courseName) == true)
{
flag = true;
}
else
{
index++;
}
}
if (flag == false)
{
return -1;
}
else
{
return index++;
}
}
public void dropCourse(String courseName)
{
int found;
found = searchCourse(courseName);
int index = 0;
if (found == -1)
{
System.out.println("Course not in schedule");
}
else
{
if (found == 5)
{
courseNumber = courseNumber -1;
}
else
{
for (index = found; index < courseNumber; index ++)
{
schedule[index] = schedule[index + 1];
}
courseNumber = courseNumber -1;
System.out.println("The course has been dropped!");
}
}
}
public int totalCredits()
{
System.out.println("The total credits are " + totalCredits);
return totalCredits;
}
}//end class Student
This is where my menu that works with the above code is:
//This is a Driver program to test the external Class named Student
import java.util.Scanner;
public class TheMenu //BEGIN Class Definition
{
//**************** Main Method*************************
static Scanner scan = new Scanner(System.in);
public static void main (String[] args)
{
//Data Definitions:
//Instance Data
String name;
String id;
String street;
String city;
String state;
String zip;
String major;
String courseName;
int courseCredits;
int menu = 0;
//Initialize first Student
name = "Florence Welch";//look her up
id = "7777";
street = "777 Heaven Street";
city = "Witchville";
state = "NY";
zip = "12345";
major = "Arts";
//instantiate the Student object
Student student1 = new Student(name, id, street, city, state, zip, major);
while (menu < 6)//begin while for menu options
{
System.out.println("1. Add a course ");
System.out.println("2. Search for a course");
System.out.println("3. Drop a course");
System.out.println("4. Print out a student's schedule");
System.out.println("5. Print out total credits");
System.out.println("6. Exit");
System.out.println("Enter an option: ");
menu = scan.nextInt();
if (menu == 1)//option to add course
{
System.out.println("Please enter the name of the course: ");
courseName = scan.next();
System.out.println("How many credits is the course? ");
courseCredits = scan.nextInt();
student1.addCourse(courseName, courseCredits);//uses method to store course information in array
}
else if (menu == 2)//option to search for course
{
int x;
System.out.println("Please enter the name of the course: ");
courseName = scan.next();
student1.searchCourse(courseName);
x = student1.searchCourse(courseName);
if (x == -1)//course is not found if value returns -1
{
System.out.println("Course not found");
}
else
{
System.out.println("Course found in position " + student1.searchCourse(courseName));//shows user the position of course
}
}
else if (menu == 3)//will drop course from users schedule
{
System.out.println("Please enter the course you wish to drop: ");
courseName = scan.next();
student1.dropCourse(courseName);
}
else if (menu == 4)//displays the users schedule
{
System.out.println(name + "'s Schedule:\n\n");
student1.displaySchedule();
}
else if (menu == 5)//will display users credits for semester
{
student1.totalCredits();
}
else
{
System.out.println("Enjoy your semester!");//option 6 will exit program
}
}
}
}

Create a program that allows to receive multiples entry data, shows the data from the list

i was told to make a program like that, after input i can see the data
This is my code, please help i had search how to do it but i mostly only if the data is already known not by user input.
is it using an array or using for?
i search many time but i still dont find like mine
ive tried using array but i dont know how to get the array like, there is 3 user input in one array. mostly i found just using one user input
and sometime i get the error where the string cannot meet the int type
import java.util.Scanner;
public class Case7{
public static void main(String[] args) {
Scanner input = new Scanner (System.in);
int choose=0;
String name ="";
String pos = "";
int age = 0;
do{
System.out.println("JOB VACANCY");
System.out.println("===========");
System.out.println("1. Insert new data");
System.out.println("2. List of staff");
System.out.println("3. Search staff");
System.out.println("4. Exit");
System.out.print("Choose: ");
choose = input.nextInt();
if (choose == 1)
{
System.out.println("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
do{
System.out.print("Input staff name: ");
name = input.nextLine();
}while(name.length() < 3 || name.length() > 20);
do{
System.out.print("Input staff position [Manager | Analyst | Programmer]: ");
pos=input.nextLine();
}while(!pos.equalsIgnoreCase("Manager") && !pos.equalsIgnoreCase("Analyst") && !pos.equalsIgnoreCase("Programmer"));
do{
System.out.print("Input staff age: ");
age=input.nextInt();
}while(age <= 17);
System.out.println("Data has been added!");
input.nextLine();
input.nextLine();
System.out.println("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
}
else if (choose == 2)
{
System.out.println("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
for (int i = 1; i < 6 ; i++ )
{
System.out.println("Staff ID :" + i);
System.out.println("==============");
System.out.println("1. name : " +name );
System.out.println("2. position : " +pos );
System.out.println("3. age : " +age );
System.out.println("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
}
}
Can I suggest a radically different implementation?
You can use a switch to score the options and You can use a LinkedList to store all the new staff member dinamically.
Here's my commented code:
static LinkedList<Staffer> staff=new LinkedList<>(); //ours database
static Scanner input = new Scanner (System.in);
public static void main(String[] args) {
String s="";
int number=-1;
while(number!=4){ //if your choice is 4, we can exit!
//Chooser:
System.out.print("JOB VACANCY\n===========\n1. Input data\n2. Show Data\n3.Delete Data\n4.£xit\nYour choice: ");
s=input.nextLine();
if(s.matches("\\d+")){ //Check if s is a number
number=Integer.parseInt(s);
switch(number){
case 1: input(); break;
case 2: showData(); break;
case 3: deleteData(); break;
case 4: System.out.println("Goodbye!"); break;
default: System.out.println("Number not valid. Try again!");
}
}else
System.out.println("Number not valid. Try again!");
}
}
private static void showData() {
for(Staffer st:staff)
System.out.println(st);
}
private static void deleteData(/*parameters*/) {
// You can delete a staffer by passing the name, for example
}
private static void input() {
//Plese, implements your data control options...
String name, position;
int age;
System.out.print("Name: ");
name=input.nextLine();
System.out.print("Position: ");
position=input.nextLine();
System.out.print("Age: ");
age=(Integer.parseInt(input.nextLine()));
Staffer staffer=new Staffer(name,position, age);
staff.add(staffer);
}
public static class Staffer{ //a staff member has 3 parameter: name, position and age... You can add others
/*You should store the name using only upperCase or LowerCase, or
* John Williams != john williams != JOHN WILLIAMS and you can have three times
* the same people.
*
* The position can be converted in enum for the same reason.
*/
private String name, position;
private int age;
public Staffer(String name, String position, int age){
this.name=name;
this.position=position;
this.age=age;
}
#Override
public String toString(){
return "Mr. "+name+", "+position+" (age: "+age+")";
}
}
You can see the following example output:
.
Obviously, you have to improve the output and all the data check options.

Method to Find ArrayList Index to Where the Object Will be Added

I have an ArrayList that is being filled with customer information using a Customer class. In my addCustomerRecord method, I am calling findAddIndex within the addCustomerRecord method so the data entered will be sorted prior to displaying the data. Here is my code and do not mind the fileWhatever method, I don't use it.
public class CustomerDemo
{
//arrayList of customer objects
public static ArrayList<Customer> customerAL = new ArrayList<>();
public static void main (String[] args)
{
//to hold menu choice
String menuChoice = "";
Scanner kb = new Scanner(System.in);
System.out.println("To add a record press 'A': \n"
+ "to display all records press 'D': \n"
+ "to exit press 'Q': \n");
//loop priming read
menuChoice = kb.nextLine();
//make input case insensitive
menuChoice = menuChoice.toLowerCase();
do
{
if(menuChoice.equals("a"))
addCustomerRecord(kb);
else if(menuChoice.equals("d"))
{
displayCustomerRecords();
}
else if(menuChoice.equals("q"))
{
System.out.println("Program exiting..");
System.exit(0);
}
else
{
System.out.println("incorrect entry. Please re-enter a valid entry: \n");
menuChoice = kb.nextLine();
menuChoice = menuChoice.toLowerCase();
}
System.out.println("To add a record press 'A': \n"
+ "to display all records press 'D': \n"
+ "to exit press 'Q': \n");
menuChoice = kb.nextLine();
menuChoice = menuChoice.toLowerCase();
}while(menuChoice.equals("a") || menuChoice.equals("d") || menuChoice.equals("q"));
kb.close();
}
/* public static void displayCustomerRecords()
{
System.out.println();
for (int i = 0; i < customerAL.size(); ++i)
{
System.out.printf("%-15s", customerAL.get(i).getLastName());
System.out.printf("%-15s", customerAL.get(i).getFirstName());
System.out.printf("%-6s", customerAL.get(i).getCustID());
System.out.printf("%15s\n", customerAL.get(i).getPhoneNumber());
}
System.out.println();
}
/**
* prompts to enter customer data and mutator methods called
* with a Scanner object passed as an argument to set data
* #param location index position of where the element will be added.
* #param kb a Scanner object to accept input
*/
public static void addCustomerRecord(Scanner kb)
{
Customer currentCustomerMemoryAddress = new Customer();
System.out.println("Enter first name: \n");
String fName = kb.nextLine();
currentCustomerMemoryAddress.setFirstName(fName);
System.out.println("Enter last name: \n");
String lName = kb.nextLine();
currentCustomerMemoryAddress.setLastName(lName);
System.out.println("Enter customer phone number: \n");
String pNum = kb.nextLine();
currentCustomerMemoryAddress.setPhoneNumber(pNum);
System.out.println("Enter customer ID number: \n");
String ID = kb.nextLine();
currentCustomerMemoryAddress.setCustID(ID);
int addLocation = findAddLocation(currentCustomerMemoryAddress);
customerAL.add(addLocation, currentCustomerMemoryAddress);
currentCustomerMemoryAddress = null;
}
public static int findAddLocation(Customer cust)
{
int location = 0;
if(!customerAL.isEmpty())
{
for(int i = 0; i < customerAL.size(); i++)
{
//Stumped here
}
}
else
return location;
return location;
}
}
It looks like you are reinventing the wheel here William
Replace your code for displayCustomerRecords with this:
public static void displayCustomerRecords()
{
System.out.println();
customerAL.stream().map(c -> String.format("%-15s%-15s%-6s%15s\n",
c.getLastName(), c.getFirstName(), c.getCustID(), c.getPhoneNumber()))
.sorted()
.forEach(System.out::print);
System.out.println();
}
Update
Taking into account your comment you can replace your findAddLocationmethod by the following:
private static Comparator<Customer> comparator = Comparator.comparing(Customer::getLastName)
.thenComparing(Customer::getFirstName)
.thenComparing(Customer::getCustID)
.thenComparing(Customer::getPhoneNumber);
public static int findAddLocation(Customer cust)
{
int location = 0;
if(!customerAL.isEmpty())
{
for(Customer customerInList : customerAL)
{
if(comparator.compare(customerInList, cust) > 0) {
break;
}
location++;
}
}
return location;
}
We are traversing the array using Java's enhanced for-loop and comparing the objects using a Java 8 declared comparator (which I believe is the key to this assignment).
It would be a good idea if you could look into the Comparable interface and implement it in your Customer class. That way you could simply do a simple call to customerInList.compareTo(cust) to compare both objects.
As already stated, this is not a good practice and shouldn't be used in production code.

Error when printing out my object from array

Im having some trouble printing out details ive put into my array. when i run my addBook i out in details of two books, but when i select option 2 from menu, i get a runtime error (outofbounds),
Above is resolved by adding [i] to the printline and changing my loop length.
The problem i am having now if my BookID from my loanbook, its not incrementing.
import java.util.Scanner;
public class library {
static Scanner keyboard = new Scanner(System.in);
static boolean run = true;
public static fiction [] fictionArray = new fiction[2];
public static nonfiction [] nonfictionArray = new nonfiction[2];
public static void main (String[] args){ // main class method
while (run){ // this while statement allows the menu to come up again
int answer = 0; // answer initialized to Zero
boolean isNumber;
do{ // start of validation
System.out.println("1. Add book"); // Menu selections
System.out.println("2. Display the books available for loan");
System.out.println("3. Display the books currently on loan");
System.out.println("4. Make a book loan");
System.out.println("5. Return book ");
System.out.println("6 Write book details to file");
if (keyboard.hasNextInt()){ // I would like to set values to =>1 <=6
answer = keyboard.nextInt(); // this is more validation for the input for menu selection
isNumber = true;
} else { // else if number not entered, it will prompt for the correct input
System.out.print(" You must enter a number from the menu to continue. \n");
isNumber = false;
keyboard.next(); // clears keyboard
}
}
while (!(isNumber)); // while to continue program after the do has completed
switch (answer){ // switch statement - uses answer from the keyboard to select a case
case 1:
addBook(); // adds book
break;
case 2:
for (int i=0; i<5; i++){
if (fictionArray[i] != null){
System.out.println(fictionArray);}
if (nonfictionArray[i] != null){
System.out.println(nonfictionArray);}}
break;
case 3:
break;
case 4:
break;
case 5:
break;
case 6:
break;
}
}
}
static void addBook(){
loanbook [] loanArray = new loanbook[2];
String title,author;
int choice;
for(int x = 0; x < loanArray.length; x++){
System.out.print("Press 1 for Fiction or 2 for Non Fiction: "); // sub menu for fiction and non fiction
choice = keyboard.nextInt();
if (choice == 1){
for(int count = 0; count < fictionArray.length; count++){
System.out.print("Enter title: ");
title= keyboard.nextLine();
title= keyboard.nextLine();
System.out.print("Enter author: ");
author= keyboard.nextLine();
fictionArray[count] = new fiction(title, author);
System.out.println("The book information you entered was : " + fictionArray[count].toString()); // this will show the entry which was inout to the array
count++; }}
else if (choice == 2) {
for(int count = 0; count < nonfictionArray.length; count++){
System.out.print("Enter title: ");
title= keyboard.nextLine();
title= keyboard.nextLine();
System.out.print("Enter author: ");
author= keyboard.nextLine();
nonfictionArray[count] = new nonfiction(title, author);
System.out.println("The book information you entered was : " + nonfictionArray[count].toString()); // this will show the entry which was inout to the array
count++;}}
else{ int noBooks = loanArray.length;
for (int i=0; i<noBooks; i++){
System.out.print(loanArray[x]);
}}}} // addbook
} // Library end
Below is my Superclass , then my subclass
public class loanbook {
private String title,author;
private int bookID;
public loanbook(String pTitle,String pAuthor){
bookID = 0;
title = pTitle;
author = pAuthor;
bookID++;
} // Constructor
public void setTitle(String pTitle){
title = pTitle;
} // setTitle
protected String getTitle(){
return title;
} // getTitle
protected String getAuthor(){
return author;
} // getAuthor
public String toString(){
return "\n BookID: "+ bookID+"\n" + " Title: "+ getTitle()+"\n" +" Author : "+ getAuthor()+ "\n";
}
} // loanbook
My subclasses are the same except for the class name and constructor
public class fiction extends loanbook {
String bookType;
private String getBookType; // Would be fiction
public fiction(String pTitle,String pAuthor){
super(pTitle,pAuthor);
} // constructor
protected void setBookType (String pBookType){
bookType = pBookType;
} // setter for bookType
protected String getBookType(){
return "Fiction";
}
public String toString(){
return super.toString() +" This book is : "+ getBookType();
}
} // class
You've declared your fictionarray and nonfictionarray to be of length 2. However, in your case 2, you are looping 5 times:
for (int i=0; i<5; i++){
if (fictionArray[i] != null){
Change it to 2. It's possible you changed the array length in the declaration, but forgot to change the loop iteration. In that case, you can just use the array's length:
for (int i = 0; i < fictionArray.length; i++) {
Additionally, it looks like you want to print out the specific array element, not the array itself:
System.out.println(fictionArray[i]);
and likewise for nonfictionarray and the nonfiction class.
Two things I see
if (fictionArray[i] != null){
System.out.println(fictionArray);}
if (nonfictionArray[i] != null){
System.out.println(nonfictionArray);}}
You're trying to print the entire array System.out.println(fictionArray). You probably want System.out.println(fictionArray[i])
Also you should set your array sizes to 5 if you want to loop 5 times

Constructor not setting up an array

I'm relatively new to Java, currently studying it in a night course. I'm having trouble setting the constructor up correctly so that it moves values entered into an array. I have the below code and it seems that the individual fields are being passed correctly but the array is not populated and I can't figure out what I'm doing wrong. I've gone back through my notes, textbooks and checked here. I may just have been staring at it for too long!
import java.util.Scanner;
public class Main {
static Scanner InOut = new Scanner(System.in);
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
//* Declare and initalize variables. Set maximum number of students to 6.
String surname = "", forename = "", course = "a", newCourse, tmpStu ="";
int firstMark = 0, secondMark = 0, thirdMark = 0, finalScore = 0,
option = 0, studentCount = 0, delNum, index = 0;
final int MAXSTUDENT = 6;
Student[] myClass = new Student[MAXSTUDENT];
//* Set class details for the constructor.
while (option != 6) {
//* Call the menu system to be displayed
option = menu();
switch (option) {
//* Checks the value return by the menu for the selected option
case 1:
//* Checks that the maximum number of students has not been exceeded.
if (studentCount >= MAXSTUDENT) {
System.out.println("Maximum number of student entered. \n\n");
menu();
} else {
//* Enter in the student details
InOut.nextLine(); /* ensures that the buffer is cleared*/
System.out.println("Enter student surname: ");
surname = InOut.nextLine();
System.out.println("Enter student forename: ");
forename = InOut.nextLine();
System.out.println("Enter 1st mark: ");
firstMark = InOut.nextInt();
System.out.println("Enter 2nd mark: ");
secondMark = InOut.nextInt();
System.out.println("Enter 3rd mark: ");
thirdMark = InOut.nextInt();
finalScore = 0;
//* Passes the entered paramaters to add the student details to the object class.
//* Increases the student counter by 1.
myClass[studentCount] = new Student(surname, forename, course, firstMark, secondMark, thirdMark, finalScore);
System.out.println(myClass[studentCount]);
studentCount++;
}
break;
case 2:
//* Enter in the student number to be deleted. Number is passed for deletion.
//* Reduces the number of student counter.
System.out.println("Delete which student?");
delNum = InOut.nextInt();
deleteStudent(delNum, studentCount);
studentCount--;
break;
case 3:
//* Allows for the course name to be updated.
InOut.nextLine(); /* ensures that the buffer is cleared*/
System.out.println("Enter new course: ");
newCourse = InOut.nextLine();
Student.setCourse(newCourse);
break;
case 4:
//* Display all details stored in the object class.
for (index = 0; index < studentCount; index = index + 1){
Student.displayDetails(index);
}
break;
case 5:
//* Input the surname of student and this name is passed to
//* display the details for this student only.
InOut.nextLine(); /* ensures that the buffer is cleared*/
System.out.println("Enter surname of student you want to search for: ");
String searchName = InOut.nextLine();
//* searchStudent(myClass, searchName, index, studentCount);
break;
case 6:
//* Exit program
System.out.println("End of program");
break;
default:
System.out.println("Invalid option");
}
}
}
public static int menu() {
//* Display menu options and returns selection.
System.out.println("****Student Menu****");
System.out.println("1. Add new student details");
System.out.println("2. Delete Student");
System.out.println("3. Change Course");
System.out.println("4. Display All Student Details");
System.out.println("5. Search Student by Name");
System.out.println("6. Exit");
System.out.println("\nInput an option:");
int option = InOut.nextInt();
return option;
}
public void addStudent(String surname, String forename, String course, int firstMark, int secondMark, int thirdMark, int finalScore)
//* Accepts passed paramaters of student details and adds them into the object class.
{
System.out.println(surname);
System.out.println(forename);
System.out.println(course);
System.out.println(firstMark);
System.out.println(secondMark);
System.out.println(thirdMark);
System.out.println(finalScore);
}
public static void deleteStudent(int delNum, int studentCount)
//* Accepts student array number to be deleted and displays details of all
//* students still stored.
{
//* int asize = myClass.length, index;
//* for (index = delNum +1; index < asize; index++)
//* {
//* myClass[index-1] = myClass[index];
//* }
//* studentCount --;
}
And this is the Student Constructor being called. I'd added in a few display statements to see if I could find where it was going wrong but no luck. I think it may be to do with the constructor being called from the "static void" main method.
import java.util.Scanner;
public class Student {
private String surname, forename;
private int firstMark, secondMark, thirdMark, finalScore, index;
private int stuCount = 0;
private final int NUMMARK = 3;
private static String course = "French";
Scanner InOut = new Scanner(System.in);
public Student(String surname, String forename, String course, int firstMark, int secondMark, int thirdMark, int finalScore)
{
System.out.println(surname);
this.surname = surname;
this.forename = forename;
this.course = course;
this.firstMark = firstMark;
this.secondMark = secondMark;
this.thirdMark = thirdMark;
finalScore = ((firstMark + secondMark + thirdMark)/ NUMMARK);
this.finalScore = finalScore;
}
public static void setCourse (String newCourse) {
course = newCourse;
}
private String getDetails()
//* Builds student details and returns them to be displayed.
{
String details = "Student Name: " + surname + ", " + forename +"\n";
details = details + "Course Name: " + course + "\n";
details = details + "Student's Marks: " + firstMark + ", " + secondMark + ", " + thirdMark + "\n";
details = details + "Final Mark: " + finalScore + "\n";
return details;
}
public static void displayDetails(int index)
//* Displays all student details that have been entered using the student counter
//* for the number of times to loop.
{
//* if (myClass[index] != null) {
//* System.out.println(myClass[index].getDetails());
//* }
}
}
This
myClass[0] = new Student(surname, forename, course, firstMark, secondMark, thirdMark, finalScore);
studentCount++;
System.out.println(myClass[0]);
Is adding each new student on the previous one, you are always setting the first position of the array, it should be like this:
myClass[studentCount] = new Student(surname, forename, course, firstMark, secondMark, thirdMark, finalScore);
System.out.println(myClass[studentCount]);//BEFORE the counter increment
studentCount++;
Side note:
This code:
System.out.println(myClass[studentCount]);
Will not print the informations that the student contains. In order to print them you have to override the toString method of your Student class, returning the string you want to be printed
your code doesn't have any serious problem. you just have to edit some part of it as follow:
first of all to see the getDeatails() method of your Student class you should declare it as
protected:
so the new version is as follow
protected String getDetails()
{
String details = "Student Name: " + surname + ", " + forename + "\n";
details = details + "Course Name: " + course + "\n";
details = details + "Student's Marks: " + firstMark + ", " + secondMark + ", " + thirdMark + "\n";
details = details + "Final Mark: " + finalScore + "\n";
return details;
}
in the first case what you write is ok. you just have to use the appropriate way to retrieve the data from an array. so use the following code:
//* Passes the entered paramaters to add the student details to the object class.
//* Increases the student counter by 1.
myClass[studentCount] = new Student(surname, forename, course, firstMark, secondMark, thirdMark, finalScore);
for(int i = 0;i<=studentCount;i++){
System.out.println(myClass[i].getDetails());
System.out.println("-----------------------");
}
studentCount++;
System.out.println("now the student count are: "+studentCount);
the following is for case 4:
case 4:
//* Display all details stored in the object class.
System.out.println("studentcount:"+studentCount);
for (index = 0; index < studentCount; index = index + 1) {
System.out.println(myClass[index].getDetails());
System.out.println("---------------------");
}
break;

Categories

Resources