Constructor not setting up an array - java

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;

Related

java.lang.NullPointerException when setting value of attributes within a loop

Trying to make it so if the user types "end", in the second input which is "Enter the first name of student", the loop automatically assigns each object in the array the attributes of "null" for id and name, and 0 for age and id, as well as breaking the outerloop. However, I get the error java.lang.NullPointerException.
Any help would be appreciated.
import java.util.*;
class Main {
public static void main(String[] args) {
Scanner myObj = new Scanner(System.in);
System.out.println("Enter number of students");
int numberof = myObj.nextInt();
System.out.println("Number of students is " + numberof);
Student Studentz[] = new Student[numberof];
outerloop:
for (int i = 0; i < numberof; ++i) {
Studentz[i] = new Student();
System.out.println("Enter first name of student " + (i + 1));
Scanner myObj1 = new Scanner(System.in);
String firstname = myObj1.nextLine();
System.out.println("Firstname is: " + firstname);
if (firstname.equals("end")) {
for (int g = i; g < numberof; ++g) {
Studentz[g].Setfirst("null");
Studentz[g].Setlast("null");
Studentz[g].Setage(0);
Studentz[g].Setid(0);
}
break outerloop;
} else {
Studentz[i].Setfirst(firstname);
System.out.println("Enter last name of student " + (i + 1));
Scanner myObj2 = new Scanner(System.in);
String lastname = myObj2.nextLine();
System.out.println("Last name is: " + lastname);
Studentz[i].Setlast(lastname);;
System.out.println("Enter age of student " + (i + 1));
Scanner myObj3 = new Scanner(System.in);
int nazca = myObj3.nextInt();
System.out.println("Age is: " + nazca);
Studentz[i].Setage(nazca);
System.out.println("Enter ID of student " + (i + 1));
Scanner myObj4 = new Scanner(System.in);
int nazca1 = myObj4.nextInt();
System.out.println("ID is: " + nazca1);
Studentz[i].Setid(nazca1);
}
for (int c = 0; c < numberof; ++c) {
System.out.println(Studentz[c].Snake());
}
}
}
}
public class Student {
private String first;
private String last;
private int age;
private int id;
public int getid() {
return
this.id;
}
public void Studentss(String f, String l, int a, int i) {
first = f;
last = l;
age = a;
id = i;
}
public void Setfirst(String z) {
this.first = z;
}
public void Setlast(String za) {
this.last = za;
}
public void Setage(int zb) {
this.age = zb;
}
public void Setid(int zc) {
this.id = zc;
}
public String Snake() {
String snek = "Name is " + this.first + " " + this.last + " , Age is " + this.age + " ,ID is " + this.id;
return snek;
}
}
you fail here because you try to print students data before you initialized all elements of Studentz array:
for (int c = 0; c < numberof; ++c) {
System.out.println(Studentz[c].Snake());
}
also your code fails here by the same reason:
for (int g = i; g < numberof; ++g) {
Studentz[g].Setfirst("null"); // NPE - no Student created yet in the array
Some Possibly Helpful Tips:
Follow Java naming rules for your variables and method names, Studentz should be studentz, even for your Arrays. I know...your tired of reading that but as you progress, you'll see how beneficial it really is.
If you can, don't use multiple Scanner objects, there is no need for that in your use-case. Declare one Scanner object and stick with it. You're probably doing this because you are using the nextLine() method after the nextInt() method and you're finding that it skips the first name prompt and provides a Null String (""). This happens because the nextInt() method does not consume the newline character when the Enter key is hit. To solve this problem you would either, place the code line myObj.nextLine(); directly under the int numberof = myObj.nextInt(); code line:
int numberof = myObj.nextInt();
myObj.nextLine(); // Consume ENTER key hit
or don't use the nextInt() method at all. Instead just stick with the nextLine() method and not worry about consumption:
Scanner myObj = new Scanner(System.in);
int numberof = 0;
String val = "";
while (val.equals("")) {
System.out.println("Enter number of students");
val = myObj.nextLine();
if (!val.matches("\\d+")) {
System.err.println("Invalid number supplied!");
val = "";
continue;
}
numberof = Integer.parseInt(val);
}
System.out.println("Number of students is " + numberof);
Student[] studentz = new Student[numberof];
It's always a good idea to validate any input from the User (as shown above), even if they're in a for loop. Give the User an opportunity to make a correct entry, after all, typo's do happen.
Get rid of the outerLoop: label. As a matter of fact, try avoid ever using them if you can....and you can. It would only be on a relatively rare occasion where you might ever need one.
Give your variables meaningful names, at least to some extent. This can benefit you later on down the road when you want to read your old code in the future.
In your Student class you made yourself a this real nice method named Studentss(). Well, I think it should be a constructor instead and save yourself a lot of code entry for calls to Setter methods. After all, that's mostly what the constructor is for. Your Student class constructor can look like this:
public Student(String firstName, String lastName, int age, int id) {
this.first = firstName;
this.last = lastName;
this.age = age;
this.id = id;
}
And be used like this. You will notice that upon each iteration of the outer for loop, all the prompt answers are placed within variables then at the end of all those prompts the constructor is used instantiate a student object, for example:
studentz[i] = new Student(firstname, lastname, age, id);
Doing it this way mean that there is no need to make calls to Setter methods. There is nothing wrong with making setter calls, it's just easier using the constructor. This is demonstrated below:
Scanner myObj = new Scanner(System.in);
int numberof = 0;
String val = "";
while (val.equals("")) {
System.out.println("Enter number of students");
val = myObj.nextLine();
if (!val.matches("\\d+")) {
System.err.println("Invalid number supplied!");
val = "";
continue;
}
numberof = Integer.parseInt(val);
}
System.out.println("Number of students is " + numberof);
Student[] studentz = new Student[numberof];
for (int i = 0; i < numberof; ++i) {
String firstname = "null";
String lastname = "null";
int age = 0;
int id = 0;
boolean exitOuterForLoop = false;
// Student First Name Prompt:
// (with option to End and default remaining to null's and 0's)
while (firstname.equals("null")) {
System.out.println("Enter first name of student " + (i + 1) + " (End to stop):");
firstname = myObj.nextLine();
if (firstname.equalsIgnoreCase("end")) {
firstname = "null";
//Make all remaining Student instances null and 0
for (int g = i; g < numberof; ++g) {
studentz[g] = new Student(firstname, lastname, age, id); // Use Student class constructor
}
exitOuterForLoop = true;
break; // Exit this 'while' loop
}
// Validate first name (no numbers or crazy characters)
if (!firstname.matches("(?i)[a-z']+")) {
System.err.println("Invalid First Name! (" + firstname + ") Try Again...");
firstname = "null";
}
}
if (exitOuterForLoop) {
break; // Exit this outer 'for' loop.
}
System.out.println("Firstname is: " + firstname);
// Student Last Name Prompt
while (lastname.equals("null")) {
System.out.println("Enter last name of student " + (i + 1));
lastname = myObj.nextLine();
// Validate last name (no numbers or crazy characters)
if (!lastname.matches("(?i)[a-z']+")) {
System.err.println("Invalid Last Name! (" + lastname + ") Try Again...");
lastname = "null";
}
}
System.out.println("Last name is: " + lastname);
// Student Age Prompt
val = "";
while (val.equals("")) {
System.out.println("Enter age of student " + (i + 1));
val = myObj.nextLine();
// Validate age (digits 0 to 9 only)
if (!val.matches("\\d+")) {
System.err.println("Invalid Age Supplied! (" + val + ") Try Again...");
val = "";
}
}
age = Integer.parseInt(val);
System.out.println("Student age is: " + age);
// Student ID Prompt
val = "";
while (val.equals("")) {
System.out.println("Enter ID of student " + (i + 1));
val = myObj.nextLine();
// Validate age (digits 0 to 9 only)
if (!val.matches("\\d+")) {
System.err.println("Invalid ID Supplied! (" + val + ") Try Again...");
val = "";
}
}
id = Integer.parseInt(val);
System.out.println("Student ID is: " + id);
studentz[i] = new Student(firstname, lastname, age, id); // Use Student class constructor
}
// Display the instances of Student contained within the 'studentz[]' array.
for (int c = 0; c < numberof; ++c) {
System.out.println(studentz[c].toString());
}
The snake() method is actually just another toString() method and there is nothing wrong with that however you might want to consider using StringBuilder class to create the returned string rather than doing concatenations, for example:
public String snake() {
return new StringBuilder("Name is ").append(this.first).append(" ").append(this.last)
.append(" , Age is ").append(this.age).append(" , ID is ")
.append(this.id).toString();
}
Not overly important here but it can save you memory if you do a lot concatenating with many large strings.

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

Saving an undefined number of user input

I have created a program in JAVA that has menu Options, 1 to 5. Option 4 being "Add student". Where it asks a 4 questions
Questions:
Please Enter student name:
Please Enter student course:
Please Enter student number:
Please Enter student gender:
After user has given these details, It will save into an array and ends the program. I am quite lost on how to save these details into an array.
This is my program where i tried to find a solution myself, But im relatively new to arrays and method myself.
public static void newstudent (String[] name,String[] course,int[] number,String[] gender)
{
}
public static void selection (int option) // Menu
{
switch (option)
{
case 1:
System.out.println("Display Student option");
break;
case 2:
System.out.println("Search Student");
break;
case 3:
System.out.println("Delete Student");
break;
case 4:
//code for adding new student
break;
case 5:
System.out.println("Exited");
break;
default:JOptionPane.showMessageDialog(null, "Invalid option! Please enter in the range from 1 to 5.", "Error", JOptionPane.ERROR_MESSAGE);
}
}
public static void main(String[] args) {
//Start of Menu loop Statement
int option1 ;
do{
String option = JOptionPane.showInputDialog(null,"Enter your option:\n"+"\n"+"1. Display Students\n"+"2. Search Students\n" + "3. Delete Students\n"+"4. Add Students\n"+"5. Exit ","DMIT Students",JOptionPane.QUESTION_MESSAGE);
option1 = Integer.parseInt(option);
selection(option1);
}while(option1 <1 || option1 > 5);
// End of Menu Loop statement
}
}
i tried doing a for loop to add +1 to these array everytime a user inputs all these details but the for loop will be stuck in a infinite loop. Is there any suggestions that i can get? or easier solutions?
You shouldn't use arrays (the way you are using here) in the first place because you don't want to store the details of single student in four different places i.e. arrays. You can define a class Student with all the details you need and then it will be simple to add the details using class instances. Something like -
public class Student
{
private String m_name;
private int m_age;
private String m_course;
private String m_year;
private String m_section;
public Student( String name, int age, String course, String year, String section )
{
m_name = name;
m_age = age;
m_course = course;
m_year = year;
m_section = section;
}
public String getName()
{
return m_name;
}
public int getAge()
{
return m_age;
}
public String getCourse()
{
return m_course;
}
public String getYear()
{
return m_year;
}
public String getSection()
{
return m_section;
}
public String toString()
{
return "name: " + m_name + ", age: " + m_age +
", course: " + m_course + ", year: " + m_year +
", section: " + m_section;
}
public static void main(String[] args)
{
ArrayList<Student> students = new ArrayList<Student>();
Scanner input = new Scanner(System.in);
int menuChoice = 4;
do {
System.out.println("\t\t\tStudent Record Menu");
System.out.println("\t\t1. Add Student\t2. View Students\t3. Search Student\t4. Exit");
try {
System.out.println("Enter a choice: ");
menuChoice = Integer.parseInt(input.nextLine());
} catch (NumberFormatException e) {
continue;
}
if (menuChoice==1)
{
System.out.println("Full name:");
String name = input.nextLine();
int age = -1;
do {
try {
System.out.println("Age:");
age = Integer.parseInt(input.nextLine());
} catch (NumberFormatException e) {
System.out.println("Enter a number!");
continue;
}
} while (age <= 0);
System.out.println("Course:");
String course = input.nextLine();
System.out.println("Year:");
String year = input.nextLine();
System.out.println("Section:");
String section = input.nextLine();
Student student = new Student(name, age, course, year, section);
students.add(student);
} else if (menuChoice==2) {
System.out.println("Students:");
for (Student student : students)
{
System.out.println(student);
}
}
} while (menuChoice<4);
}
}
The above code snippet is referred from here.

Comparing user inputted string to an array variable 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.

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

Categories

Resources