I'm pretty new to programming so I need help. I wanna add the SubjectGrades to the studentList ArrayList. But I think I'm doing the wrong way. What should I do for me to add the SubjectGrades to the ArrayList? Thanks
Here's my partial Main class.
import java.util.Scanner;
import java.util.ArrayList;
public class Main {
private static Scanner in;
public static void main(String[] args) {
ArrayList<Student> studentList = new ArrayList<Student>();
//ArrayList<SubjectGrades> Grades = new ArrayList<SubjectGrades>();
in = new Scanner(System.in);
String search, inSwitch1, inSwitch2;
int inp;
do {
SubjectGrades sGrade = new SubjectGrades();
Student student = new Student();
System.out.println("--------------------------------------");
System.out.println("What do you want to do?");
System.out.println("[1]Add Student");
System.out.println("[2]Find Student");
System.out.println("[3]Exit Program");
System.out.println("--------------------------------------");
inSwitch1 = in.next();
switch (inSwitch1) {
case "1":
System.out.println("Input student's Last Name:");
student.setLastName(in.next());
System.out.println("Input student's First Name:");
student.setFirstName(in.next());
System.out.println("Input student's course:");
student.setCourse(in.next());
System.out.println("Input student's birthday(mm/dd/yyyy)");
student.setBirthday(in.next());
System.out.println("Input Math grade:");
student.subjectGrade.setMathGrade(in.nextDouble());
System.out.println("Input English grade:");
student.subjectGrade.setEnglishGrade(in.nextDouble());
System.out.println("Input Filipino grade:");
student.subjectGrade.setFilipinoGrade(in.nextDouble());
System.out.println("Input Java grade:");
student.subjectGrade.setJavaGrade(in.nextDouble());
System.out.println("Input SoftEng grade:");
student.subjectGrade.setSoftEngGrade(in.nextDouble());
studentList.add(student);
studentList.add(student.setSubjectGrade(sGrade)); //Here it is that I want to add
break;
//end case 1
Here is my Student Class.
package santiago;
public class Student {
private String lastName;
private String firstName;
private String course;
private String birthday;
SubjectGrades subjectGrade = new SubjectGrades();
public SubjectGrades getSubjectGrade() {
return subjectGrade;
}
public void setSubjectGrade(SubjectGrades subjectGrade) {
this.subjectGrade = subjectGrade;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getCourse() {
return course;
}
public void setCourse(String course) {
this.course = course;
}
public String getBirthday() {
return birthday;
}
public void setBirthday(String birthday) {
this.birthday = birthday;
}
}
And my SubjectGrades class
package santiago;
public class SubjectGrades{
Double mathGrade, englishGrade, filipinoGrade, javaGrade, softEngGrade, weightedAverage;
public Double getMathGrade() {
return mathGrade;
}
public void setMathGrade(Double mathGrade) {
this.mathGrade = mathGrade;
}
public Double getEnglishGrade() {
return englishGrade;
}
public void setEnglishGrade(Double englishGrade) {
this.englishGrade = englishGrade;
}
public Double getFilipinoGrade() {
return filipinoGrade;
}
public void setFilipinoGrade(Double filipinoGrade) {
this.filipinoGrade = filipinoGrade;
}
public Double getJavaGrade() {
return javaGrade;
}
public void setJavaGrade(Double javaGrade) {
this.javaGrade = javaGrade;
}
public Double getSoftEngGrade() {
return softEngGrade;
}
public void setSoftEngGrade(Double softEngGrade) {
this.softEngGrade = softEngGrade;
}
public Double getWeightedAverage(){
weightedAverage = ((mathGrade + englishGrade + filipinoGrade + javaGrade + softEngGrade)*3) / 15;
return weightedAverage;
}
public String getScholarStatus(){
String status = "";
if(weightedAverage <= 1.5) {
status = "full-scholar";
} else if (weightedAverage <= 1.75){
status = "half-scholar" ;
} else {
status = "not a scholar";
}
return status;
}
}
Your mistake:
studentList.add(student);
studentList.add(student.setSubjectGrade(sGrade));
You are adding the student, then trying to add a void. The return value of setSubjectGrade is void, so nothing will be added:
Just do:
student.setSubjectGrade(sGrade);
studentList.add(student);
Where sGrade is an Object of type SubjectGrades, which was populated in the same way
student.subjectGrade.setSoftEngGrade(in.nextDouble()); was populated.
Use
ArrayList <SubjectGrades> list;
in student class instead SubjectGrades subjectGrade = new SubjectGrades();.
and generate getters and setters
Just remove this line:
studentList.add(student.setSubjectGrade(sGrade)); //Here it is that I want to add
The way you have done it, the student object already has the subjectGrade attribute with its values set.
You can access it with studentList.get(0).getSubjectGrade()
Related
I have a customer, customers and main class. I have an ArrayList in the customers class to store each customer. I think I have successfully added customers. How do I display all the customers in the ArrayList and how would I remove a specific one? I am trying to create a method in the customer class and call on it in the main.
Customer Class:
import java.util.ArrayList;
import java.util.Scanner;
public class customer {
//create variables
private int Id;
private String firstName;
private String lastName;
public customer() {
}
//setters and getters
public int getId() {
return Id;
}
public void setId(int id) {
Id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) throws InputValidationException {
if (firstName.matches("\\p{Upper}(\\p{Lower}){2,20}")) {
} else {
throw new InputValidationException();
}
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) throws InputValidationException {
if (lastName.matches("\\p{Upper}(\\p{Lower}){2,20}")) {
} else {
throw new InputValidationException();
}
this.lastName = lastName;
}
//constructor
public customer(int Id, String firstName, String lastName) {
this.Id = Id;
this.firstName = firstName;
this.lastName = lastName;
}
//get user input
public void customerInfo() {
Scanner input = new Scanner(System.in);
{
while (true) {
//ask user for input and get input
System.out.println("Enter id (press 'q' to quit): ");
String temp = input.nextLine();
if (temp.equals("q")) break;
int id = Integer.parseInt(temp);
System.out.println("Enter first name:");
String firstName = input.nextLine();
System.out.println("Enter last name:");
String lastName = input.nextLine();
//add customer
customers.add(new customer(id, firstName, lastName));
}
}
}
public void displayCustomers() {
System.out.println("Customer List : ");
}
}
Customers Class:
import java.util.ArrayList;
//creates an array of the customers
public final class customers {
public static ArrayList<customer> customers;
public customers() {
customers = new ArrayList<customer>();
}
public static void add(customer customer) {
}
}
Main Class:
public class Main {
public static void main(String[] args) {
customer customerInfoObject = new customer();
customerInfoObject.customerInfo();
customer displayCustomersObject = new customer();
displayCustomersObject.displayCustomers();
}
}
To print the information of all customers of the list, use a loop.
There are different ways for the user to delete a customer. You could receive an integer from the user and delete the customer at the given index. You could also receive the customer-name and compare it in a loop to the names of the customers and delete the one with the received name.
Also, dont use empty brackets. Just put an ! in front of the if-condition to invert it
I have the abstract class Human, which is extendet by other two classes Student and Worker. I`m am trying to fill in two array lists. ArrayList of type Student and ArrayList of type Worker dynamically.
public abstract class Human {
private String fName = null;
private String lName = null;
public String getfName() {
return fName;
}
public Human(String fName, String lName) {
super();
this.fName = fName;
this.lName = lName;
}
public void setfName(String fName) {
this.fName = fName;
}
public String getlName() {
return lName;
}
public void setlName(String lName) {
this.lName = lName;
}
}
public class Student extends Human {
private String grade = null;
public Student(String fName, String lName, String grade) {
super(fName, lName);
this.grade = grade;
}
public String getGrade() {
return grade;
}
public void setGrade(String grade) {
this.grade = grade;
}
}
public class Worker extends Human {
private int weekSalary = 0;
private int workHoursPerDay = 0;
public Worker(String fName, String lName, int weekSalary, int workHoursPerDay) {
super(fName, lName);
this.weekSalary = weekSalary;
this.workHoursPerDay = workHoursPerDay;
}
public int getWorkSalary() {
return weekSalary;
}
public void setWorkSalary(int workSalary) {
this.weekSalary = workSalary;
}
public int getWorkHoursPerDay() {
return workHoursPerDay;
}
public void setWorkHoursPerDay(int workHoursPerDay) {
this.workHoursPerDay = workHoursPerDay;
}
public int moneyPerHour() {
return weekSalary / (5 * workHoursPerDay);
}
}
public class Program {
public static void main(String[] args) {
ArrayList<Student> student = new ArrayList<>();
ArrayList<Worker> worker = new ArrayList<>();
}
}
Sure, just add the students:
ArrayList<Student> students = new ArrayList<>(); // note: students
students.add(new Student("Jens", "Nenov", "A+"));
You can do almost exactly the same thing for the workers. If you want to use a loop, do the following:
for (int i=0; i<50; i++) {
students.add(new Student("Jens"+i, "Nenov", "A+"));
}
This will create a list of new students with different numbers after their names. If you want different data, though, that data needs to come from somewhere. For example, you might get the data from user input:
Scanner input = new Scanner(System.in);
for ...
System.out.println("Enter a first name:");
String firstname = input.nextLine();
...
students.add(new Student(firstname, lastname, grade));
I have a class called CustomerRecord, that another Class, CustomerList contains. When Customer List initializes, everything is fine, but when the first instance of Customer record initializes I get a Null Pointer Exception. Im not sure why this keeps happening but I would much appreciate some help on what is wrong and how to fix it.
Exception in thread "main" java.lang.NullPointerException
at CustomerList.getCustomerList(CustomerList.java:31)
at Assignment3.main(Assignment3.java:16)
Here is my code
public class CustomerRecord {
private int customerNumber;
private String firstName;
private String lastName;
private double balance;
public CustomerRecord() {
super();
}
public int getCustomerNumber() {
return customerNumber;
}
public void setCustomerNumber(int customerNumber) {
this.customerNumber = customerNumber;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public double getBalance() {
return balance;
}
public void setBalance(double balance) {
this.balance = balance;
}
public String toString(){
return this.customerNumber + " " + this.firstName + " " + this.lastName + " " + this.balance;
}
}
Here is my CustomerList Code
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class CustomerList {
private int count;
private CustomerRecord[] data;
public CustomerList(){
count = 0;
CustomerRecord[] data = new CustomerRecord[100];
}
public void getCustomerList (String fileName){
Scanner fileScan;
try {
fileScan = new Scanner(new File(fileName));
while (fileScan.hasNext()){
if (fileScan.hasNextInt()){
int customerNumber = fileScan.nextInt();
String firstName = fileScan.next();
String lastName = fileScan.next();
double TransactionAmount = fileScan.nextDouble();
data[customerNumber].setBalance(data[customerNumber].getBalance() + TransactionAmount);
}
else{
data[count] = new CustomerRecord();
data[count].setCustomerNumber(count);
data[count].setFirstName(fileScan.next());
data[count].setLastName(fileScan.next());
data[count].setBalance(fileScan.nextDouble());
count++;
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
public CustomerRecord getCustomer (int customerNumber){
if (data[customerNumber] != null){
return data[customerNumber];
}
else
return null;
}
}
When you initialized data in the constructor you weren't actually referring to the same 'data' you had defined. You created a new data and set it to have 100 positions. But you defined it inside the constructor, so it didn't affect your global variable. What you need to do is replace CustomerRecord[] data = new CustomerRecord[100]; for data = new CustomerRecord[100];
I have this project ive been working on all week and cannot get the search in Main.java in the switch case 3 to work. Any idea why this will not display??
Here it all is :(
Main.Java
package hartman;
import java.util.ArrayList;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Printer.printWelcome();
Scanner keyboard = new Scanner(System.in);
ArrayList<Person> personList = new ArrayList<>();
boolean keepRunning = true;
while (keepRunning) {
Printer.printMenu();
Printer.printPrompt("Please enter your operation: ");
String userSelection = keyboard.nextLine();
switch (userSelection) {
case "1":
Database.addPerson(personList);
break;
case "2":
Database.printDatabase(personList);
break;
case "3":
Printer.printSearchPersonTitle();
String searchFor = keyboard.nextLine();
Database.findPerson(searchFor);
Printer.printPersonList(personList);
break;
case "4":
keepRunning = false;
break;
default:
break;
}
}
Printer.printGoodBye();
keyboard.close();
}
}
Database.Java
package hartman;
import java.util.ArrayList;
import java.util.Scanner;
public class Database {
static Scanner keyboard = new Scanner(System.in);
private static ArrayList<Person> personList = new ArrayList<Person>();
public Database() {
}
public static void addPerson(ArrayList<Person> personList) {
Printer.printAddPersonTitle();
Printer.printPrompt(" Enter first name: ");
String addFirstName = keyboard.nextLine();
Printer.printPrompt(" Enter last Name: ");
String addLastName = keyboard.nextLine();
Printer.printPrompt(" Enter social Security Number: ");
String addSocial = keyboard.nextLine();
Printer.printPrompt(" Enter year of birth: ");
int addYearBorn = Integer.parseInt(keyboard.nextLine());
System.out.printf("\n%s, %s saved!\n", addFirstName, addLastName);
Person person = new Person();
person.setFirstName(addFirstName);
person.setLastName(addLastName);
person.setSocialSecurityNumber(addSocial);
person.setYearBorn(addYearBorn);
personList.add(person);
}
public static void printDatabase(ArrayList<Person> personList) {
System.out
.printf("\nLast Name First Name Social Security Number Age\n");
System.out
.printf("=================== =================== ====================== ===\n");
for (Person p : personList) {
System.out.printf("%-20s%-21s%-24s%s\n", p.getLastName(),
p.getLastName(), p.getSocialSecurityNumber(), p.getAge());
}
}
public static ArrayList<Person> findPerson(String searchFor) {
ArrayList<Person> matches = new ArrayList<>();
for (Person p : personList) {
boolean isAMatch = false;
if (p.getFirstName().equalsIgnoreCase(searchFor)) {
isAMatch = true;
} else if (p.getLastName().equalsIgnoreCase(searchFor)) {
isAMatch = true;
} else if (p.getSocialSecurityNumber().contains(searchFor)) {
isAMatch = true;
;
} else if (String.format("%d", p.getAge()).equals(searchFor)) {
isAMatch = true;
}
if (isAMatch) {
matches.add(p);
}
Printer.printPersonList(matches);
}
return matches;
}
}
Person.Java
package hartman;
public class Person {
private String firstName;
private String lastName;
private String socialSecurityNumber;
private int yearBorn;
public Person() {
}
public Person(String firstName, String lastName,
String socialSecurityNumber, int yearBorn) {
this.firstName = firstName;
this.lastName = lastName;
this.socialSecurityNumber = socialSecurityNumber;
this.yearBorn = yearBorn;
}
public int getAge() {
return yearBorn = 2014 - yearBorn;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getSocialSecurityNumber() {
return socialSecurityNumber;
}
public void setSocialSecurityNumber(String socialSecurityNumber) {
this.socialSecurityNumber = socialSecurityNumber;
}
public int getYearBorn() {
return yearBorn;
}
public void setYearBorn(int yearBorn) {
this.yearBorn = yearBorn;
}
}
Printer.Java
package hartman;
import java.util.ArrayList;
public class Printer {
public static void printWelcome() {
System.out.printf("WELCOME TO PERSON DATABASE!\n");
}
public static void printGoodBye() {
System.out.printf("\nGOOD BYE!!\n");
}
public static void printMenu() {
System.out.printf("\nMain Menu\n");
System.out.printf("---------\n\n");
System.out.printf(" 1. Add a new Person to the database.\n");
System.out.printf(" 2. Print the database.\n");
System.out.printf(" 3. Search for a person in the database.\n");
System.out.printf(" 4. Exit the application.\n");
System.out.printf("\n");
}
public static void printPrintMenu() {
System.out.printf("Print\n\n");
}
public static void printAddPersonTitle() {
System.out.printf("\nAdd Person to Database\n\n");
}
public static void printPrompt(String promptForWhat) {
System.out.printf("%s", promptForWhat);
}
public static void printPersonSaved(Person personSaved) {
System.out.printf("%s", personSaved);
}
public static void printSearchPersonTitle() {
System.out.printf("\nSearch for Person in Database\n\n");
System.out.printf("Enter search value: ");
}
public static void printPersonList(ArrayList<Person> personListToPrint) {
System.out
.printf("\nLast Name First Name Social Security Number Age\n");
System.out
.printf("=================== =================== ====================== ===\n");
for (Person p : personListToPrint) {
System.out.printf("%-20s%-21s%-24s%s\n", p.getLastName(),
p.getLastName(), p.getSocialSecurityNumber(), p.getAge());
}
}
}
Any help would be great... im about to break my pc and give up.
The problems is that you are using the static instance from DataBase
ArrayList<Person> personList = new ArrayList<Person>();
I was gonna say follow the rules of OOP click here if you want to learn
But since you already started a lot of coding ill try to answer your problem..
Dont use instance of personList in the DataBase. Just use from the Main class.
here is where the problem started:
for (Person p : personList)
You are using an empty ArrayList from DataBase class..
The one that has data and you are using is from the Main class..
solution:
Remove the
private static ArrayList<Person> personList = new ArrayList<Person>();
from your DataBase then do this in you Main Class
public class Main {
public static ArrayList<Person> personList;
public static void main(String[] args) {
Printer.printWelcome();
Scanner keyboard = new Scanner(System.in);
personList = new ArrayList<Person>();
and change the for loop to:
for (Person p : Main.personList)
This is what you get when you dont use OOP on your problems its soo ugly and complicated..
Its better when it is object oriented.. P.S. learn that..
I have to have the code below, pass the data typed in by the user passed to the following method:
public void addPerson(Person p)
{
personList.add(p);
}
and it must be from there added to the array "personList" that is in databse.java (which is posted at the very bottom.
This is what i have so far:
package hartman;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Printer.printWelcome();
Scanner keyboard = new Scanner(System.in);
boolean keepRunning = true;
while (keepRunning) {
Printer.printMenu();
Printer.printPrompt("Please enter your operation: ");
String userSelection = keyboard.nextLine();
switch (userSelection) {
case "1":
handleAddPerson(keyboard);
break;
case "2":
Database.printDatabase();
break;
case "3":
handleSearchPerson(keyboard);
break;
case "4":
keepRunning = false;
break;
default:
break;
}
}
Printer.printGoodBye();
}
private static void handleAddPerson(Scanner keyboard) {
Printer.printAddPersonTitle();
Printer.printPrompt("First Name: ");
String addFirstName = keyboard.nextLine();
Printer.printPrompt("Last Name: ");
String addLastName = keyboard.nextLine();
Printer.printPrompt("Social Security Number: ");
String addSocial = keyboard.nextLine();
Printer.printPrompt("Year Born: ");
int addYearBorn = Integer.parseInt(keyboard.nextLine());
Person person = new Person();
person.setFirstName(addFirstName);
person.setLastName(addLastName);
person.setSocialSecurityNumber(addSocial);
person.setYearBorn(addYearBorn);
}
static void handleSearchPerson(Scanner keyboard) {
Printer.printSearchPersonTitle();
Printer.printPrompt(" Enter search value: ");
String keyword = keyboard.nextLine();
}
}
here is Person.java for those who wondered.
package hartman;
public class Person {
private String firstName;
private String lastName;
private String socialSecurityNumber;
private int yearBorn;
public Person() {
}
public Person(String firstName, String lastName,
String socialSecurityNumber, int yearBorn) {
}
public int getAge() {
return yearBorn = 2014 - yearBorn;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getSocialSecurityNumber() {
return socialSecurityNumber;
}
public void setSocialSecurityNumber(String socialSecurityNumber) {
this.socialSecurityNumber = socialSecurityNumber;
}
public int getYearBorn() {
return yearBorn;
}
public void setYearBorn(int yearBorn) {
this.yearBorn = yearBorn;
}
}
and here is database.java
package hartman;
import java.util.ArrayList;
import java.util.Scanner;
public class Database {
Scanner keyboard = new Scanner(System.in);
private ArrayList<Person> personList;
public Database() {
}
public void addPerson(Person p) {
personList.add(p);
}
public static void printDatabase() {
}
public ArrayList<Person> findPerson(String searchFor) {
Main.handleSearchPerson(keyboard);
ArrayList<Person> matches = new ArrayList<>();
for (Person p : personList) {
boolean isAMatch = false;
if (p.getFirstName().equalsIgnoreCase(searchFor)) {
isAMatch = true;
}
if (p.getLastName().equalsIgnoreCase(searchFor)) {
isAMatch = true;
}
if (p.getSocialSecurityNumber().contains(searchFor)) {
isAMatch = true;
}
if (String.format("%d", p.getAge()).equals(searchFor))
if (isAMatch) {
matches.add(p);
}
}
return matches;
}
}