How can I fix this null pointer exception? - java

I keep getting a nullPointerException and the rest of my code won't run. I have two classes setup. One is the SalesPerson and the other contains the main method. Line 42 is marked and that is where the nullPointerException occurs.
This is line 42
System.out.printf("%-20s %15.2f %14.2f %n", list[i].getFirstName() + " " + list[i].getLastName(), list[i].getTotalSales(), list[i].getSalary());
public class SalesPerson {
private String firstName;
private String lastName;
private double firstSales;
private double secondSales;
private double thirdSales;
private double fourthSales;
private double totalSales;
private double salary;
public SalesPerson(String lastName, String firstName, double firstSales,
double secondSales, double thirdSales, double fourthSales,
double totalSales, double salary) {
this.lastName = lastName;
this.firstName = firstName;
this.firstSales = firstSales;
this.secondSales = secondSales;
this.thirdSales = thirdSales;
this.fourthSales = fourthSales;
this.totalSales = totalSales;
this.salary = salary;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
public double getTotalSales() {
return totalSales;
}
public void setTotalSales(double totalSales) {
this.totalSales = totalSales;
}
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 getFirstSales() {
return firstSales;
}
public void setFirstSales(double firstSales) {
if (firstSales >= 0) {
this.firstSales = firstSales;
} else {
System.out.println("First sales must be greater than zero.");
}
}
public double getSecondSales() {
return secondSales;
}
public void setSecondSales(double secondSales) {
if (secondSales >= 0) {
this.secondSales = secondSales;
} else {
System.out.println("Second sales must be greater than zero.");
}
}
public double getThirdSales() {
return thirdSales;
}
public void setThirdSales(double thirdSales) {
if (thirdSales >= 0) {
this.thirdSales = thirdSales;
} else {
System.out.println("Third sales must be greater than zero.");
}
}
public double getFourthSales() {
return fourthSales;
}
public void setFourthSales(double fourthSales) {
if (fourthSales >= 0) {
this.fourthSales = fourthSales;
} else {
System.out.println("Fourth sales must be greater than zero.");
}
}
}
SECOND CLASS
import java.io.File;
import java.util.Scanner;
public class Assignment10 {
public static final int NUM_SALESPEOPLE = 20;
public static final double NUM_PER_SALARY = 25;
public static void main(String[] args) {
SalesPerson[] list = new SalesPerson[NUM_SALESPEOPLE];
try {
int people = 0;
Scanner fileInput = new Scanner(new File("A10.txt"));
while (fileInput.hasNext()) {
String lastName = fileInput.next();
String firstName = fileInput.next();
double firstSales = fileInput.nextDouble();
double secondSales = fileInput.nextDouble();
double thirdSales = fileInput.nextDouble();
double fourthSales = fileInput.nextDouble();
double totalSales = firstSales + secondSales + thirdSales + fourthSales;
double salary = NUM_PER_SALARY * totalSales;
SalesPerson person = new SalesPerson(lastName, firstName,
firstSales, secondSales, thirdSales, fourthSales, totalSales, salary);
list[people] = person;
people++;
}
} catch (Exception ex) {
System.out.println("Error opening file.");
}
System.out.println("Full Name Total Sales Salary");
System.out.println("========= =========== ======");
for (int i = 0; i < NUM_SALESPEOPLE; i++) {
System.out.printf("%-20s %15.2f %14.2f %n", list[i].getFirstName() + " " + list[i].getLastName(), list[i].getTotalSales(), list[i].getSalary());
}
System.out.println("===================================================");
}
}

You are creating an array of size 20. This array will hold only references to NULL. If in your file you have less than 20 entries you will end up with a nullpointerexception.
To be sure, try to print the value of people. If it less than 20 then this is normal.

Your file 'A10.txt' doesn't have 20 (correct) lines.
You should not create an Array. Use ArrayList and Iterator instead and you won't have such problems.

Simply add a check for null:
for (int i = 0; i < NUM_SALESPEOPLE; i++) {
if (list[i] != null) {
System.out.printf("%-20s %15.2f %14.2f %n", list[i].getFirstName() + " " + list[i].getLastName(), list[i].getTotalSales(), list[i].getSalary());
}
}
or declare
int people = 0;
two lines earlier (before your try-block) and use this number of actual read people as the upper bound in your for loop instead of NUM_SALESPEOPLE.

Related

Can't figure out why abstract method isn't overriding

My programming assignment tasked me with writing an increase/decreasePay abstract method that must be put in my abstract employee class. I can't seem to get the the method correct in HourlyWorker so that it will take increase or decrease the pay by a "percentage". My math is sound (monthly pay - or + (monthly pay * the percentage), but my output in my test class is coming out the same after increasing/decreasing pay. Any help?
Employee class:
abstract public class Employee
{
private String lastName;
private String firstName;
private String ID;
public abstract void increasePay(double percentage);
public abstract void decreasePay(double percentage);
public abstract double getMonthlyPay();
public Employee(String last, String first, String ID)
{
lastName = last;
firstName = first;
this.ID = ID;
}
public void setLast(String last)
{
lastName = last;
}
public void setFirst(String first)
{
firstName = first;
}
public void setIdNumber(String ID)
{
this.ID = ID;
}
public String getLastName()
{
return lastName;
}
public String getFirstName()
{
return firstName;
}
public String getName()
{
return firstName + lastName;
}
public String getIdNumber()
{
return ID;
}
}
HourlyWorkerClass
public class HourlyWorker extends Employee
{
private int hours;
private double hourlyRate;
private double monthlyPay;
public HourlyWorker(String last, String first, String ID, double rate)
{
super(last, first, ID);
hourlyRate = rate;
}
public void setHours(int hours)
{
this.hours = hours;
}
public int getHours()
{
return hours;
}
public void setHourlyRate(double rate)
{
if ( hours > 160 )
this.hourlyRate = hourlyRate * 1.5;
else
this.hourlyRate = rate;
}
public double getHourlyRate()
{
return hourlyRate;
}
public void setMonthlyPay(double monthlyPay)
{
monthlyPay = hourlyRate * hours;
}
public double getMonthlyPay()
{
return hourlyRate * hours;
}
public void increasePay(double percentage)
{
monthlyPay = monthlyPay* percentage;
}
public void decreasePay(double percentage)
{
monthlyPay = monthlyPay* percentage;
}
public String toString()
{
String result = "Name: " + getFirstName() + " " + getLastName() + "\nID: "
+ getIdNumber() + " \nHourly Rate: " + hourlyRate;
return result;
}
}
Testing class (currently testing increase
public class TestEmployee2
{
public static void main(String[] args)
{
Employee [] staff = new Employee[3];
Supervisor sup = new Supervisor("Boss", "Jim", "JB7865", 54000);
HourlyWorker hw1 = new HourlyWorker("Bee", "Busy", "BB1265", 11.95);
hw1.setHours(200);
staff[0] = sup;
staff[1] = hw1;
System.out.println(staff[0].getMonthlyPay());
staff[0].increasePay(5);
System.out.println(staff[0].getMonthlyPay());
System.out.println(staff[1].getMonthlyPay());
staff[1].increasePay(10);
System.out.println(staff[1].getMonthlyPay());
}
}
Supervisor class:
public class Supervisor extends Employee
{
private double annualSalary;
private double monthlyPay;
public Supervisor(String last, String first, String ID, double salary)
{
super(last, first, ID);
annualSalary = salary;
}
public void setAnnualSalary(double salary)
{
annualSalary = salary;
}
public double getAnnualSalary()
{
return annualSalary;
}
public double getMonthlyPay()
{
return ((annualSalary + (annualSalary * .02)) / 12);
}
public void increasePay(double percentage)
{
monthlyPay = monthlyPay* percentage;
}
public void decreasePay(double percentage)
{
monthlyPay = monthlyPay* percentage;
}
public String toString()
{
String result = "Name: " + getFirstName() + " " + getLastName() + "\nID: "
+ getIdNumber() + "\nAnnual Salary: " + annualSalary;
return result;
}
}
Output is:
4590.0
4590.0
2390.0
2390.0
Doesn't appear to be modifying getMonthlyPay()
Should be:
4590.00
4819.50
2390.00
2629.00
In increasePay, you are increasing monthlyPay:
public void increasePay(double percentage)
{
monthlyPay = monthlyPay* percentage;
}
But when you getMonthlyPay, you calculate the pay using two other variables - hourlyRate and hours:
public double getMonthlyPay()
{
return hourlyRate * hours;
}
So changing monthlyPay doesn't affect what getMonthlyPay returns. I suspect a similar thing happens in Supervisor.
increasePay should instead increase hourlyRate:
public void increasePay(double percentage)
{
hourlyRate *= 1 + percentage / 100;
}
Also, I don't think you need a monthlyPay field (or setMonthlyPay, for that matter) in HourlyEmployee at all. The monthly rate can always be calculated by hours and hourlyRate.
For Supervisor, do the same thing, and change annualSalary rather than monthlyPay:
public double getMonthlyPay()
{
return ((annualSalary + (annualSalary * .02)) / 12);
}
public void increasePay(double percentage)
{
annualSalary *= 1 + percentage / 100;
}

Return user input into setter function

I have been working on an assignment and i am stuck at here. Basically i have 1 class which defines all functions and members.
And another class to initialize and manipulate objects.
Here is my first class code.
public class cyryxStudent_association {
String studentID, studentName, studentCourse_level, studentTitle;
int course_completed_year;
static double registration_fee;
double activity_fee;
double total_amt;
//Default constructor
cyryxStudent_association ()
{
studentID = "Null";
studentName = "Null";
studentCourse_level = "Null";
studentTitle = "Null";
course_completed_year = 0;
}
//Parameterized Constructor
cyryxStudent_association (String id, String name, String course_level, String title, int ccy)
{
this.studentID = id;
this.studentName = name;
this.studentCourse_level = course_level;
this.studentTitle = title;
this.course_completed_year = ccy;
}
//Getters
public String getStudentID ()
{
return studentID;
}
public String getStudentName ()
{
return studentName;
}
public String getStudentCourse_level ()
{
return studentCourse_level;
}
public String getStudentTitle ()
{
return studentTitle;
}
public int getCourse_completed_year ()
{
return course_completed_year;
}
public double getRegistration_fee ()
{
return registration_fee;
}
public double getActivity_fee ()
{
return findActivity_fee(registration_fee);
}
public double getTotal_amt ()
{
return total_amt(registration_fee, activity_fee);
}
//Setters
public void setStudentID (String id)
{
studentID = id;
}
public void setStudentName (String name)
{
studentName = name;
}
public void setStudentCourse_level (String course_level)
{
studentCourse_level = course_level;
}
public void setStudentTitle (String title)
{
studentTitle = title;
}
public void setCourse_completed_year (int ccy)
{
course_completed_year = ccy;
}
//Find registration fee method
public static double findRegistration_fee (String course_level)
{
if (course_level.equalsIgnoreCase("Certificate"))
{
registration_fee = 75;
}
else if (course_level.equalsIgnoreCase("Diploma"))
{
registration_fee = 100;
}
else if (course_level.equalsIgnoreCase("Degree"))
{
registration_fee = 150;
}
else if (course_level.equalsIgnoreCase("Master"))
{
registration_fee = 200;
}
return registration_fee;
}
//Find activity method
public static double findActivity_fee (double registration_fee)
{
return registration_fee * 0.25;
}
//Find total amount
public static double total_amt (double registration_fee, double activity_fee)
{
return registration_fee + activity_fee;
}
//To string method
public String toString ()
{
return "ID: "+getStudentID()+"\nName: "+getStudentName()+"\nCourse Level:
"+getStudentCourse_level()+"\nTitle: "+getStudentTitle()+"\nCourse Completed Year:
"+getCourse_completed_year()+"\nRegistration Fee: "+getRegistration_fee()+"\nActivity Fee:
"+getActivity_fee()+"\nTotal Amount: "+getTotal_amt ();
}
}
And here is my second class code.
import java.util.Scanner;
public class test_cyryxStudent_association {
public static void main (String[] args)
{
Scanner sc = new Scanner (System.in);
int num, i;
System.out.println("Welcome!");
System.out.println("\nEnter the number of students: ");
num = sc.nextInt();
sc.nextLine();
cyryxStudent_association Std[] = new cyryxStudent_association[num];
for (i = 0; i < Std.length; i++)
{
System.out.println("\nEnter ID: ");
Std[i].setStudentID(sc.nextLine());
System.out.println("Enter Name: ");
Std[i].setStudentName(sc.nextLine());
System.out.println("Enter Course Level [Certificate, Diploma, Degree, Master]: ");
Std[i].setStudentCourse_level(sc.nextLine());
System.out.println("Enter Title: ");
Std[i].setStudentTitle(sc.nextLine());
Std[i].getRegistration_fee();
Std[i].getActivity_fee();
Std[i].getTotal_amt();
}
for (i = 0; i < Std.length; i++)
{
System.out.println("\nStudent " + i + 1 + " Information");
System.out.println("===================================");
Std[i].toString();
}
sc.close();
}
}
I get an error when values in the for loop. Can someone help me? I'm pretty new to programming and studying java for 2 months now. What am i doing wrong?
Here is my objectives.
Create an array of objects and get user input for number of objects to be manipulated.
Read and display array of object values.
Thank you!
You have to initialize the objects of your array.
After the line:
cyryxStudent_association Std[] = new cyryxStudent_association[num];
do a for loop like:
for(i = 0; i<std.length; i++){
std[i] = new cyryxStudent_association();
}

Exception in thread "main" java.Lang.NullPointerException; unable to identify problem [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 3 years ago.
Since I've finished my code I am debugging every step in the main. I keep hitting a NullPointerException not even 40 lines in. The problem is my setter is not working in my Person class. Or what I assume that my setter isn't working. But I also first believe my read isn't working for my file.
I've tried to change around the variables but I simply can't find the problem and why it won't add the name to the Person class. I read into NullPointerExceptions on here and can't find where that problem is for me to fix in my code.
public class Person {
private String firstName;
private String lastName;
private String address;
private String city;
private String state;
private String zipCode;
public Person(String firstName, String lastName, String address, String city, String state, String zipCode) {
this.firstName = firstName;
this.lastName = lastName;
this.address = address;
this.city = city;
this.state = state;
this.zipCode = zipCode;
}
protected Person() {
}
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 getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getCity() {
return this.city;
}
public void setCity(String city) {
this.city = city;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getZipCode() {
return zipCode;
}
public void setZipCode(String zipCode) {
this.zipCode = zipCode;
}
#Override
public String toString() {
return "FirstName: " + firstName + "\nLastName: " + lastName + "\nAddress: " + address + "\nCity: " + city + "\nState: " + state + "\nZipCode: " + zipCode;
}
public String toCSV() {
return this.firstName + "," + this.lastName + "," + this.address + "," + this.city
+ "," + this.state + "," + this.zipCode;
}
public void copy(Person p) {
firstName = p.firstName;
lastName = p.lastName;
address = p.address;
city = p.city;
state = p.state;
zipCode = p.zipCode;
}
public void copy(String firstName, String lastName, String address, String city, String state, String zipCode) {
this.firstName = firstName;
this.lastName = lastName;
this.address = address;
this.city = city;
this.zipCode = zipCode;
}
#Override
public Person clone() {
Person p = new Person(this.firstName, this.lastName, this.address, this.city, this.state, this.zipCode);
return p;
}
}
public class Customer extends Person{
private int customerID;
private double grossSales;
public Customer(int customerID, double grossSales, String firstName, String lastName, String address, String city, String state, String zipCode) {
super(firstName, lastName, address, city, state, zipCode);
this.customerID = customerID;
this.grossSales = grossSales;
}
public Customer(String s, int customerID, double grossSales, String firstName, String lastName, String address, String city, String state, String zipCode) {
super(firstName, lastName, address, city, state, zipCode);
copyCSV(s);
}
protected Customer() {
}
public int getCustomerID() {
return customerID;
}
public void setCustomerID(int customerID) {
this.customerID = customerID;
}
public double getGrossSales() {
return grossSales;
}
public void setGrossSales(double grossSales) {
this.grossSales = grossSales;
}
#Override
public String toString() {
return "CustomerID: " + customerID + "\nGrossSales: " + grossSales + super.toString();
}
public String toCSV() {
return this.customerID + "," + this.grossSales + "," + super.toCSV();
}
public void copy(Customer c) {
super.copy(c);
customerID = c.customerID;
grossSales = c.grossSales;
}
public void copy(int customerId, double grossSales, String firstName, String lastName, String address, String city, String state, String zipCode) {
super.copy(firstName, lastName, address, city, state, zipCode);
this.customerID = customerId;
this.grossSales = grossSales;
}
public Customer clone() {
Customer c = new Customer(this.customerID, this.grossSales, this.getFirstName(), this.getLastName(), this.getAddress(), this.getCity(), this.getState(), this.getZipCode());
return c;
}
public int compareTo(Customer c) {
int returnValue = 0;
if (this.customerID > c.customerID) {
returnValue = -1;
} else if (this.customerID < c.customerID) {
returnValue = 1;
} else {
returnValue = 0;
}
return returnValue;
}
public void copyCSV(String s) {
List<String> list = new ArrayList<>();
String[] a = s.split(",");
list = Arrays.asList(a);
this.copy(Integer.parseInt(list.get(0)), Double.parseDouble(list.get(1)), list.get(2),
list.get(3), list.get(4), list.get(5), list.get(6), list.get(7));
}
}
public class CustomerList {
public Customer[] cl;
public int size;
public CustomerList() {
this.cl = new Customer[4];
}
public int size() {
return this.size = cl.length;
}
public Customer get(Integer i) {
if (i < 0 || i >= size) {
throw new IndexOutOfBoundsException("null");
}
return cl[i];
}
public boolean set(Customer c,Integer i) {
if (i < 0 || i >= size) {
throw new IndexOutOfBoundsException("null");
} else {
cl[i] = c;
return true;
}
}
public void add(Customer c) {
for (int i = 0; i < size; i++) {
if (cl[i] == null) {
cl[i] = c;
} else {
if (i == size) {
Customer[] temp = new Customer[size * 2];
for (int j = 0; j < size; j++) {
temp[j] = cl[j];
}
cl[size] = c;
size++;
}
}
}
}
public Customer remove(Integer i) {
if (i < 0 || i >= size) {
throw new IndexOutOfBoundsException("null");
}
Customer temp = cl[i];
for (int j = 0; j < cl.length - 1; j++) {
cl[i] = cl[i + 1];
}
return temp;
}
#Override
public String toString() {
String s = " ";
double sum = 0;
for(Customer c: cl){
if(c == null)
s = "";
else
s += c + " \n";
}
for(Customer c: cl){
if (c == null)
sum += 0;
else
sum += c.getGrossSales();
}
return s + "\n" + "Total Gross Sales = " + Double.toString(sum);
}
public static CustomerList read(String fn) throws FileNotFoundException {
Scanner input = new Scanner(new File(fn));
CustomerList ab = new CustomerList();
try {
while(input.hasNextLine()) {
String currentline = input.nextLine();
Customer cd = new Customer();
cd.copyCSV(currentline);
cd.toCSV();
ab.add(cd);
}
} finally {
return ab;
}
}
//Write is facing the same problems as read. We can't access the toCSV() method from Customer.
public static boolean write(CustomerList cl, String fn) throws FileNotFoundException {
boolean a = false;
PrintWriter output = new PrintWriter(new File(fn));
// try {
for (int i = 0; i < cl.size; i++) {
Customer cd = new Customer();
cd.toCSV();
// }
// } catch (FileNotFoundException s) {
// System.out.println("File does not exist please try again: ");
// return a;
} return a = true;
}
//I utilized the sort function it said to and assume this will work as expected.
public void sort() {
Arrays.sort(cl);
}
public int indexOf(int id) {
for (int i = 0; i < size; i++) {
if(cl[i].getCustomerID() == id) {
return i;
}
}
return -1;
}
public boolean update(int id, double amt) {
boolean test;
int index = indexOf(id);
if(index == -1) {
System.out.println("CustomerID not present");
test = false;
} else {
amt += cl[index].getGrossSales();
test = true;
}
return test;
}
}
public static void main(String[] args) throws FileNotFoundException {
boolean b = false;
// Read file
System.out.println("Read file");
CustomerList cl = CustomerList.read("Customers.csv");
if(cl != null) {
System.out.println("Read: " + cl.size() + " records");
System.out.println(cl.toString() + "\n\n\n");
} else {
System.out.println("File read error.");
return;
}
// Test get and set for CustomerList
System.out.println("Test get and set for CustomerList");
System.out.println("x = " + cl.get(0));
Customer c = cl.get(0);
c.setFirstName("Homer"); // This is the line it keeps stopping at.
cl.set(c, 0);
System.out.println("x = " + cl.get(0));
System.out.println("\n\n\n");
It should be setting the first name of the customer as "Homer"
The only results it prints out is
Read file
Read: 4 records
Total Gross Sales = 0.0
Test get and set for CustomerList
x = null
--- Exception in thread "main" java.lang.NullPointerException
It's pretty simple, you ask to print cl.get(0). it returns null then you say Customer c = cl.get(0) which is null then you try to do c.setFirstName but c is null so nullPointerException.
Your are trying to access c but c is null. you need to initialize it as a new customer or make it equal to an actual customer (not null) before being able to setFirstName. Just do :
Customer c = new Customer();
c.setFirstName("homer");
It would work if your cl was not empty. To avoid this type of error you could also do :
Customer c;
if (cl.get(0) != null){
c = cl.get(0)
} else {
c = new Customer();
}
c.setFirstName("homer");

How to search for an element in an array? and How to add variables with declared methods into an array list?

I have 2 major troubles (that I'm aware of) with this program. Firstly, I don't know how to get FinalGrade and LetterGrade into the array. Secondly, I don't know how to use last name and first name to search for a student in the array. Let me know if you find other problems with my program. Thanks
This is the 1st class
package student;
public class Person {
protected String FirstName, LastName;
//Constructor
public Person(String FirstName, String LastName) {
this.FirstName = FirstName;
this.LastName = LastName;
}
//Getters
public String getFirstName() {
return FirstName;
}
public String getLastName() {
return LastName;
}
//Setters
public void setFirstName(String FirstName) {
this.FirstName = FirstName;
}
public void setLastName(String LastName) {
this.LastName = LastName;
}
}
This is the 2nd class:
package student;
import java.util.ArrayList;
import java.util.Scanner;
public class Student extends Person{
private int HomeworkAve, QuizAve, ProjectAve, TestAve;
private double FinalGrade;
private String LetterGrade;
//Constructor for the averages
public Student(int HomeworkAve, int QuizAve, int ProjectAve, int TestAve, String FirstName, String LastName)
{
super(FirstName, LastName);
this.HomeworkAve = HomeworkAve;
this.QuizAve = QuizAve;
this.ProjectAve = ProjectAve;
this.TestAve = TestAve;
}
//Method to calculate final grade and letter grade
//Final grade calculation
public double CalcGrade (int HomeworkAve, int QuizAve, int ProjectAve, int TestAve)
{
FinalGrade = (double)(0.15*HomeworkAve + 0.05*QuizAve + 0.4 * ProjectAve + 0.4*TestAve);
return FinalGrade;
}
//Letter grade calculation
public String CalcGrade ( double FinalGrade)
{
if ( FinalGrade >= 90.00)
LetterGrade="A";
else if(FinalGrade >= 80.00)
LetterGrade="B";
else if(FinalGrade>=70.00)
LetterGrade="C";
else if(FinalGrade>=60.00)
LetterGrade="D";
else LetterGrade="F";
return LetterGrade;
}
public String getFullName (String FirstName,String LastName)
{
String str1 = FirstName;
String str2 = LastName;
String FullName = str1+","+str2;
return FullName;
}
public Student(int HomeworkAve, int QuizAve, int ProjectAve, int TestAve, double FinalGrade, String LetterGrade, String FirstName, String LastName) {
super(FirstName, LastName);
this.HomeworkAve = HomeworkAve;
this.QuizAve = QuizAve;
this.ProjectAve = ProjectAve;
this.TestAve = TestAve;
this.FinalGrade = FinalGrade;
this.LetterGrade = LetterGrade;
}
//Setters for this student class
public void setHomeworkAve(int HomeworkAve) {
this.HomeworkAve = HomeworkAve;
}
public void setQuizAve(int QuizAve) {
this.QuizAve = QuizAve;
}
public void setProjectAve(int ProjectAve) {
this.ProjectAve = ProjectAve;
}
public void setTestAve(int TestAve) {
this.TestAve = TestAve;
}
public void setFinalGrade(int FinalGrade) {
this.FinalGrade = FinalGrade;
}
public void setLetterGrade(String LetterGrade) {
this.LetterGrade = LetterGrade;
}
//Getters for this student class
public int getHomeworkAve() {
return HomeworkAve;
}
public int getQuizAve() {
return QuizAve;
}
public int getProjectAve() {
return ProjectAve;
}
public int getTestAve() {
return TestAve;
}
public double getFinalGrade() {
return FinalGrade;
}
public String getLetterGrade() {
return LetterGrade;
}
public void DisplayGrade (){
System.out.println(FirstName+" "+LastName+"/nFinal Grade: "+FinalGrade+"/nLetter Grade: "+ LetterGrade);
}
public static void main(String[] args){
Scanner oScan = new Scanner(System.in);
Scanner iScan = new Scanner(System.in);
boolean bContinue = true;
int iChoice;
ArrayList<Student> students = new ArrayList<>();
while (bContinue == true)
{
//The menu
System.out.println("1. New Class List");
System.out.println("2. Search for a Student");
System.out.println("3. Exit");
System.out.println("Choose an item");
iChoice = iScan.nextInt();
//The 1st case: when the user wants to enter the new list
if (iChoice == 1){
System.out.println("Enter the number of students");
int numberOfStudents = iScan.nextInt();
for(int iCount = 0;iCount < numberOfStudents;){
System.out.println("Enter the name for Student " + ++iCount);
System.out.println("Enter First Name");
String FirstName = oScan.nextLine();
System.out.println();
System.out.println("Enter Last Name");
String LastName = oScan.nextLine();
System.out.println();
System.out.println("Enter Homework Average");
int HomeworkAve = iScan.nextInt();
System.out.println();
System.out.println("Enter Quiz Average");
int QuizAve = iScan.nextInt();
System.out.println();
System.out.println("Enter Project Average");
int ProjectAve = iScan.nextInt();
System.out.println();
System.out.println("Enter Test Average");
int TestAve = iScan.nextInt();
System.out.println();
How to get FinalGrade and LetterGrade??
Student hobbit = new Student(HomeworkAve,QuizAve, ProjectAve,TestAve,FirstName, LastName);
students.add(hobbit);
}
}
//The 2nd case: when the user wants to search for a student
else if (iChoice == 2)
{
System.out.println("Enter First Name");
String FirstName = oScan.nextLine();
System.out.println();
System.out.println("Enter Last Name");
String LastName = oScan.nextLine();
System.out.println();
Here is my revised code to find the student but I don't know how to print the array after I found it
int i = 0;
for (Student student : students) {
if (FirstName != null & LastName != null);{
if (student.getFirstName().equals(FirstName) && student.getLastName().equals(LastName)) {
System.out.println(students.get(i)); //this doesn't work
break;
}
i++;
}
}
//The 3r case: when the user wants to exit
else if (iChoice == 3)
{
bContinue = false;
}
}
}
}
You have an ArrayList of type Student and you are doing indexOf on a variable of type String. You will have to traverse the entire ArrayList and then do a comparison to find out if the student name mathces. Sample code:
int i = 0;
for (Student student : students) {
// Add null checks if first/last name can be null
if (student.getFirstName().equals(firstName) && student.getLastName().equals(lastName)) {
System.out.println("Found student at " + i);
break;
}
i++;
}
FinalGrade and LetterGrade are variables in each object, I think you are mistaken about the concept of an Array/ArrayList. The ArrayList only holds each Student object, not the variable in each object. You can go through each student and get their finalGrade and letterGrade with the get* functions. Before doing this, you should make a call to CalcGrade methods so the grades are calculated.

java.util.Scanner; vs JOptionPane; [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Please I would like know How would I implement JOptionPane instead of import java.util.Scanner;
I also have 4 separate classes
If i implement JOptionPane will it clean up the code I would also like to know any changes anyone would make.
Employee.Class
import java.text.NumberFormat;
import java.util.Scanner;
public class Employee {
public static int numEmployees = 0;
protected String firstName;
protected String lastName;
protected char gender;
protected int dependents;
protected double annualSalary;
private NumberFormat nf = NumberFormat.getCurrencyInstance();
public Benefit benefit;
private static Scanner scan;
public Employee() {
firstName = "";
lastName = "";
gender = 'U';
dependents = 0;
annualSalary = 40000;
benefit = new Benefit();
numEmployees++;
}
public Employee(String first, String last, char gen, int dep, Benefit benefit1) {
this.firstName = first;
this.lastName = last;
this.gender = gen;
this.annualSalary = 40000;
this.dependents = dep;
this.benefit = benefit1;
numEmployees++;
}
public double calculatePay1() {
return annualSalary / 52;
}
#Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("First Name: ").append(firstName).append("\n");
sb.append("Last Name: ").append(lastName).append("\n");
sb.append("Gender: ").append(gender).append("\n");
sb.append("Dependents: ").append(dependents).append("\n");
sb.append("Annual Salary: ").append(nf.format(getAnnualSalary())).append("\n");
sb.append("Weekly Pay: ").append(nf.format(calculatePay1())).append("\n");
sb.append(benefit.toString());
return sb.toString();
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getFirstName() {
return firstName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getLastName() {
return lastName;
}
public <Gender> void setGender(char gender) {
this.gender = gender;
}
public <Gender> char getGender() {
return gender;
}
public void setDependents(int dependents) {
this.dependents = dependents;
}
public void setDependents(String dependents) {
this.dependents = Integer.parseInt(dependents);
}
public int getDependents() {
return dependents;
}
public void setAnnualSalary(double annualSalary) {
this.annualSalary = annualSalary;
}
public void setAnnualSalary(String annualSalary) {
this.annualSalary = Double.parseDouble(annualSalary);
}
public double getAnnualSalary() {
return annualSalary;
}
public double calculatePay() {
return annualSalary / 52;
}
public double getAnnualSalary1() {
return annualSalary;
}
public static void displayDivider(String outputTitle) {
System.out.println(">>>>>>>>>>>>>>> " + outputTitle + " <<<<<<<<<<<<<<<");
}
public static String getInput(String inputType) {
System.out.println("Enter the " + inputType + ": ");
scan = new Scanner(System.in);
String input = scan.next();
return input;
}
public static int getNumEmployees() {
return numEmployees;
}
public static void main(String[] args) {
displayDivider("New Employee Information");
Benefit benefit = new Benefit();
Employee employee = new Employee("George", "Anderson", 'M', 5, benefit);
System.out.println(employee.toString());
System.out.println("Total employees: " + getNumEmployees());
displayDivider("Hourly Temp Employee Information");
Hourly hourly = new Hourly("Mary", "Nola", 'F', 5, 14, 45, "temp");
System.out.println(hourly.toString());
System.out.println("Total employees: " + getNumEmployees());
displayDivider("Hourly Full Time Employee Information");
Hourly hourly1 = new Hourly("Mary", "Nola", 'F', 5, 18, 42, "full time");
System.out.println(hourly1.toString());
System.out.println("Total employees: " + getNumEmployees());
displayDivider("Hourly Part Time Employee Information");
Hourly hourly11 = new Hourly("Mary", "Nola", 'F', 5, 18, 20, "part time");
System.out.println(hourly11.toString());
System.out.println("Total employees: " + getNumEmployees());
displayDivider("Salaried Revised Employee Information");
Benefit benefit1 = new Benefit("None", 500, 3);
Salaried salaried = new Salaried("Frank", "Lucus", 'M', 5, 150000, benefit1, 3);
System.out.println(salaried.toString());
System.out.println("Total employees: " + getNumEmployees());
displayDivider("Salaried Employee Information");
Benefit benefit11 = new Benefit("None", 500, 3);
Salaried salaried1 = new Salaried("Frank", "Lucus", 'M', 5, 100000, benefit11, 2);
System.out.println(salaried1.toString());
System.out.println("Total employees: " + getNumEmployees());
}
}
SALARIED.CLASS
import java.util.Random;
import java.util.Scanner;
public class Salaried extends Employee {
private static final int MIN_MANAGEMENT_LEVEL = 0;
private static final int MAX_MANAGEMENT_LEVEL = 3;
private static final int BONUS_PERCENT = 10;
private int managementLevel;
private Scanner in;
public Salaried() {
super();
Random rand = new Random();
managementLevel = rand.nextInt(4) + 1;
if (managementLevel == 0) {
System.out.println("Not Valid");
}
//numEmployees++;
}
private boolean validManagementLevel(int level) {
return (MIN_MANAGEMENT_LEVEL <= level && level <= MAX_MANAGEMENT_LEVEL);
}
public Salaried(String fname, String lname, char gen, int dep,
double sal, Benefit ben, int manLevel)
{
super.firstName = fname;
super.lastName = lname;
super.gender = gen;
super.dependents = dep;
super.annualSalary = sal;
super.benefit = ben;
while (true) {
if (!validManagementLevel(manLevel)) {
System.out.print("Invalid management level, please enter
another management level value in range [0,3]: ");
manLevel = new Scanner(System.in).nextInt();
} else {
managementLevel = manLevel;
break;
}
}
//numEmployees++;
}
public Salaried(double sal, int manLevel) {
super.annualSalary = sal;
while (true) {
if (!validManagementLevel(manLevel)) {
System.out.print("Invalid management level, please enter another
management level value in range [0,3]: ");
in = new Scanner(System.in);
manLevel = in.nextInt();
} else {
managementLevel = manLevel;
break;
}
}
// numEmployees++;
}
#Override
public double calculatePay() {
double percentage = managementLevel * BONUS_PERCENT;
return (1 + percentage/100.0) * annualSalary / 52;
}
#Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(super.toString());
sb.append("Management Level: ").append(managementLevel).append("\n");
return sb.toString();
}
}
Hourly.Class
import java.util.Scanner;
public class Hourly extends Employee {
private static final double MIN_WAGE = 10;
private static final double MAX_WAGE = 75;
private static final double MIN_HOURS = 0;
private static final double MAX_HOURS = 50;
private double wage;
private double hours;
private String category;
private Scanner in;
private Scanner in2;
private Scanner in3;
private Scanner in4;
public Hourly() {
super();
this.wage = 20;
this.hours= 30;
this.category = "full time";
annualSalary = wage * hours * 52;
}
public Hourly(double wage_, double hours_, String category_) {
while (true) {
if (!validWage(wage_)) {
System.out.print("Invalid wage: ");
in2 = new Scanner(System.in);
wage_ = in2.nextDouble();
} else {
this.wage = wage_;
break;
}
}
while (true) {
if (!validHour(hours_)) {
System.out.print("Invalid hours: ");
in = new Scanner(System.in);
hours_ = in.nextDouble();
} else {
this.hours = hours_;
break;
}
}
while (true) {
if (!validCategory(category_)) {
System.out.print("Invalid category, please enter another category value: ");
category_ = new Scanner(System.in).next();
} else {
this.category = category_;
break;
}
}
annualSalary = wage * hours * 52;
//numEmployees++;
}
public Hourly(String fname, String lname, char gen, int dep, double wage_,double hours_, String category_) {
super.firstName = fname;
super.lastName = lname;
super.gender = gen;
super.dependents = dep;
super.annualSalary = annualSalary;
super.benefit = benefit;
while (true) {
if (!validWage(wage_)) {
System.out.print("Invalid wage : ");
in3 = new Scanner(System.in);
wage_ = in3.nextDouble();
} else {
this.wage = wage_;
break;
}
}
while (true) {
if (!validHour(hours_)) {
System.out.print("Invalid hours : ");
hours_ = new Scanner(System.in).nextDouble();
} else {
this.hours = hours_;
break;
}
}
while (true) {
if (!validCategory(category_)) {
System.out.print("Invalid category, please enter another category value: ");
in4 = new Scanner(System.in);
category_ = in4.next();
} else {
this.category = category_;
break;
}
}
annualSalary = wage * hours * 52;
//numEmployees++;
}
private boolean validHour(double hour) {
return (MIN_HOURS <= hour && hour <= MAX_HOURS);
}
private boolean validWage(double wage) {
return (MIN_WAGE <= wage && wage <= MAX_WAGE);
}
private boolean validCategory(String category) {
String[] categories = {"temp", "part time", "full time"};
for (int i = 0; i < categories.length; i++)
if (category.equalsIgnoreCase(categories[i]))
return true;
return false;
}
public double calculatePay() {
return annualSalary / 52;
}
#Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(super.toString());
sb.append("Wage: ").append(wage).append("\n");
sb.append("Hours: ").append(hours).append("\n");
sb.append("Category: ").append(category).append("\n");
return sb.toString();
}
}
Benefit.Class
public class Benefit {
private String healthInsurance;
private double lifeInsurance;
private int vacationDays;
public Benefit() {
healthInsurance = "Full";
lifeInsurance = 100;
vacationDays = 5;
}
public Benefit(String health, double life, int vacation) {
setHealthInsurance(health);
setLifeInsurance(life);
setVacation(vacation);
}
#Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("Health Insurance: ").append(healthInsurance).append("\n");
sb.append("Life Insurance: ").append(lifeInsurance).append("\n");
sb.append("Vacation Days: ").append(vacationDays).append("\n");
return sb.toString();
}
public void setHealthInsurance(String healthInsurance) {
this.healthInsurance = healthInsurance;
}
public String getHealthInsurance() {
return healthInsurance;
}
public void setLifeInsurance(double lifeInsurance) {
this.lifeInsurance = lifeInsurance;
}
public double getLifeInsurance() {
return lifeInsurance;
}
public void setVacation(int vacation) {
this.vacationDays = vacation;
}
public int getVacation() {
return vacationDays;
}
public void displayBenefit() {
this.toString();
}
}
Start by taking a look at How to Make Dialogs...
What you basically want is to use JOptionPane.showInputDialog, which can be used to prompt the use for input...
Yes, there are a few flavours, but lets keep it simply and look at JOptionPane.showInputDialog(Object)
The JavaDocs tells us that...
message - the Object to display
Returns:user's input, or null meaning the user canceled the input
So, from that we could use something like...
String value = JOptionPane.showInputDialog("What is your name?");
if (value != null) {
System.out.println("Hello " + value);
} else {
System.out.println("Hello no name");
}
Which displays...
Now, if we take a look at your code, you could replace the use of scan with...
public static String getInput(String inputType) {
String input = JOptionPane.showInputDialog("Enter the " + inputType + ": ");
return input;
}
As an example...
Now, what I might recommend is creating a simple helper method which can be used to prompt the user in a single line of code, for example...
public class InputHelper {
public static String promptUser(String prompt) {
String input = JOptionPane.showInputDialog(prompt);
return input;
}
}
which might be used something like...
String value = InputHelper.promptUser("Please enter the hours worked");
hours_ = Double.parse(value);
And this is where it get's messy, as you will now need to valid the input of the user.
You could extend the idea of the InputHelper to do automatic conversions and re-prompt the user if the value was invalid...as an idea
It is much easier than you think, if you try. Get used to reading the Java API.
http://docs.oracle.com/javase/7/docs/api/javax/swing/JOptionPane.html
Even has examples.
String input;
JOptionPane jop=new JOptionPane();
input=jop.showInputDialog("Question i want to ask");
System.out.println(input);

Categories