So I've been looking at this piece of code all afternoon and I can't see the error(s). Here is what I'm supposed to do:
Create a Delivery class for a delivery service. The class contains fields to hold the following:
A delivery number that contains eight digits. The first four digits represent the year, and the last four digits represent the delivery number.
A code representing the delivery area. A local delivery is code 1, and a long distance delivery is code 2.
A weight, in pounds, of the item to be delivered.
The fee for the delivery, as follows:
Create a constructor for the Delivery class that accepts arguments for the year,
delivery number within the year, delivery distance code, and weight of the package. The
constructor determines the eight-digit delivery number and delivery fee. Also include a
method that displays every Delivery object field. Save the file as Delivery.java.
Next, create an application that prompts the user for data for a delivery. Keep
prompting the user for each of the following values until they are valid:
A four-digit year between 2001 and 2025 inclusive
A delivery number for the year between 1 and 9999 inclusive
A package weight between 0.10 pound and 100 pounds inclusive
A delivery distance code that is either 1 or 2
When all the data entries are valid, construct a Delivery object, and then display its
values. Save the file as CreateDelivery.java.
So here is my delivery Class
import javax.swing.*;
import java.util.*;
class Delivery
{
//variables
private int year;
private int deliveryNumber; //deliveryNo
private double weight;
private int distanceCode; //code
//constructor
//Delivery()
//{
// year = year;
// deliveryNumber = deliveryNumber;
// weight = weight;
// distanceCode = distanceCode;
//}
//get year
public int getYear()
{
return year;
}
//set year
public int setYear (int newYear)
{
year = newYear;
return year;
}
//get deliveryNumber
public int getDeliveryNumber()
{
return deliveryNumber;
}
//set deliveryNumber
public int setDeliveryNumber (int newDeliveryNumber)
{
deliveryNumber = newDeliveryNumber;
return deliveryNumber;
}
//get weight
public double getWeight()
{
return weight;
}
//set Weight
public double setWeight (double newWeight)
{
weight = newWeight;
return weight;
}
//get distanceCode
public int getDistanceCode()
{
return distanceCode;
}
//set distanceCode
public int setDistanceCode (int newDistanceCode)
{
distanceCode = newDistanceCode;
return distanceCode;
}
//calculate fee
public double displayFees(int distance, double w) //distance = c
{
double fees = 0;
if(distance == 1)
{
if(w < 5)
{
fees = 12;
}
else if((w < 20)&&(w > 5))
{
fees = 16.50;
}
else if(w > 20)
{
fees = 22;
}
}
else if(distance == 2)
{
if(w < 5)
{
fees = 35;
}
else if(w >= 5)
{
fees = 47.95;
}
}
return fees;
}
//display method
public void display(int year, int deliveryNumber, double weight, int distanceCode)
{
System.out.println("Year: " + year + '\n'
+ "Delivery Number: " + deliveryNumber + '\n'
+ "Weight of the package: " + weight + '\n'
+ "Delivery code: " + distanceCode);
}
}
And here is my CreateDelivery Class
import javax.swing.JOptionPane;
import java.util.Scanner;
public class CreateDelivery
{
public static void main(String []args)
{
Delivery delivery1 = new Delivery();
//scanner year
Scanner input = new Scanner(System.in);
System.out.print("Please enter the current year, format (yyyy) >>> ");
delivery1.setYear(input.nextInt());
//loop year
while((delivery1.getYear() <= 2000)||(delivery1.getYear() >= 2026))
{
System.out.println('\n'+ "Error, year should be in the range of (2010 - 2025). Please enter a valid option >> ");
delivery1.setYear(input.nextInt());
}
//scanner for delivery number
System.out.print('\n'+ "Please enter a delivery number: ");
delivery1.setDeliveryNumber(input.nextInt());
//loop for delivery number
while((delivery1.getDeliveryNumber() <= 0001)||(delivery1.getDeliveryNumber() >= 10000))
{
System.out.println("Error, the delivery number is a 4 digit number between 0001 and 9999, please enter a valid option >> ");
delivery1.setDeliveryNumber(input.nextInt());
}
//scanner for weight
System.out.print("Please enter the weight of the package (in pounds): ");
delivery1.setWeight(input.nextDouble());
//loop for weight
while((delivery1.getWeight() <= .09)||(delivery1.getWeight() >= 101))
{
System.out.println("Error, the minimum allowed weight is 0.10 pounds and the maximum is 100 pounds. Please enter a valid weight >> ");
delivery1.setWeight(input.nextDouble());
}
//scanner for delivery code
System.out.print("Please enter 1 for local or 2 for long distance deliveries >> ");
delivery1.setDistanceCode(input.nextInt());
//loop for delivery code
while((delivery1.getDistanceCode() == 1) && (delivery1.getDistanceCode() == 2))
{
System.out.println("Error, please enter a valid distance code (1 for local deliveries and 2 for long distance deliveries) >> ");
delivery1.setDistanceCode(input.nextInt());
}
//turn int to string
String n = Integer.toString(delivery1.getDeliveryNumber());
String y = Integer.toString(delivery1.getYear());
String trackingNumber = n + y;
System.out.println(delivery1.getDistanceCode() + " "
+ trackingNumber + " " + delivery1.getWeight() + " " + fees);
}
}
So I made the changes you guys suggested, but now I can't pull fees from the Delivery class. Any thoughts?
Delivery()
{
year = year;
deliveryNumber = deliveryNumber;
weight = weight;
distanceCode = distanceCode;
}
Replace it with something along the lines of:
Delivery(int year, int deliveryNumber, int weight, int distanceCode)
{
this.year = year;
this.deliveryNumber = deliveryNumber;
this.weight = weight;
this.distanceCode = distanceCode;
}
From there, I would avoid using the set methods. Instead, store all the values into respective fields as you load them from the System.in. Once you have all the fields, create the Delivery object.
I think you are missing () at the end of the methods such as getDeliveryNumber,getYear etc. in the while loop.
and you are also using undeclared variables at the end such as getDeliveryNumber,getYear etc.
or we can do that simply like Delivery class
public class Delivery {
private int year,deliveryNumber,distanceCode;
private double weight;
private double fees=0;
//delivery class constructor
public Delivery(int year,int deliveryNumber,int distanceCode,double weight)
{
this.year=year;
this.deliveryNumber=deliveryNumber;
this.distanceCode=distanceCode;
this.weight=weight;
}
//calculate delivery fee
public void displayFees(int distanceCode, double weight)
{
if(distanceCode == 1)
{
if(weight<5)
{
fees = 12;
}
else if((weight < 20)&&(weight >=5))
{
fees = 16.50;
}
else if(weight > 20)
{
fees = 22;
}
}
else if(distanceCode == 2)
{
if(weight <5)
{
fees = 35;
}
else if(weight >= 5)
{
fees = 47.95;
}
}
}
public double getFee()
{
return fees;
}
}
and CreateDelivery class:
public class CreateDelivery {
public static void main(String[] args) {
int year=(int)ReadValues.readValue("Year", 1999,2026);
int deliveryNumber=(int)ReadValues.readValue("Delivery Number (1 to 10000)", 0,10000);
int distanceCode=(int)ReadValues.readValue("DistanceCode (1 or 2)",0, 3);
double weight=ReadValues.readValue("weight",0, 20);
Delivery delivery=new Delivery(year, deliveryNumber, distanceCode, weight);
delivery.displayFees(distanceCode, weight);
double fee=delivery.getFee();
System.out.println("\n\n*****Delivery Fees Details*****\n\nTrackingNumber:"+year+deliveryNumber+"\nDistanceCode:"+distanceCode+"\nFee :"+fee);
}
}
and for reading values from user another class called ReadValue
import java.util.Scanner;
public class ReadValues {
public static double readValue(String prompt, int min, int max) {
Scanner scan = new Scanner(System.in);
double value;
System.out.print(prompt + " :");
while (true) {
value = scan.nextDouble();
if (value < min || value > max)
System.out.println("Enter value between " + min + " & " + max);
else
break;
}
return value;
}
}
Related
This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 3 years ago.
I wish to limit the input of an integer value, between certain values using a while loop, with a couple of if-else if-else statements inside it! It's kinda working, but not exactly as it should... thought of using a switch as well, but I'm too "green" to know how! If someone's up for it and knows how... I'd welcome the use of a switch as well! Even a nested switch if need be...
Here's my code:
public class OOPProject {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
Scanner sc = new Scanner(System.in);
Car Honda = new Car(2018, 20000, "Honda", "Civic", 200, 6, 0, 0);
System.out.println("Manufacturer is: " + Honda.maker + ", model: " + Honda.model +
", year of fabrication: " + Honda.year + ", price: " + Honda.price + "!");
System.out.println("Please start the engine of your vehicle, by typing in 'Yes' or 'Start' or 'Turn on'!");
System.out.print("Do you wish to start the engine?");
System.out.println(" ");
Honda.StartEngine(sc);
//System.out.println("Engine is on!");
System.out.println("Do you wish to depart? Shift in to the first gear then and accelerate!");
System.out.println("Type in the speed: ");
Honda.accelerate(sc);
System.out.println("We are departing! Shifting in to " + Honda.currentGear +
"st gear and accelerating to " + Honda.currentSpeed + " km per hour!");
}
Constructor & functions:
public class Car {
public int year;
public int price;
public String maker;
public String model;
public int maximumSpeed;
public int numberOfGears;
public int currentSpeed;
public int currentGear;
public boolean isEngineOn;
public Car(int year, int price, String maker, String model, int maximumSpeed,
int numberOfGears, int currentSpeed, int currentGear) {
this.year = year;
this.price = price;
this.maker = maker;
this.model = model;
this.maximumSpeed = maximumSpeed;
this.numberOfGears = numberOfGears;
this.currentSpeed = currentSpeed;
this.currentGear = currentGear;
}
public String StartEngine(Scanner in) {
while(in.hasNext()) {
String input = in.nextLine();
if(input.equals("Yes") || input.equals("Start") || input.equals("Turn on")) {
isEngineOn = true;
System.out.println("Engine is on!");
return input;
} else {
System.out.println("Your input is not correct! Please start the engine!");
}
}
return null;
}
public int accelerate(Scanner in){
while(in.hasNextInt()){
currentSpeed = in.nextInt();
if(isEngineOn && currentSpeed > 0){
currentGear++;
} else if(currentSpeed > 50){
System.out.println("We cannot accelerate to more than 50 km per hour, when shifting in the 1st gear!");
} else{
System.out.println("We cannot depart at 0 km per hour!");
}
}
return 0;
}
}
It's taking the input, but it's not going further with it as it should, neither does it give an error message or stop the app, what's my mistake?
Changing the order of your if statement will work.
In your current method:
if(isEngineOn && currentSpeed > 0)
Will always return true with any value that you enter.
Using this method will get you a little further, although I suspect it will still won't be what you are expecting, but I hope it helps you in the right direction.
public int accelerate(Scanner in){
while(in.hasNextInt()){
currentSpeed = in.nextInt();
if(currentSpeed > 50 && currentGear <= 1){
System.out.println("We cannot accelerate to more than 50 km per hour, when shifting in the 1st gear!");
} else if(isEngineOn && currentSpeed > 0){
currentGear++;
break; /* I've added this to break out of the method to progress in your flow */
} else{
System.out.println("We cannot depart at 0 km per hour!");
}
}
return 0;
}
}
I want to start by saying that I'm a newby in Java, and it's also my first time asking something on this site. After 3 days trying to figure out how to break this small program in methods, I haven't been able to do so. could anyone help me with it ?
I've been reading and it looks like I'm violating the single responsibility principle. Any opinions would be more than welcome.
public class RateSystem {
double employeeSalary;
public int salaryRate(String employeePosition) {
if (employeePosition.equalsIgnoreCase("1")) {
return 40;
} else if (employeePosition.equalsIgnoreCase("2")) {
return 30;
} else
employeePosition.equalsIgnoreCase("3");
return 50;
}
}
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Employee position please...");
System.out.println("Press 1 for IT " + "\n" + "Press 2 for Tech" +
"\n" + "Press 3 for engineer");
String ePosition = input.nextLine();
RateSystem raul = new RateSystem();
int getPay = raul.salaryRate(ePosition);
System.out.println("How many hours did he work for the week?...");
int weekHours = input.nextInt();
int totalPay = 0;
if (weekHours <= 40) {
totalPay = getPay * weekHours;
System.out.println("Employee salary is " + totalPay);
} else {
int overTimeHours = weekHours - 40;
int extra$$PerOverTime = overTimeHours * getPay +(overTimeHours * getPay/2);
totalPay = getPay * (weekHours - overTimeHours);
System.out.println("The employee accumulated 40 hours equivalent to $"+
totalPay + " plus $" + extra$$PerOverTime + " overtime hours, a total of $"+(extra$$PerOverTime + totalPay));
}
}
}
If we are looking at main(), It does multiple tasks:
Receive user input
Calculate total pay and possible other finance information
Print the results
How's that for starters
I see followings could be added.
1) Salaries are created for Employees so why don't you create and Employee class and encapsulate details inside it like "employeePosition". So you can add more things later and having setters inside it you will get the chance of changing setter logics for employees.
2) You can create a Calculator class and create methods accepting single Employee or a List of Employees and calculate their Salary Rates.
3) You also can add a Printing related class. So you can produce different printing for single or List of Employees or may be like a tabular format.
I have identified following methods in your code.
1) showMainMenu --> responsible to show menu to the user
2) readMenuSelection --> here you will read whatever user has selected in the main menu. It should be read in int value rather than string.
3) For each Selection from menu there will be separate methods such as payForIT(), payForTech() and payForEngineer()
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Employee position please...");
System.out.println("Press 1 for IT " + "\n" + "Press 2 for Tech" + "\n" + "Press 3 for engineer");
String position = input.nextLine();
RateSystem rateSystem = new RateSystem();
rateSystem.setEmployeePosition(position);
System.out.println("How many hours did he work for the week?...");
int weekHours = input.nextInt();
rateSystem.setWeekHours(weekHours);
rateSystem.calculateSalary();
int totalPay = rateSystem.getTotalPay();
int overTime = rateSystem.getOvertime();
if (overTime > 0) {
System.out.println("The employee accumulated 40 hours equivalent to $" + totalPay + " plus $" + overTime
+ " overtime hours, a total of $" + (overTime + totalPay));
} else {
System.out.println("Employee salary is " + totalPay);
}
}
}
public class RateSystem {
private final int STANDARD_WORK = 40;
private double employeeSalary;
private int weekHours;
private Position employeePosition;
private int totalPay = 0;
private int overTime = 0;
public void setEmployeePosition(String position) {
employeePosition = Position.fromString(position);
}
public void setWeekHours(int weekHours) {
this.weekHours = weekHours;
}
public int getTotalPay() {
return totalPay;
}
public int getOvertime() {
return overTime;
}
public void calculateSalary() {
int salaryRate = employeePosition.getRate();
int workhours = (weekHours > STANDARD_WORK) ? STANDARD_WORK : weekHours;
int overTimeHours = (weekHours > STANDARD_WORK) ? (weekHours - STANDARD_WORK) : 0;
totalPay = workhours * weekHours;
overTime = (overTimeHours * salaryRate) + (overTimeHours * salaryRate / 2);
}
}
public enum Position {
IT(40), Tech(30), Engineer(50);
private int rate = 0;
Position(int r) {
rate = r;
}
public int getRate() {
return rate;
}
public static Position fromString(String position) {
switch (position) {
case "1":
return IT;
case "2":
return Tech;
case "3":
return Engineer;
}
return null;
}
}
To follow single responsibility principle you have to create method for each common task in your program. That helps do not repeat code and helps to modify code in one place.
I have created separate methods for building string and for printing string as you use it frequently in your code:
package com.stackoverflow.main;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
println("Employee position please...");
println(buildString("Press 1 for IT ", "\n", "Press 2 for Tech", "\n", "Press 3 for engineer"));
String ePosition = input.nextLine();
RateSystem raul = new RateSystem();
int getPay = raul.salaryRate(ePosition);
println("How many hours did he work for the week?...");
int weekHours = input.nextInt();
int totalPay = 0;
if (weekHours <= 40) {
totalPay = getPay * weekHours;
println(buildString("Employee salary is ", String.valueOf(totalPay)));
} else {
int overTimeHours = weekHours - 40;
int extra$$PerOverTime = overTimeHours * getPay + (overTimeHours * getPay / 2);
totalPay = getPay * (weekHours - overTimeHours);
println(buildString("The employee accumulated 40 hours equivalent to $", String.valueOf(totalPay),
" plus $", String.valueOf(extra$$PerOverTime), " overtime hours, a total of $",
String.valueOf((extra$$PerOverTime + totalPay))));
}
}
private static String buildString(String... strings) {
StringBuilder builder = new StringBuilder();
for (String string : strings) {
builder.append(string);
}
return builder.toString();
}
private static void println(String s) {
System.out.println(s);
}
}
And class RateSystem:
package com.stackoverflow.main;
public class RateSystem {
double employeeSalary;
public int salaryRate(String employeePosition) {
if (equalsIgnoreCase(employeePosition, "1")) {
return 40;
} else if (equalsIgnoreCase(employeePosition, "2")) {
return 30;
} else if (equalsIgnoreCase(employeePosition, "3"))
return 50;
return 0;
}
private boolean equalsIgnoreCase(String arg1, String arg2) {
return arg1.equalsIgnoreCase(arg2);
}
}
I can output the details from the student, but always when i do it displays
Exception in thread "main" java.lang.NullPointerException
at client.Client.main(Client.java:126)
and the program crashes.
The array is null , I don't why and I don't know how to fix that. Please help me to understand, the problem should be around here..
if (choice == 3) {
for (int a = 0; a < list.length; a++) { //To Display all current Student Information.
// list[i] = new student();
list[a].DisplayOutput();
}
Anyways here comes my code.
package client;
import java.util.Scanner;
public class Client {
//my infos
public static void AuthorInformation() {
System.out.print("__________________________________________\n"
+ "Student Name: xxxxxx xxxxxx\n"
+ "Student ID-Number: xxxxxx\n"
+ "Tutorial Timing: Wednesday 9:30 - 12:30 \n"
+ "Tutor Name: Mr xxxxxx\n\n"
+ "__________________________________________\n");
}
This is my client Class
public static void main(String[] args) {
AuthorInformation(); //calls the method for my information
student[] list = new student[20]; //my array
student student = new student();
int choice = 0; //variable for the choise of the menu
Scanner keyboard = new Scanner(System.in); //Scanner class
do { //MY menu in the do-while, so that it runs at least once while user enters 7(quit)
student.DisplayQuestions();
choice = keyboard.nextInt(); //takes the entered value from the user
if (choice == 1) {
System.out.println("Enter the Number of Students you want to store: ");//Enter amount of students to be stored
int studentNumber = keyboard.nextInt();
// student.addStudent();
for (int i = 0; i < studentNumber; i++) { //for loop is till the student number is achieved
list[i] = new student();
System.out.println("\nTitle of the student (eg, Mr, Miss, Ms, Mrs etc): ");
list[i].SetTitle(keyboard.next());
System.out.println("First name (given name)");
list[i].SetFirstName(keyboard.next());
System.out.println("A last name (family name/surname)");
list[i].SetFamilyName(keyboard.next());
System.out.println("Student number (ID):");
list[i].SetStudentID(keyboard.nextInt());
System.out.println("Enter the Day of birth(1-31): ");
list[i].SetDay(keyboard.nextInt());
System.out.println("Enter the Month of birth (1-12): ");
list[i].SetMonth(keyboard.nextInt());
System.out.println("Enter The Year of birth: ");
list[i].SetYear(keyboard.nextInt());
System.out.println("Students First Assignment Mark (0 - 100): ");
list[i].SetFirstMark(keyboard.nextInt());
System.out.println("Students Second Assignment Mark (0 - 100): ");
list[i].SetSecondMark(keyboard.nextInt());
System.out.println("Enter the mark of Student weekly practical work (0-10) ");
list[i].SetWeeklyMarks(keyboard.nextInt());
System.out.println("Please Enter the Marks for the final Exam(0 - 100): ");
list[i].SetFinalMark(keyboard.nextInt());
/* System.out.println("- - - - - - - - - - - - -");
System.out.println("Do you want to add another Student? (Yes/No)");
String a = keyboard.next();
if (a.equalsIgnoreCase("yes")) {
} else if (a.equalsIgnoreCase("no")) {
i = list.length + 1;
}*/
}
}
if (choice == 2) {
int x = 2;
double AverageNum = 0;
for (int p = 0; p < x; p++) { //This is to take the Average OverallMarks of all students
AverageNum += list[p].OverallMarking();
}
System.out.println("Total Average Of Overall Marks is :" + AverageNum / 2);
}
if (choice == 3) {
for (int a = 0; a < list.length; a++) { //To Display all current Student Information.
// list[i] = new student();
list[a].DisplayOutput();
}
}
if (choice == 4) { //To Display the distribution of grades awarded.
System.out.println("\nGrade Distribution: \n" + student.GetCounterHD() + " HDs\n" + student.GetCounterD() + " Ds\n" + student.GetCounterC() + " Cs\n" + student.GetCounterP() + " Ps\n" + student.GetCounterN() + " Ns\n");
}
if (choice == 5) {
System.out.println("Enter Student's ID Number to search for: "); // to take the id number from the user
int FindID = keyboard.nextInt();
boolean Found = false;
// to find with the student ID Number details of the student.
for (int i = 0; i < 10; i++) {
if (FindID == list[i].GetStudentID()) {
list[i].DisplayOutput();
Found = true;
break;
}
}
}
if (choice == 6) { //
System.out.println("Enter Student's Name to search for: ");
String SearchStudentName = keyboard.next(); //take the name of the student
boolean Found = false;
//To find the name of the student it loops till it has it or the limit of studentnumbers are achieved.
for (int i = 0; i < list.length; i++) {
if (SearchStudentName.equalsIgnoreCase(list[i].GetFirstName())) {
list[i].DisplayOutput();
Found = true;
break;
}
}
}
} while (choice != 7);
{ //while statement quit the program
System.out.println("\nYou Quit.");
}
}
}
And here is my student class
package client;
import java.util.Scanner;
public class student {
//The instance vriables for students (Title, first name, family name,
Student ID, date of birth in day month and year, first and second
assignment mark, mark of weekly practical work and final exam
private String Title;
private String FirstName;
private String FamilyName;
private long StudentID;
private int Day;
private int Month;
private int Year;
private float FirstMark;
private float SecondMark;
private float WeeklyMarks;
private float FinalMark;
//those private instance variables are for the calculation of (first and
second assignment mark, mark of weekly practical work and exam mark, final
mark and overall mark)
private float FirstMarkPercentage;
private float SecondMarkPercentage;
private float WeeklyMarksPercentage;
private float ExamPercentage;
private String FinalGrade;
private float OverallMarks = 0;
//those private instance variables are to count the the marks(
private int CounterN = 0;
private int CounterP = 0;
private int CounterC = 0;
private int CounterD = 0;
private int CounterHD = 0;
public student(String Title, String FirstName, String FamilyName, long StudentID, int Day, int Month, int Year, float FirstMark, float SecondMark, float WeeklyMarks, float FinalMark) {
this.Title = Title;
this.FirstName = FirstName;
this.FamilyName = FamilyName;
this.StudentID = StudentID;
this.Day = Day;
this.Month = Month;
this.Year = Year;
this.FirstMark = FirstMark;
this.SecondMark = SecondMark;
this.WeeklyMarks = WeeklyMarks;
this.FinalMark = FinalMark;
this.FinalGrade = FinalGrade;
}
//This Method is to display (Title, first name, family name, Student ID, date of birth in day month and year, first and second assignment mark, mark of weekly practical work and final exam)
public student() {
Title = "";
FirstName = "";
FamilyName = "";
StudentID = 0;
Day = 0;
Month = 0;
Year = 0;
FirstMark = 0;
SecondMark = 0;
WeeklyMarks = 0;
FinalMark = 0;
}
//The methods starting with Get...(), are to return the (Title, first name, family name, Student ID, date of birth in day month and year, first and second assignment mark, mark of weekly practical work and final exam and the marks N, P, C, D & HD)
public String GetTitle() {
return Title;
}
public String GetFirstName() {
return FirstName;
}
public String GetFamilyName() {
return FamilyName;
}
public long GetStudentID() {
return StudentID;
}
public int GetDay() {
return Day;
}
public int GetMonth() {
return Month;
}
public int GetYear() {
return Year;
}
public float GetFirstMark() {
return FirstMark;
}
public float GetSecondMark() {
return SecondMark;
}
public float GetWeeklyMarks() {
return WeeklyMarks;
}
public float GetFinalMark() {
return FinalMark;
}
public String GetFinalGrade() {
return FinalGrade;
}
public int GetCounterHD() {
return CounterHD;
}
public int GetCounterD() {
return CounterD;
}
public int GetCounterC() {
return CounterC;
}
public int GetCounterP() {
return CounterP;
}
public int GetCounterN() {
return CounterN;
}
public float GetOverallMarks() {
return OverallMarks;
}
//The methods starting with Set...(), are to set the (Title, first name, family name, Student ID, date of birth in day month and year, first and second assignment mark, mark of weekly practical work and final exam and the marks N, P, C, D & HD)
public void SetTitle(String Title) {
this.Title = Title;
}
public void SetFirstName(String FirstName) {
this.FirstName = FirstName;
}
public void SetFamilyName(String FamilyName) {
this.FamilyName = FamilyName;
}
public void SetStudentID(int StudentID) {
this.StudentID = StudentID;
}
public void SetDay(int Day) {
this.Day = Day;
}
public void SetMonth(int Month) {
this.Month = Month;
}
public void SetYear(int Year) {
this.Year = Year;
}
public void SetFirstMark(float FirstMark) {
this.FirstMark = FirstMark;
}
public void SetSecondMark(float SecondMark) {
this.SecondMark = SecondMark;
}
public void SetWeeklyMarks(float WeeklyMarks) {
this.WeeklyMarks = WeeklyMarks;
}
public void SetFinalMark(float FinalMark) {
this.FinalMark = FinalMark;
}
public void SetFinalGrade(String FinalGrade) {
this.FinalGrade = FinalGrade;
}
public void SetOverallMarks(float OverallMarks) {
this.OverallMarks = OverallMarks;
}
public boolean equals(student OtherStudent) {
return (this.FirstName.equalsIgnoreCase(OtherStudent.FirstName)) && (this.FamilyName.equalsIgnoreCase(OtherStudent.FamilyName));
}
//this method is for the calculation of (first and second assignment mark, mark of weekly practical work and exam mark, final mark and overall mark)
public float OverallMarking() {
FirstMarkPercentage = ((FirstMark / 100) * 20);
SecondMarkPercentage = ((SecondMark / 100) * 20);
WeeklyMarksPercentage = ((WeeklyMarks / 10) * 10);
ExamPercentage = ((FinalMark / 100) * 50);
OverallMarks = FirstMarkPercentage + SecondMarkPercentage + WeeklyMarksPercentage + ExamPercentage; //for the overall mark returns
return OverallMarks;
}
//this function arranges the grade calculations and returns the final grade
public String GradeCalculations() {
if (OverallMarks >= 80 && OverallMarks <= 100) { // if grade lies within this range print HD
FinalGrade = "HD";
CounterHD++;
} else if (OverallMarks >= 70 && OverallMarks < 80) { // if grade lies within this range print D
FinalGrade = "D";
CounterD++;
} else if (OverallMarks >= 60 && OverallMarks < 70) { // if grade lies within this range print C
FinalGrade = "C";
CounterC++;
} else if (OverallMarks >= 50 && OverallMarks < 60) { // if grade lies within this range print P
FinalGrade = "P";
CounterP++;
} else if (OverallMarks < 50 && OverallMarks >= 0) { // if grade lies within this range print N
FinalGrade = "N";
CounterN++;
}
return FinalGrade;
}
public void DisplayQuestions() {
System.out.println("\n Welcome to the Menu to perform one of the following operations (You must enter a number between 1-7):");
System.out.println("(1) To add the Student Information.");
System.out.println("(2) To Display the Output from the Average Overall Mark for students.");
System.out.println("(3) To Display all current Student Information.");
System.out.println("(4) To Display the distribution of grades awarded.");
System.out.println("(5) for entering a student ID Number To view all details of the student.");
System.out.println("(6) for entering a student name To view all details of the student.");
System.out.println("(7) Quit");
System.out.println("\n__________________________________________");
}
//This function displays the details of the student with before calculated marks.
public void DisplayOutput() {
System.out.println("\nName: " + GetTitle() + " " + GetFirstName() + " " + GetFamilyName());
System.out.println("Student ID: " + GetStudentID());
System.out.println("Date of Birth: " + GetDay() + "/" + GetMonth() + "/" + GetYear());
System.out.println("Assignment 1 Marks: " + GetFirstMark());
System.out.println("Assignment 2 Marks: " + GetSecondMark());
System.out.println("Weekly Practical Marks: " + GetWeeklyMarks());
System.out.println("Final Exam Marks: " + GetFinalMark());
System.out.println("Final Marks & Grade: " + OverallMarking() + "/" + GradeCalculations());
}
public void addStudent() {
/*Scanner keyboard = new Scanner(System.in);
for (int i = 0; i < list.length; i++) { //for loop is till the student number is achieved
list[i] = new student();
System.out.println("\nTitle of the student (eg, Mr, Miss, Ms, Mrs etc): ");
list[i].SetTitle(keyboard.next());
System.out.println("First name (given name)");
list[i].SetFirstName(keyboard.next());
System.out.println("A last name (family name/surname)");
list[i].SetFamilyName(keyboard.next());
System.out.println("Student number (ID):");
list[i].SetStudentID(keyboard.nextInt());
System.out.println("Enter the Day of birth(1-31): ");
list[i].SetDay(keyboard.nextInt());
System.out.println("Enter the Month of birth (1-12): ");
list[i].SetMonth(keyboard.nextInt());
System.out.println("Enter The Year of birth: ");
list[i].SetYear(keyboard.nextInt());
System.out.println("Students First Assignment Mark (0 - 100): ");
list[i].SetFirstMark(keyboard.nextInt());
System.out.println("Students Second Assignment Mark (0 - 100): ");
list[i].SetSecondMark(keyboard.nextInt());
System.out.println("Enter the mark of Student weekly practical work (0-10) ");
list[i].SetWeeklyMarks(keyboard.nextInt());
System.out.println("Please Enter the Marks for the final Exam(0 - 100): ");
list[i].SetFinalMark(keyboard.nextInt());
System.out.println("- - - - - - - - - - - - -");
System.out.println("Do you want to add another Student? (Yes/No)");
String a = keyboard.next();
if (a.equalsIgnoreCase("yes")) {
addStudent();
} else if (a.equalsIgnoreCase("no")) {
i=list.length+1;
}
}*/
}
}
The array isn't null.
The exception is thrown when you try to call a method on a null member of the array.
You iterate over the full array, but have not necessarily filled the entire array. Members that you have not assigned to reference an object are null.
for (int a = 0; a < list.length; a++) { //To Display all current Student Information.
// list[i] = new student();
list[a].DisplayOutput();
}
One fix would be to stop iterating after you've hit the first null.
for (int a = 0; a < list.length; a++) { //To Display all current Student Information.
// list[i] = new student();
student student = list[a];
if ( null == student ) {
break;
}
else {
list[a].DisplayOutput();
}
}
Another fix would be to remember in case 1 how many students were stored, and change the loop condition to reflect that.
for (int a = 0; a < cntStudents; a++) { //To Display all current Student Information.
By the way, in Java code it is almost universally accepted that:
Class names begin with an uppercase character.
Method names begin with a lowercase character.
Im trying to get different variables from loan but none of them ever get to loan.java. My inheritance goes from Loan.Java > BusinessLoan.java > CreateLoan.java. I can get a variable from CreateLoan to display in business but when I set it in business I can't grab it. And I know some of this stuff is stupid but this is my final so some of the stuff was required. Heres my code
Loan.java
package Construction;
public class Loan implements LoanConstant{
public static int loanNumber;
public static String lastName;
public static int loanAmount;
public static int interestRate;
public static int term;
public int primeRate;
public int getLoanNumber() { return loanNumber; }
public void setLoanNumber(int n) { n = loanNumber; }
public String getLastName() { return lastName; }
public void setLastName(String s) { s = lastName; }
public int getLoanAmount() { return loanAmount; }
public void setLoanAmount(int n) {
n = loanAmount;
if (loanAmount > MAX_LOAN_AMOUNT)
loanAmount = MAX_LOAN_AMOUNT;
}
public int getTerm() { return term; }
public void setTerm(int n) {
n = term;
if (term == 1) {
term = SHORT_TERM;
} else if (term == 3) {
term = MEDIUM_TERM;
} else if(term == 5) {
term = LONG_TERM;
} else
term = SHORT_TERM;
}
public int getInterestRate() { return interestRate; }
public void setInterestRate(int i) { i = interestRate; }
public static void displayAll() {
System.out.println("The Company's Name is " + COMPANY_NAME);
System.out.println("The loan number is " + loanNumber);
System.out.println("The last name on the loan is " + lastName);
System.out.println("The loan amount is " + loanAmount);
System.out.println("The interest rate on the loan is " + interestRate);
System.out.println("The term on the account is " + term);
}
}
PersonalLoan.java
package Construction;
public class PersonalLoan extends Loan{
public PersonalLoan(int ln, String last, int la, int term) {
setLoanNumber(ln);
setLastName(last);
setLoanAmount(la);
setTerm(term);
interestRate = (int)((primeRate * 0.02) + primeRate);
setInterestRate(interestRate);
}
}
BusinessLoan.java
package Construction;
public class BusinessLoan extends Loan{
public BusinessLoan(int ln, String last, int la, int term) {
setLoanNumber(ln);
setLastName(last);
setLoanAmount(la);
setTerm(term);
interestRate = (int)((primeRate * 0.01) + primeRate);
setInterestRate(interestRate);
}
}
CreateLoan.java
package Construction;
import java.util.Scanner;
public class CreateLoan {
public static void main(String[] args) {
int x = 0;
int primeRate;
String type;
Scanner input = new Scanner(System.in);
Loan[] loans = new Loan[5];
System.out.println("Please enter the prime interest rate");
primeRate = input.nextInt();
primeRate = primeRate/100;
input.nextLine();
for(x = 0; x < 6; ++x) {
System.out.println("Please enter a loan type. Choose either Business or Personal. If you don't type it like that you'll get an error.");
type = input.nextLine();
if (type.equalsIgnoreCase("Business")) {
System.out.println("What is the account number on the loan?");
int ln = input.nextInt();
System.out.println("What is the last name on the account?");
String last = input.nextLine();
input.nextLine();
System.out.println("What is the loan amount? If you put more then 100k it'll only accept up to 100k");
int la = input.nextInt();
System.out.println("What is the term on the account? If you enter something other then 1, 3, or 5 it will default to a short term.");
int term = input.nextInt();
loans[x] = new BusinessLoan(ln, last, la, term);
System.out.println("The Company's Name is " + Loan.COMPANY_NAME);
System.out.println("The loan number is " + loans[x].getLoanNumber());
System.out.println("The last name on the loan is " + loans[x].getLastName());
System.out.println("The loan amount is " + loans[x].getLoanAmount());
System.out.println("The interest rate on the loan is " + loans[x].getInterestRate());
System.out.println("The term on the account is " + loans[x].getTerm());
}
else if (type.equalsIgnoreCase("Personal")) {
System.out.println("What is the account number on the loan?");
int ln = input.nextInt();
System.out.println("What is the last name on the account?");
String last = input.nextLine();
input.nextLine();
System.out.println("What is the loan amount? If you put more then 100k it'll only accept up to 100k");
int la = input.nextInt();
System.out.println("What is the term on the account? If you enter something other then 1, 3, or 5 it will default to a short term.");
int term = input.nextInt();
loans[x] = new PersonalLoan(ln, last, la, term);
System.out.println("The Company's Name is " + Loan.COMPANY_NAME);
System.out.println("The loan number is " + loans[x].getLoanNumber());
System.out.println("The last name on the loan is " + loans[x].getLastName());
System.out.println("The loan amount is " + loans[x].getLoanAmount());
System.out.println("The interest rate on the loan is " + loans[x].getInterestRate());
System.out.println("The term on the account is " + loans[x].getTerm());
} else {
System.out.println("You've entered an invalid type. Please restart and try again.");
System.exit(0);
}
}
}
}
LoanConstants.java
package Construction;
public interface LoanConstant {
public final static int SHORT_TERM = 1;
public final static int MEDIUM_TERM = 3;
public final static int LONG_TERM = 5;
public final static String COMPANY_NAME = "Sanchez Construction";
public final static int MAX_LOAN_AMOUNT = 100000;
}
In addition to the Loan fields being static (remove the static). You should also update your setters.
public void setLoanNumber(int n) { n = loanNumber; }
public void setLastName(String s) { s = lastName; }
You are assigning the value to the passed in variable (not the field). Should be
public void setLoanNumber(int n) { loanNumber = n; }
public void setLastName(String s) { lastName = s; }
and
public void setTerm(int n) {
// n = term;
if (n == 1) {
term = SHORT_TERM;
} else if (n == 3) {
term = MEDIUM_TERM;
} else if (n == 5) {
term = LONG_TERM;
} else
term = SHORT_TERM;
}
public void setInterestRate(int i) { interestRate = i; }
I cannot find out where my mathematical error is. I just cannot see why I continue to receive no values back for my determineCableSrvs method.
private static Scanner input = new Scanner(System.in); //STORES CUSTOMER NAME STRING VALUE
public static void main(String[] args)
{//BEGIN main()
//Variables
int subscription = 0; //STORES SUBSCRIPTION INTEGER VALUE
int moviesOnDemand = 0; //STORES MOVIES ON DEMAND INTEGER VALUE
double cableSrvs = 0; //STORES TOTAL CABLE SERVICE DECIMAL VALUE
double totalMovieCharges = 0; //STORES TOTAL MOVIE CHARGES DECIMAL VALUE
double total = 0; //STORES TOTAL DECIMAL VALUE
char confirm = 'Y'; //LOOP CONTROL VARIABLE SET TO Y
Calendar dateTime = Calendar.getInstance(); //STORES THE DATE VALUE
String customerName = "";
while(Character.toUpperCase(confirm) == 'Y') //START OF WHILE LOOP AUTOMATICALLY ENTERS
{
String customer = setCustNm(customerName);
double cable = setCablePkg(subscription);
double type = determineCableSrv(subscription, cableSrvs);
int movies = setMoviePurchase(moviesOnDemand);
totalMovieCharges = movies * 7; //CALCULATING THE TOTAL MOVIE ON DEMAND CHARGE
total = totalMovieCharges + type; //CALCULATING THE OVERALL TOTAL
System.out.printf("%n%s %tD"
+ "\nCustomer: %S"
+ "%n%nCable Service: $%,21.2f"
+ "%nMovies-On-Demand-HD: %,20.2f"
+ "\n\nTOTAL DUE: $%,21.2f\n",
"SA CABLE CHARGES AS OF", dateTime, customer, type,
totalMovieCharges, total);
input.nextLine();
askNewSubscription(confirm);
printThankYou(confirm);
}
}
public static String setCustNm(String customerName)
{
// 1st prompt
System.out.printf("%n%n%nWELCOME TO SA CABLE %n");
System.out.printf("%nPlease enter your name: "); //PROMPTING USER TO ENTER NAME
customerName = input.nextLine(); //CAPTURES USERS NAME
return customerName;
}
public static int setCablePkg(int subscription)
{
do{
// 2nd Prompt DISPLAYING THE DIFFERENT PACKAGES AVAILABLE FOR SUBSCRIPTION
System.out.printf("%nSA CABLE - SUBSCRIPTION PACKAGES " +
"%n%n1. Basic: Local & major TV network channels %s" +
"%n2. Deluxe: Local, major TV, cable & 100 other channels %s" +
"%n3. Premium: Deluxe package plus HEB, on-demand & 300 other channels %s",
"$35.00", "75.00", "110.00") ;
System.out.printf("%n%nSelect your cable subscription package: ");
subscription = input.nextInt();//CAPTURING USER INPUT
}while (subscription < 1 || subscription > 3);
return subscription;
}
public static double determineCableSrv(int subscription, double cableSrvs)
{
if(subscription == 1) // IF STATEMENT TO IDENTIFY THE PRICE OF THE TOTAL CABLE SERVICE
{
cableSrvs = 35;
}
else if(subscription == 2)
{
cableSrvs = 75;
}
else if(subscription == 3)
{
cableSrvs = 110;
}
return cableSrvs;
}
public static int setMoviePurchase(int moviesOnDemand)
{
System.out.printf("%nSA CABLE - MOVIES " +
"%n%nEnter the number of Movies-On-Demand-HD purchases: ");
moviesOnDemand = input.nextInt();
return moviesOnDemand;
}
public static char askNewSubscription(char confirm)
{
System.out.printf("\nEnter 'Y' to continue with a new subscription or 'N' to exit: ");
confirm = input.nextLine().charAt(0);
return confirm;
}
public static char printThankYou(char confirm)
{
if(Character.toUpperCase(confirm) == 'Y')
{
confirm = 'Y';
}
if (Character.toUpperCase(confirm) != 'Y')
{
confirm = 'N';
System.out.printf("Thank you for being a valued SA Cable customer!");
System.exit(0);
}
return confirm;
}
I'm having trouble with this part:
public static double determineCableSrv(int subscription, double cableSrvs)
{
if(subscription == 1) // IF STATEMENT TO IDENTIFY THE PRICE OF THE TOTAL CABLE SERVICE
{
cableSrvs = 35;
}
else if(subscription == 2)
{
cableSrvs = 75;
}
else if(subscription == 3)
{
cableSrvs = 110;
}
return cableSrvs;
}
Here is how I'm calling the method:
double type = determineCableSrv(subscription, cableSrvs);
I cannot seem to get the return value. I need the value for:
total = totalMovieCharges + type; //CALCULATING THE OVERALL TOTAL
and this print out statement:
System.out.printf("%n%s %tD"
+ "\nCustomer: %S"
+ "%n%nCable Service: $%,21.2f"
+ "%nMovies-On-Demand-HD: %,20.2f"
+ "\n\nTOTAL DUE: $%,21.2f\n",
"SA CABLE CHARGES AS OF", dateTime, customer, type,
totalMovieCharges, total);
You set subscription equal to 0 and never change it before passing it in to the determineCableSrv method. You do the same with cableSrvs, so the return value from your method is going to be 0. The cableSrvs variable isn't read inside the method, so it probably shouldn't be in input parameter to begin with.