public class ParkingLotApplication {
static Scanner input = new Scanner(System.in);
public static ParkingDescription[][] ParkingLot = new ParkingDescription[3][15];
public StudentDescription StudDesc = new StudentDescription();
static int i = 0;
static int j = 0;
static int parkLevel = 0;
static int parkSlot = 0;
public static void main(String[] args) {
// TODO: Add your code here
ParkingLotApplication PA = new ParkingLotApplication();
PA.menu();
}
public void menu() {
Scanner input = new Scanner(System.in);
System.out.println("WELCOME TO CAR PARK SYSTEM");
System.out.println("Enter your name: ");
String nm = input.nextLine();
System.out.println("Enter your password: ");
int pass = input.nextInt();
if ((nm.equals("admin12")) && (pass == 12345)) {
Login();
} else {
menu();
}
}
public void Login() {
System.out.println("|----------------------------------|");
System.out.println("| Admin Menu |");
System.out.println("|----------------------------------|");
System.out.println("| N- New Registration |");
System.out.println("| U- Update Data |");
System.out.println("|----------------------------------|");
char ch = input.next().charAt(0);
switch (ch) {
case 'N':
case 'n':
Reg();
break;
case 'U':
case 'u':
UpdatePark();
break;
default:
System.out.println("Choose Again!");
Login();
break;
}
}
public void Reg() {
System.out.println();
System.out.println(" **Parking Lot** ");
System.out.println(" ________________________________________________________________________________");
for (i = 0; i < 3; i++) {
for (j = 0; j < 15; j++) {
ParkingLot[i][j] = new ParkingDescription();
System.out.print(" * " + ParkingLot[i][j].getStatus());
}
System.out.println();
System.out.println(" ********************************************************************************");
}
System.out.println("Please insert number 1-3 to choose the parking level");
parkLevel = input.nextInt();
System.out.println("Please insert number 1-15 to choose the parking slot");
parkSlot = input.nextInt();
//check available
if (parkLevel == 1) {
ParkingLot[0][parkSlot - 1] = new ParkingDescription();
if (ParkingLot[0][parkSlot - 1].getAvailable() == true) {
System.out.println("Please Enter tp: ");
int tp = input.nextInt();
System.out.println("Please Enter First Name: ");
String ft = input.next();
System.out.println("Please Enter Last Name: ");
String lt = input.next();
System.out.println("Please Enter Contact Number: ");
int cn = input.nextInt();
System.out.println("Please Enter Email Address: ");
String ea = input.next();
System.out.println("Please Enter Car Number: ");
String cnb = input.next();
System.out.println("Please Enter Date Registered : ");
int date = input.nextInt();
StudDesc.setStudDesc(tp, ft, lt, cn, ea, cnb, date);
int pID = (parkLevel * 1000) + parkSlot;
ParkingLot[0][parkSlot - 1].setPark(pID, false, StudDesc);
System.out.println("Thanks");
menu();
} else {
System.out.println("Sorry");
menu();
}
} else if (parkLevel == 2) {
ParkingLot[1][parkSlot - 1] = new ParkingDescription();
if (ParkingLot[1][parkSlot - 1].getAvailable() == true) {
System.out.println("Please Enter tp: ");
int tp = input.nextInt();
System.out.println("Please Enter First Name: ");
String ft = input.next();
System.out.println("Please Enter Last Name: ");
String lt = input.next();
System.out.println("Please Enter Contact Number: ");
int cn = input.nextInt();
System.out.println("Please Enter Email Address: ");
String ea = input.next();
System.out.println("Please Enter Car Number: ");
String cnb = input.next();
System.out.println("Please Enter Date Registered : ");
int date = input.nextInt();
StudDesc.setStudDesc(tp, ft, lt, cn, ea, cnb, date);
int pID = (parkLevel * 1000) + parkSlot;
ParkingLot[1][parkSlot - 1].setPark(pID, false, StudDesc);
System.out.println("Thanks");
menu();
} else {
System.out.println("Sorry");
menu();
}
} else if (parkLevel == 3) {
ParkingLot[2][parkSlot - 1] = new ParkingDescription();
if (ParkingLot[2][parkSlot - 1].getAvailable() == true) {
System.out.println("Please Enter tp: ");
int tp = input.nextInt();
System.out.println("Please Enter First Name: ");
String ft = input.next();
System.out.println("Please Enter Last Name: ");
String lt = input.next();
System.out.println("Please Enter Contact Number: ");
int cn = input.nextInt();
System.out.println("Please Enter Email Address: ");
String ea = input.next();
System.out.println("Please Enter Car Number: ");
String cnb = input.next();
System.out.println("Please Enter Date Registered : ");
int date = input.nextInt();
StudDesc.setStudDesc(tp, ft, lt, cn, ea, cnb, date);
int pID = (parkLevel * 1000) + parkSlot;
ParkingLot[2][parkSlot - 1].setPark(pID, false, StudDesc);
System.out.println("Thanks");
menu();
} else {
System.out.println("Sorry");
menu();
}
}
}
public void UpdatePark() {
System.out.println();
System.out.println(" **Parking Lot** ");
System.out.println(" ________________________________________________________________________________");
for (i = 0; i < 3; i++) {
for (j = 0; j < 15; j++) {
ParkingLot[i][j] = new ParkingDescription();
System.out.print(" * " + ParkingLot[i][j].getStatus());
}
System.out.println();
System.out.println(" ********************************************************************************");
}
System.out.println("Please insert number 1-3 to choose the parking level");
parkLevel = input.nextInt();
System.out.println("Please insert number 1-15 to choose the parking slot");
parkSlot = input.nextInt();
//check available
if (parkLevel == 1) {
ParkingLot[0][parkSlot - 1] = new ParkingDescription();
if (ParkingLot[0][parkSlot - 1].getAvailable() == false) {
ParkingLot[0][parkSlot - 1].showDetails();
menu();
} else {
System.out.println("Sorry");
menu();
}
} else if (parkLevel == 2) {
ParkingLot[1][parkSlot - 1] = new ParkingDescription();
if (ParkingLot[1][parkSlot - 1].getAvailable() == true) {
ParkingLot[1][parkSlot - 1].showDetails();
menu();
} else {
System.out.println("Sorry");
menu();
}
} else if (parkLevel == 3) {
ParkingLot[2][parkSlot - 1] = new ParkingDescription();
if (ParkingLot[2][parkSlot - 1].getAvailable() == true) {
ParkingLot[2][parkSlot - 1].showDetails();
menu();
} else {
System.out.println("Sorry");
menu();
}
}
}
}
//Class parking description
public class ParkingDescription {
public static int StudID, ParkSpaceID, DReg;
public static String Status, CNum;
public static Boolean Available = true;
public ParkingDescription() {
// TODO: Add your code here
}
public void setPark(int parkSpaceID, Boolean available, StudentDescription StDe)
{
this.StudID = StDe.getStudentID();
this.CNum = StDe.getCarNumber();
this.DReg = StDe.getDateReg();
this.ParkSpaceID = parkSpaceID;
this.Available = available;
}
public Boolean getAvailable()
{
return Available;
}
public String getStatus()
{
if(Available == false){
return "1";
} else {
return "0";
}
}
public void showDetails()
{
//generate report
System.out.println("Student ID : TP"+StudID);
System.out.println();
System.out.println("Car Number : "+CNum);
System.out.println();
System.out.println("Parking Space : L"+ParkSpaceID);
System.out.println();
System.out.println("Date Register : "+DReg);
}
}
//Student class
public class StudentDescription {
public int StudentID, CNumber, DateReg;
public String FName, LName, EMail, CarNum;
public StudentDescription() {
// TODO: Add your code here
}
public void setStudDesc(int studentID, String fName, String lName, int cNumber, String eMail, String carNum, int dateReg)
{
this.StudentID = studentID;
this.FName = fName;
this.LName = lName;
this.CNumber = cNumber;
this.EMail = eMail;
this.CarNum = carNum;
this.DateReg = dateReg;
}
public int getStudentID()
{
return this.StudentID;
}
public String getCarNumber()
{
return this.CarNum;
}
public int getDateReg()
{
return this.DateReg;
}
}
I have this problem. when i want to set one parking detail object into ParkingLot array, the array is insert same data information on all of array. the output suppose to be like this:
**Parking Lot**
* 1 * 0 * 0 * 0 * 0 * 0 * 0 * 0 * 0 * 0 * 0 * 0 * 0 * 0 * 0
* 0 * 0 * 0 * 0 * 0 * 0 * 0 * 0 * 0 * 0 * 0 * 0 * 0 * 0 * 0
* 0 * 0 * 0 * 0 * 0 * 0 * 0 * 0 * 0 * 0 * 0 * 0 * 0 * 0 * 0
but I got all the output being set to 1. So how to solve this problem? thanks..
There's still lots of code that you haven't shown, for example, the code for the ParkingDescription class. But based on what you HAVE shown ...
In the chunk of code that prints out all the statuses, (which for some reason, you've coded twice - once in Reg and once in UpdatePark), you are populating your array with 45 new ParkingDescription objects, and printing the status of each one. That is, you're throwing away all the ParkingDescription objects that you had previously, and only printing brand new objects. You really don't want to do that, because it's the ParkingDescription objects that store all the data that the user has entered.
I guess you're getting all 1s because 1 is the status of a new ParkingDescription.
UPDATE
Now that you've shown your ParkingDescription class, I see that the problem is that you've declared its fields as static. That means that there's only one copy of each field, shared between all the instances of this class. Remove the word static from the field declarations, and the problem should be fixed.
And the next time you post a question on Stack Overflow, I strongly recommend posting ALL the code when you first post the question. Don't just post the part where YOU think the bug is, because you waste everyone's time if you're wrong.
Related
I made the invalid grades into " " but it seems in output it's showing space like this https://i.stack.imgur.com/3kHZW.png how to show only the valid grades? the invalid grades is making blank space in output
This is the question https://i.stack.imgur.com/uxLhG.png
This is the needed output https://i.stack.imgur.com/HNZpZ.png
This is my Program
String [][] student = new String[100][3];
int stu = 0, totalp=0, totalf=0;
for(int h=0; h<100; h++) {
System.out.print("Enter Name: ");
student[h][0] = sc.nextLine();
System.out.print("Enter Grade: ");
student[h][1] = sc.nextLine();
int grade = Integer.parseInt(student[h][1]);
if(grade >100 || grade <50) {
student[h][0] = "";
student[h][1] = "";
student[h][2] = "";
System.out.println("Invalid Grade");
}
else if(grade >=75) {
student[h][2] = ("Passed");
totalp++;
}
else if(grade <=74) {
student[h][2] = ("Failed");
totalf++;
}
System.out.print("Add new record (Y/N)?: ");
char choice = sc.nextLine().charAt(0);
System.out.println("");
if(choice == 'y' || choice =='Y') {
stu++;
continue;
}
else if(choice == 'n' ||choice =='N') {
break;
}
}
System.out.println("\nGRADE SUMMARY REPORT");
System.out.println("\nName\tGrades\tRemarks");
for(int i =0; i<stu+1; i++) {
for(int h =0; h<student[i].length; h++) {
System.out.print(student[i][h] + "\t");
}
System.out.println();
}
System.out.println("\nTotal Passed: " + totalp);
System.out.println("Total Failed: "+ totalf);
If a grade entered by the user is invalid, just don't add it to student array. Then it won't get printed at all. You should also handle the case where the user does not enter a number when asked to enter a grade.
When asking the user if she wants to add a new record, you only need to check whether she entered a Y. Anything else can be considered a no.
The below code uses method printf to format the report. Also, in order to format the report, I keep track of the longest name entered by the user.
import java.util.Scanner;
public class Students {
private static final int MAX_ROWS = 100;
private static final int NAME = 0;
private static final int GRADE = 1;
private static final int REMARK = 2;
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
String[][] student = new String[MAX_ROWS][3];
int totalp = 0, totalf = 0, longest = 0;
int h = 0;
while (h < MAX_ROWS) {
System.out.print("Enter Name: ");
String name = sc.nextLine();
int len = name.length();
if (len > longest) {
longest = len;
}
System.out.print("Enter Grade: ");
String grade = sc.nextLine();
try {
int mark = Integer.parseInt(grade);
if (mark >= 50 && mark <= 100) {
student[h][NAME] = name;
student[h][GRADE] = grade;
if (mark >= 75) {
student[h][REMARK] = "Passed";
totalp++;
}
else {
student[h][REMARK] = "Failed";
totalf++;
}
h++;
if (h == MAX_ROWS) {
System.out.println("Maximum students entered.");
}
else {
System.out.print("Add new record (Y/N)?: ");
String choice = sc.nextLine();
if (!"Y".equalsIgnoreCase(choice)) {
break;
}
}
}
else {
throw new NumberFormatException();
}
}
catch (NumberFormatException xNumberFormat) {
System.out.println("Invalid. Grade is a number between 50 and 100.");
}
System.out.println();
}
System.out.println("\nGRADE SUMMARY REPORT\n");
if (longest < 4) {
longest = 4;;
}
System.out.printf("%-" + longest + "s", "Name");
System.out.println(" Grade Remarks");
String format = "%-" + longest + "s %4s %s%n";
for (int i = 0; i < h; i++) {
System.out.printf(format, student[i][NAME], student[i][GRADE], student[i][REMARK]);
}
System.out.println();
System.out.println("Total passed: " + totalp);
System.out.println("Total failed: " + totalf);
}
}
Here is output from a sample run of the above code:
Enter Name: Superman
Enter Grade: 99
Add new record (Y/N)?: y
Enter Name: Batman
Enter Grade: 23
Invalid. Grade is a number between 50 and 100.
Enter Name: Iron Man
Enter Grade: 74
Add new record (Y/N)?: n
GRADE SUMMARY REPORT
Name Grade Remarks
Superman 99 Passed
Iron Man 74 Failed
Total passed: 1
Total failed: 1
You may also want to refer to the Exceptions lesson in Oracle's Java tutorials.
right now you are still printing the invalid grades in a line. what you want is to check and make sure the grade is valid before printing it. Since you made all the invalid grade an empty string, you can simply check for that like so
if(!student[i][h].isEmpty()){
System.out.print(student[i][h] + "\t");
}
I'm trying to compare the cost of a user's phone usage under plans from three
different providers. I can get as far as entering the usage details but once entered I try to call the method to rerun from the if statement but it just displays the main menu again and stops. I want it to run through the entire if statement from the start again
import java.util.Scanner;
public class MainMenuSelection {
public static int menuSel() {
int menuSel ;
System.out.println("ENTER USAGE DETAILS MENU\n");
System.out.println("Please select an option from the menu:");
System.out.println("1.Phone Call");
System.out.println("2.SMS ");
System.out.println("3.Data usage");
System.out.println("4. Return to main menu");
Scanner in = new Scanner(System.in);
System.out.println("Enter selection: ");
menuSel = in.nextInt();
while (menuSel < 1 || menuSel >4){
System.out.println("Value must bebetween 1 and 4, plese try again.");
System.out.println("Enter your selection: ");
menuSel = in.nextInt();
}
return menuSel;
}
public static int mainMenuSelection() {
System.out.println("MAIN MENU\n");
System.out.println("Please select from the menu:");
System.out.println("1. Enter Usage details");
System.out.println("2. Display Cost under provider 1");
System.out.println("3. Display Cost under provider 2");
System.out.println("4. Display Cost under provider 3");
System.out.println("5. Clear usage details");
System.out.println("6. Exit System");
int mainMenuSelection;
Scanner userInput = new Scanner(System.in);
System.out.println("Enter your selection: ");
mainMenuSelection = userInput.nextInt();
//return mainMenuSelection;
while (mainMenuSelection < 1 || mainMenuSelection >6){
System.out.println("Value must bebetween 1 and 6, plese try again.");
System.out.println("Enter your selection: ");
mainMenuSelection = userInput.nextInt();
}
System.out.println("You chose selection " + mainMenuSelection + "\n");
return mainMenuSelection;
}
public static void main(String[] args) {
System.out.println("Hello World!");
int callLength = 0;
int numSMS = 0;
int numberOfMB = 0;
int numberofCalls;
int callTime;
int totalcallTime = 0;
int mainMenuSelection = mainMenuSelection();
if (mainMenuSelection == 1) {
int menuSel = menuSel();
if (menuSel == 1) {
Scanner in = new Scanner(System.in);
System.out.println("Enter the number of phone call you have made? ");
numberofCalls = in.nextInt();
for (int i = 0; i < numberofCalls; i++) {
Scanner callInput = new Scanner(System.in);
System.out.println("How long was the call in seconds?");
callTime = callInput.nextInt();
totalcallTime = callTime + totalcallTime;
}
System.out.println("Your total number of calls is " + numberofCalls);
System.out.println("Your total call time is " + totalcallTime + " seconds" + "\n");
} else if (menuSel == 2) {
System.out.println("Enter the number of SMS messages: ");
//int numSMS;
Scanner userNumSMS = new Scanner(System.in);
numSMS = userNumSMS.nextInt();
System.out.println("Your number of SMSs is " + numSMS + "\n");
} else if (menuSel == 3) {
System.out.println("Enter the amount of data in MB: ");
//int numberOfMB;
Scanner userNumMB = new Scanner(System.in);
numberOfMB = userNumMB.nextInt();
System.out.println("Your amount of data in MB is " + numberOfMB + "\n");
} else {
mainMenuSelection(); // go back to main menu
}
} else if (mainMenuSelection == 2) {
//Display cost under provider 1
double callCost = 0.03 * totalcallTime;
double smsCost = 0.10 * numSMS;
double dataCost = 0.02 * numberOfMB;
double totalCostProvider1 = callCost + smsCost + dataCost;
System.out.println(totalCostProvider1);
} else if (mainMenuSelection == 3) {
//Display cost under provider 2
double callCost2 = 0.04 * totalcallTime;
double smsCost2 = 0.12 * numSMS;
double dataCost2 = 0.04 * numberOfMB;
double totalCostProvider2 = callCost2 + smsCost2 + dataCost2;
System.out.println(totalCostProvider2);
} else if (mainMenuSelection == 4) {
//Display cost under provider 3
double callCost3 = 0.05 * totalcallTime;
double smsCost3 = 0.11 * numSMS;
double dataCost3 = 0.03 * numberOfMB;
double totalCostProvider3 = callCost3 + smsCost3 + dataCost3;
System.out.println(totalCostProvider3);
} else if (mainMenuSelection == 5) {
//clear usage details
} else {
System.out.println("Exiting System");
System.exit(0);
}
mainMenuSelection = mainMenuSelection();
}
}
Codes run from top to bottom. Therefore, after the int mainMenuSelection = mainMenuSelection(); and the if-else statement is run, the code would run once again for the mainMenuSelection = mainMenuSelection() and ends, as there is nothing left in the block.
A fairly simple solution would be using a while or do-while loop with a boolean checking if the user entered the number 6 to exit the system.
You can try this example:
public static void main(String[] args) {
/*
* Your variables here
*/
boolean isExit = false;
while(!isExit) {
int mainMenuSelection = mainMenuSelection();
if (mainMenuSelection == 1) {
// menuSel codes here
} else if (mainMenuSelection == 2) {
// Display cost under provider 1
} else if (mainMenuSelection == 3) {
// Display cost under provider 2
} else if (mainMenuSelection == 4) {
// Display cost under provider 3
} else if (mainMenuSelection == 5) {
// Clear usage details
} else {
System.out.println("Exiting System");
isExit = true;
}
}
Hopes this answer helps you well.
It looks like you need a loop. Your main method has an exit condition so you can essentially loop forever by wrapping the code in your main method with a while loop:
public static void main(String[] args) {
while(true) {
// your main method code in here
}
}
By the way, you need to edit your code above in good formatting.
I have added a while loop in your main. Also, whenever any unwanted number the loop will exit using a break; and that in turn stops the program.
mainMenuSelection = mainMenuSelection();
I have deleted the above line from the code so you just need to call it once at the beginning of the code.
Let me know if you need sth else!
import java.util.Scanner;
public class MainMenuSelection {
public static int menuSel() {
int menuSel;
System.out.println("ENTER USAGE DETAILS MENU\n");
System.out.println("Please select an option from the menu:");
System.out.println("1.Phone Call");
System.out.println("2.SMS ");
System.out.println("3.Data usage");
System.out.println("4. Return to main menu");
Scanner in = new Scanner(System.in);
System.out.println("Enter selection: ");
menuSel = in.nextInt();
while (menuSel < 1 || menuSel > 4) {
System.out.println("Value must bebetween 1 and 4, plese try again.");
System.out.println("Enter your selection: ");
menuSel = in.nextInt();
}
return menuSel;
}
public static int mainMenuSelection() {
System.out.println("MAIN MENU\n");
System.out.println("Please select from the menu:");
System.out.println("1. Enter Usage details");
System.out.println("2. Display Cost under provider 1");
System.out.println("3. Display Cost under provider 2");
System.out.println("4. Display Cost under provider 3");
System.out.println("5. Clear usage details");
System.out.println("6. Exit System");
int mainMenuSelection;
Scanner userInput = new Scanner(System.in);
System.out.println("Enter your selection: ");
mainMenuSelection = userInput.nextInt();
//return mainMenuSelection;
while (mainMenuSelection < 1 || mainMenuSelection > 6) {
System.out.println("Value must bebetween 1 and 6, plese try again.");
System.out.println("Enter your selection: ");
mainMenuSelection = userInput.nextInt();
}
System.out.println("You chose selection " + mainMenuSelection + "\n");
return mainMenuSelection;
}
public static void main(String[] args) {
int callLength = 0;
int numSMS = 0;
int numberOfMB = 0;
int numberofCalls;
int callTime;
int totalcallTime = 0;
while (true) {
int mainMenuSelection = mainMenuSelection();
if (mainMenuSelection == 1) {
int menuSel = menuSel();
if (menuSel == 1) {
Scanner in = new Scanner(System.in);
System.out.println("Enter the number of phone call you have made? ");
numberofCalls = in.nextInt();
for (int i = 0; i < numberofCalls; i++) {
Scanner callInput = new Scanner(System.in);
System.out.println("How long was the call in seconds?");
callTime = callInput.nextInt();
totalcallTime = callTime + totalcallTime;
}
System.out.println("Your total number of calls is " + numberofCalls);
System.out.println("Your total call time is " + totalcallTime + " seconds" + "\n");
} else if (menuSel == 2) {
System.out.println("Enter the number of SMS messages: ");
//int numSMS;
Scanner userNumSMS = new Scanner(System.in);
numSMS = userNumSMS.nextInt();
System.out.println("Your number of SMSs is " + numSMS + "\n");
} else if (menuSel == 3) {
System.out.println("Enter the amount of data in MB: ");
//int numberOfMB;
Scanner userNumMB = new Scanner(System.in);
numberOfMB = userNumMB.nextInt();
System.out.println("Your amount of data in MB is " + numberOfMB + "\n");
}
} else if (mainMenuSelection == 2) {
//Display cost under provider 1
double callCost = 0.03 * totalcallTime;
double smsCost = 0.10 * numSMS;
double dataCost = 0.02 * numberOfMB;
double totalCostProvider1 = callCost + smsCost + dataCost;
System.out.println(totalCostProvider1);
} else if (mainMenuSelection == 3) {
//Display cost under provider 2
double callCost2 = 0.04 * totalcallTime;
double smsCost2 = 0.12 * numSMS;
double dataCost2 = 0.04 * numberOfMB;
double totalCostProvider2 = callCost2 + smsCost2 + dataCost2;
System.out.println(totalCostProvider2);
} else if (mainMenuSelection == 4) {
//Display cost under provider 3
double callCost3 = 0.05 * totalcallTime;
double smsCost3 = 0.11 * numSMS;
double dataCost3 = 0.03 * numberOfMB;
double totalCostProvider3 = callCost3 + smsCost3 + dataCost3;
System.out.println(totalCostProvider3);
} else if (mainMenuSelection == 5) {
//clear usage details
} else {
System.out.println("Exiting System");
System.exit(0);
break;
}
}
}
}
I created a program that will add, view, update and delete student arrays. To prevent user from entering duplicate ID number, I used the following code:
public static void addStud() {
int numID, year;
String userName, course;
int addMore;
do {
System.out.println("1. Enter Student ID: ");
numID = sc.nextInt();
sc.nextLine();
for(int x = 0; x < count; x++){
if(numID == stud[x].getNumID()) {
System.out.println("The Student ID: " +numID+ " already exist.\nEnter New Student ID: ");
numID = sc.nextInt();
sc.nextLine();
x = 0;
}
}
System.out.println("2. Enter Student Name");
userName = sc.nextLine();
System.out.println("3. Enter Student Course");
course = sc.nextLine();
System.out.println("4. Enter Student Year");
year = sc.nextInt();
stud[count] = new Student(numID, year, userName, course);
++count;
System.out.println("To add another Student Record Press 1 [any] number to stop");
addMore = sc.nextInt();
sc.nextLine();
} while (addMore == 1);
}
However, by inputting ID numbers 1-5 (again and again) for some reason the program accepts the duplicate ID [1]. What I, did is i change the if(numID == stud[x].getNumID()) to while(numID == stud[x].getNumID()) and it fix my problem.
I'm not good with debugging, I just want to know what went wrong? Why it works with while and not with if?
Bellow is my full program. Try to input ID numbers 1 - 5 and repeat it will accept the duplicate if used the IF statement.
import java.util.Scanner;
public class StudentArray {
static Scanner sc = new Scanner(System.in);
static Student[] stud = new Student[100];
static int count = 0;
public static void main(String[] args) {
while (true) {
int select;
System.out.println("1. Add Student Record");
System.out.println("2. View Student Record");
System.out.println("3. Update Student Record");
System.out.println("4. Delete Student Record");
System.out.println("0. Exit");
select = sc.nextInt();
switch (select) {
case 1:
addStud();
break;
case 2:
viewStud();
break;
case 3:
updateStud();
break;
case 4:
deleteStud();
break;
case 0:
return;
default:
System.out.println("Invalid Option");
}
}
}
public static void addStud() {
int numID, year;
String userName, course;
int addMore;
do {
System.out.println("1. Enter Student ID: ");
numID = sc.nextInt();
sc.nextLine();
for(int x = 0; x < count; x++){
if(numID == stud[x].getNumID()) { // change if to while prevents duplicate
System.out.println("The Student ID: " +numID+ " already exist.\nEnter New Student ID: ");
numID = sc.nextInt();
sc.nextLine();
x = 0;
}
}
System.out.println("2. Enter Student Name");
userName = sc.nextLine();
System.out.println("3. Enter Student Course");
course = sc.nextLine();
System.out.println("4. Enter Student Year");
year = sc.nextInt();
stud[count] = new Student(numID, year, userName, course);
++count;
System.out.println("To add another Student Record Press 1 [any] number to stop");
addMore = sc.nextInt();
sc.nextLine();
} while (addMore == 1);
}
public static void viewStud() {
while(true) {
int select;
System.out.println("1. View Record by ID number ");
System.out.println("2. View Record by Course ");
System.out.println("3. View Record by Course and Year ");
System.out.println("4. View All ");
System.out.println("0. Return Main Menu ");
select = sc.nextInt();
sc.nextLine();
switch (select) {
case 1:
int view1;
System.out.println("Please enter Student ID Number: ");
view1 = sc.nextInt();
viewArray(view1);
break;
case 2:
String view2;
System.out.println("Please enter Student Course: ");
view2 = sc.nextLine();
viewArray(view2);
break;
case 3:
String view3;
int view4;
System.out.println("Please enter Student Course: ");
view3 = sc.nextLine();
System.out.println("Please enter Student Year: ");
view4 = sc.nextInt();
viewArray(view3, view4);
break;
case 4:
viewArray();
break;
case 0:
return;
default:
System.out.println("Invalid Option");
}
}
}
public static void viewArray(){
System.out.println("Student ID\tStudent Name\tStudent Course\tStudent Year");
for (Student student : stud) {
if (student != null) {
System.out.println(student.getNumID()+"\t\t\t\t"+student.getUserName()+ "\t\t\t\t"+student.getCourse()+"\t\t\t\t"+ student.getYear());
}
}
}
public static void viewArray(int key){
boolean isExist = false;
int temp = 0;
for(int x = 0; x < count; ++x){
if(key == stud[x].getNumID()){
temp = x;
isExist = true;
break;
}
}
if(isExist){
System.out.println("1. Student ID: " + stud[temp].getNumID());
System.out.println("2. Student Name: " + stud[temp].getUserName());
System.out.println("3. Student Course: " + stud[temp].getCourse());
System.out.println("4. Student Year: " + stud[temp].getYear() +"\n");
}
else
System.out.println("The Student ID: " +key+ " is invalid");
}
public static void viewArray(String key){
boolean isExist = false;
for(int x = 0; x < count; ++x){
if(key.equalsIgnoreCase(stud[x].getCourse())){
System.out.println("1. Student ID: " + stud[x].getNumID());
System.out.println("2. Student Name: " + stud[x].getUserName());
System.out.println("3. Student Course: " + stud[x].getCourse());
System.out.println("4. Student Year: " + stud[x].getYear() +"\n");
isExist = true;
}
}
if(isExist == false){
System.out.println("The Student Course: " +key+ " is invalid");
}
}
public static void viewArray(String course, int year){
boolean isExist = false;
for(int x = 0; x < count; ++x){
if(course.equalsIgnoreCase(stud[x].getCourse()) && year == stud[x].getYear()){
System.out.println("1. Student ID: " + stud[x].getNumID());
System.out.println("2. Student Name: " + stud[x].getUserName());
System.out.println("3. Student Course: " + stud[x].getCourse());
System.out.println("4. Student Year: " + stud[x].getYear() +"\n");
isExist = true;
}
}
if(isExist == false){
System.out.println("The Student Course: " +course+ " and Year: "+year+" is invalid");
}
}
public static void updateStud(){
int numID, temp = 0;
boolean flag = false;
System.out.println("Student ID\tStudent Name\tStudent Course\tStudent Year");
for (Student student : stud) {
if (student != null) {
System.out.println(student.getNumID()+"\t\t\t\t"+student.getUserName()+ "\t\t\t\t"+student.getCourse()+"\t\t\t\t"+ student.getYear());
}
}
System.out.println("Enter Student ID to update: ");
numID = sc.nextInt();
sc.nextLine();
for(int x = 0; x < count && flag == false; x++){
if (numID == stud[x].getNumID()){
temp = x;
flag = true;
}
}
if(flag) {
System.out.println("Enter Student Name: ");
stud[temp].setUserName(sc.nextLine());
System.out.println("Enter Student Course");
stud[temp].setCourse(sc.nextLine());
System.out.println("Enter Student Year");
stud[temp].setYear(sc.nextInt());
System.out.println("The Student ID: " + numID + " record has been updated");
}
else
System.out.println("The Student ID: " +numID+ " is invalid");
}
public static void deleteStud() {
int numID, temp = 0;
boolean flag = false;
if (count > 0){ // check if array is empty
System.out.println("Student ID\tStudent Name\tStudent Course\tStudent Year");
for (Student student : stud) {
if (student != null) {
System.out.println(student.getNumID()+"\t\t\t\t"+student.getUserName()+ "\t\t\t\t"+student.getCourse()+"\t\t\t\t"+ student.getYear());
}
}
System.out.println("Enter Student ID to delete: ");
numID = sc.nextInt();
sc.nextLine();
for(int x = 0; x < count && flag == false; x++){
if (numID == stud[x].getNumID()){
temp = x; // get the index
flag = true; // stops the loop if id is found
}
}
for( ; temp < count -1; temp++){
stud[temp]=stud[temp+1];
}
stud[count-1] = null;
--count;
}
else {
System.out.println("Cannot delete [Array is Empty]");
}
}
}
My Student class:
public class Student {
private int numID, year;
private String userName, course;
public Student(int numID, int year, String userName, String course) {
this.numID = numID;
this.year = year;
this.userName = userName;
this.course = course;
}
public int getNumID() {
return numID;
}
public void setNumID(int numID) {
this.numID = numID;
}
public int getYear() {
return year;
}
public void setYear(int year) {
this.year = year;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getCourse() {
return course;
}
public void setCourse(String course) {
this.course = course;
}
}
You don't need the while loop, if you fix the issue with your for loop. Suppose you entered user IDs 1 to 5, and then entered 1 again. The first iteration of the for loop will find that 1 == stud[0].getNumID(), so you will ask for new student ID. Then you'll get a new input and reset x to 0.
Now, x will be incremented to 1 by the x++ part of the loop, so if you entered 1 again, the loop will never compare 1 to stud[0].getNumID(), since x==1. Therefore the duplicate input will be accepted.
This can be fixed by resetting x to -1:
for(int x = 0; x < count; x++){
if(numID == stud[x].getNumID()) {
System.out.println("The Student ID: " +numID+ " already exist.\nEnter New Student ID: ");
numID = sc.nextInt();
sc.nextLine();
x = -1;
}
}
Of course there are much better ways to check for duplicate IDs (that would be more readable and more efficient). Use a HashSet<Integer> to store all the used IDs, and use the Set to check if a new ID has already been used.
For example:
System.out.println("1. Enter Student ID: ");
numID = sc.nextInt();
sc.nextLine();
Set<Integer> ids = new HashSet<>();
while (!ids.add(numID)) { // add returns false if numID is already in the Set
System.out.println("The Student ID: " +numID+ " already exist.\nEnter New Student ID: ");
numID = sc.nextInt();
sc.nextLine();
}
...
I am trying to take user input for name, last name, phone number and age.
For some odd reason the scanner is skipping name but none of the other variables.
Can someone point out my mistake please? I can't figure it out.
import java.util.Scanner;
public class Lab2{
String [][] info = new String [10][4];
public static void main(String [] args){
new Lab2();
}
public Lab2(){
Scanner input = new Scanner(System.in);
System.out.println();
System.out.println("Student contact Interface");
System.out.println("Please select a number from the options below:");
while(true){
System.out.println("1: Add a new contact.");
System.out.println("2: Remove an existing contact.");
System.out.println("3: Display the contact list.");
System.out.println("0: Exit the contact list.");
int options = input.nextInt();
String name, lastName, number, age;
switch(options){
case 1:
System.out.println("Please enter the name: ");
name = input.nextLine(); // This is the String var that is not accepting input from...
System.out.println("Please enter the last name: ");
lastName = input.nextLine();
System.out.println("Please enter the phone number: ");
number = input.nextLine();
System.out.println("Please enter the age (eg. 25): ");
age = input.nextLine();
addStudent(name, lastName, number, age);
break;
case 2:
System.out.println("\nEnter the name to remove: ");
String delName = input.nextLine();
System.out.println("\nEnter the last name to remove: ");
String delLastName = input.nextLine();
remove(delName, delLastName);
break;
case 3:
display();
break;
case 0:
System.out.println("Thank you for using the contact Database.");
System.exit(0);
}
}
}
public void addStudent (String name, String lastName, String number, String age){
boolean infoInserted = false;
for(int i = 0; i < 10; i++){
if(info[i][0] == null || info[i][0].equals(null)){
info[i][0] = name;
info[i][1] = lastName;
info[i][2] = number;
info[i][3] = age;
infoInserted = true;
break;
}
}
if(infoInserted){
System.out.println("\nContact saved.\n");
}
else{
System.out.println("\nYour database is full.\n");
}
}
public void remove(String delName, String delLastName){
boolean removed = false;
int i = 0;
for (i = 0; i < 10; i++) {
if (info[i][0] != null && !info[i][0].equals(null)) {
if (info[i][0].equals(delName) && info[i][1].equals(delLastName)) {
while (i < 9) {
info[i][0] = info[i + 1][0];
info[i][1] = info[i + 1][1];
info[i][2] = info[i + 1][2];
info[i][3] = info[i + 1][3];
i++;
}
info[9][0] = null;
info[9][1] = null;
info[9][2] = null;
info[9][3] = null;
removed = true;
break;
}
}
}
if (removed) {
System.out.println("Contact removed.");
}
else {
System.out.println("Contact was not found.");
}
}
public void display (){
for (int i = 0; i < 10; i++) {
if (info[i][0] != null && !info[i][0].equals(null)) {
System.out.println("Contact " + (i + 1)+ ":");
System.out.println("\t" + info[i][0]);
System.out.println("\t" + info[i][1]);
System.out.println("\tPhone Number:" + info[i][2]);
System.out.println("\tAge:" + info[i][3]);
}
}
}
}
Add a
input.nextLine();
after your
int options = input.nextInt();
This is because:
nextInt method does not read the last newline character (of your integer input)
that newline is consumed in the next call to nextLine
causing name 'to be skipped'
so you need to 'flush away' the newline character after getting the integer input
Another option:
Take in the entire line, using input.nextLine()
Get the integer value using Integer.parseInt() to extract the integer value
It is skipping name because , input.nextInt() wont go to next input line.
You can use
int option=Integer.parseInt(input.nextLine());
then it wont skip name.
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 8 years ago.
I am creating a tester class for a simple input database program. I do not have to store information nor delete anything, but there are two arrays in my the class I am running my tester class for.
This is my tester class:
import java.util.Scanner;
public class Asst_3 {
private static Scanner keyboard;
public Asst_3(){
this.keyboard = new Scanner(System.in);
}
public static void main(String[]args){
Policy insurance = new Policy();
insurance.setCustomerLast(null);
insurance.setCustomerFirst(null);
insurance.setPolicyNumber();
insurance.setAge();
insurance.setAccidentNumber();
insurance.setPremiumDueDate(00,00,0000);
//insurance.toString();
System.out.println("Welcome to Drive-Rite Insurance Company");
showMenuOptions();
Scanner keyboard = new Scanner(System.in);
int choice = keyboard.nextInt();
intiateMenuSelection(choice);
}
private static void intiateMenuSelection(int selectedOption) {
switch (selectedOption){
case 1: newPolicy(null);
break;
case 2: returnFromAge();
break;
case 3: returnFromDue();
break;
case 4: System.out.println("Goodbye");
System.exit(0);
break;
default: break;
}
}
private static void newPolicy(Policy insurance) {
System.out.println("Enter Customer's Policy Number: ");
int poliNum = keyboard.nextInt();
insurance.getPolicyNumber();
System.out.println("Customer's Policy Number is: " + keyboard.nextInt());
System.out.println("Enter Customer's Last Name: ");
String custLast = keyboard.nextLine();
insurance.getCustomerLast();
System.out.println("Customer's Last Name is: " + keyboard.nextInt());
System.out.println("Enter Customer's First Name: ");
String custFirst = keyboard.nextLine();
insurance.getCustomerFirst();
System.out.println("Customer's First Name is: " + keyboard.nextInt());
System.out.println("Enter Customer's Age: ");
int custAge = keyboard.nextInt();
insurance.getAge();
System.out.println("Customer's Age is: " + keyboard.nextInt());
System.out.println("Enter Customer's Amount of Previous Accident Reaports in Past 3 years: ");
int custAccident = keyboard.nextInt();
insurance.getAccidentNumber();
System.out.println("Customer's Amount of Accidents is: " + keyboard.nextInt());
System.out.println("Enter Customer's next Premium Due Date: ");
int dueDate = keyboard.nextInt();
insurance.getPremiumDueDate();
System.out.println("Customer's Next Due Date is: " + keyboard.nextInt());
insurance.toString();
showMenuOptions();
}
private static void returnFromDue() {
showMenuOptions();
}
private static void returnFromAge() {
showMenuOptions();
}
private static void returnToMenu() {
intiateMenuSelection(0);
}
private static void showMenuOptions() {
System.out.println("Choose a menu option: ");
System.out.println("(1) Create New Policies");
System.out.println("(2) Search by age");
System.out.println("(3) Search by due date");
System.out.println("(4) Exit");
System.out.print("Input Option Number ---> ");
}
}
And the Null Pointer Error:
Exception in thread "main" java.lang.NullPointerException
at Asst_3.newPolicy(Asst_3.java:55)
at Asst_3.intiateMenuSelection(Asst_3.java:40)
at Asst_3.main(Asst_3.java:35)
This is the class I'm making my tester for:
import java.util.*;
public class Policy {
private int policyNumber;
private int age;
private int accidentNumber;
private String customerLast;
private String customerFirst;
private int [] months;
private int [] premiumDueDate;
public Policy() {
this.policyNumber = 0;
this.age = 0;
this.accidentNumber = 0;
this.customerLast = "";
this.customerFirst = "";
this.premiumDueDate = new int [3];
this.premiumDueDate[0] = 0;
this.premiumDueDate[1] = 0;
this.premiumDueDate[2] = 0;
this.months = new int [12];
this.months[0] = this.months[2] = this.months[4] = this.months[6] = this.months[7] = this.months[9] = this.months[11] = 31;
this.months[1] = 28;
this.months[3] = this.months[5] = this.months[8] = this.months[10] = 30;
}
public int getPolicyNumber(){
return this.policyNumber;
}
public void setPolicyNumber(){
if(policyNumber < 1000){
policyNumber = 0;
}
if(policyNumber > 9999){
policyNumber = 0;
}
}
public int[] getPremiumDueDate(){
return this.premiumDueDate;
}
public void setPremiumDueDate(int month, int day, int year){
this.premiumDueDate[0] = month;
this.premiumDueDate[1] = day;
this.premiumDueDate[2] = year;
if(month < 0||month >= 12)
{
this.premiumDueDate[0] = 0;
this.premiumDueDate[1] = 0;
this.premiumDueDate[2] = 0;
}
else if(day < 0 || day > this.months[month])
{
this.premiumDueDate[0] = 0;
this.premiumDueDate[1] = 0;
this.premiumDueDate[2] = 0;
}
}
public int getAge(){
return this.age;
}
public void setAge(){
this.age = 0;
}
public int getAccidentNumber(){
return this.accidentNumber;
}
public void setAccidentNumber(){
this.accidentNumber = 0;
}
public String getCustomerLast(){
return this.customerLast;
}
public void setCustomerLast(String customerLast){
this.customerLast = customerLast;
}
public String getCustomerFirst(){
return this.customerFirst;
}
public void setCustomerFirst(String customerFirst){
this.customerFirst = customerFirst;
}
public String toString(){
return "\n Policy Number: " + this.policyNumber + "\n Customer Last Name: " + this.customerLast + "\n Customer First Name: " + this.customerFirst
+ "\n Customer age: " + this.age + "\n Number of Accidents in Past Three Years: " + this.accidentNumber + "\n Premium Due Date: " + this.premiumDueDate;
}
}
Thank you everyone, your amazing!
Here's my edited code:
The Tester
import java.util.Scanner;
public class Asst_3 {
private static Scanner keyboard;
public Asst_3(){
this.keyboard = new Scanner(System.in);
}
public static void main(String[]args){
System.out.println("Welcome to Drive-Rite Insurance Company");
showMenuOptions();
int choice = keyboard.nextInt();
intiateMenuSelection(choice);
}
private static void intiateMenuSelection(int selectedOption) {
switch (selectedOption){
case 1: newPolicy(new Policy());
break;
case 2: returnFromAge();
break;
case 3: returnFromDue();
break;
case 4: System.out.println("Goodbye");
System.exit(0);
break;
default: break;
}
}
private static void newPolicy(Policy insurance) {
System.out.println("Enter Customer's Policy Number: ");
int poliNum = keyboard.nextInt();
insurance.setPolicyNumber(poliNum);
System.out.println("Customer's Policy Number is: " + insurance.getPolicyNumber());
System.out.println("Enter Customer's Last Name: ");
String custLast = keyboard.nextLine();
insurance.setCustomerLast(custLast);
System.out.println("Customer's Last Name is: " + insurance.getCustomerLast());
System.out.println("Enter Customer's First Name: ");
String custFirst = keyboard.nextLine();
insurance.setCustomerFirst(custFirst);
System.out.println("Customer's First Name is: " + insurance.getCustomerFirst());
System.out.println("Enter Customer's Age: ");
int custAge = keyboard.nextInt();
insurance.setAge(custAge);
System.out.println("Customer's Age is: " + insurance.getAge());
System.out.println("Enter Customer's Amount of Previous Accident Reaports in Past 3 years: ");
int custAccident = keyboard.nextInt();
insurance.setAccidentNumber(custAccident);
System.out.println("Customer's Amount of Accidents is: " + insurance.getAccidentNumber());
System.out.println("Enter Customer's next Premium Due Date: ");
int dueDate = keyboard.nextInt();
insurance.setPremiumDueDate(dueDate, dueDate, dueDate);
System.out.println("Customer's Next Due Date is: " + insurance.getPremiumDueDate());
insurance.toString();
returnToMenu();
}
private static void returnFromDue() {
showMenuOptions();
}
private static void returnFromAge() {
showMenuOptions();
}
private static void returnToMenu() {
intiateMenuSelection(0);
}
private static void showMenuOptions() {
System.out.println("Choose a menu option: ");
System.out.println("(1) Create New Policies");
System.out.println("(2) Search by age");
System.out.println("(3) Search by due date");
System.out.println("(4) Exit");
System.out.print("Input Option Number ---> ");
}
}
And the class being tested:
import java.util.*;
public class Policy {
private int policyNumber;
private int age;
private int accidentNumber;
private String customerLast;
private String customerFirst;
private int [] months;
private int [] premiumDueDate;
public Policy() {
this.policyNumber = 0;
this.age = 0;
this.accidentNumber = 0;
this.customerLast = "";
this.customerFirst = "";
this.premiumDueDate = new int [3];
this.premiumDueDate[0] = 0;
this.premiumDueDate[1] = 0;
this.premiumDueDate[2] = 0;
this.months = new int [12];
this.months[0] = this.months[2] = this.months[4] = this.months[6] = this.months[7] = this.months[9] = this.months[11] = 31;
this.months[1] = 28;
this.months[3] = this.months[5] = this.months[8] = this.months[10] = 30;
}
public int getPolicyNumber(){
return this.policyNumber;
}
public void setPolicyNumber(int policyNumber){
if(policyNumber < 1000){
policyNumber = 0;
}
if(policyNumber > 9999){
policyNumber = 0;
}
}
public int[] getPremiumDueDate(){
return this.premiumDueDate;
}
public void setPremiumDueDate(int month, int day, int year){
this.premiumDueDate[0] = month;
this.premiumDueDate[1] = day;
this.premiumDueDate[2] = year;
if(month < 0||month >= 12)
{
this.premiumDueDate[0] = 0;
this.premiumDueDate[1] = 0;
this.premiumDueDate[2] = 0;
}
else if(day < 0 || day > this.months[month])
{
this.premiumDueDate[0] = 0;
this.premiumDueDate[1] = 0;
this.premiumDueDate[2] = 0;
}
}
public int getAge(){
return this.age;
}
public void setAge(int age){
this.age = 0;
}
public int getAccidentNumber(){
return this.accidentNumber;
}
public void setAccidentNumber(int accidentNumber){
this.accidentNumber = 0;
}
public String getCustomerLast(){
return this.customerLast;
}
public void setCustomerLast(String customerLast){
this.customerLast = customerLast;
}
public String getCustomerFirst(){
return this.customerFirst;
}
public void setCustomerFirst(String customerFirst){
this.customerFirst = customerFirst;
}
public String toString(){
return "\n Policy Number: " + this.policyNumber + "\n Customer Last Name: " + this.customerLast + "\n Customer First Name: " + this.customerFirst
+ "\n Customer age: " + this.age + "\n Number of Accidents in Past Three Years: " + this.accidentNumber + "\n Premium Due Date: " + this.premiumDueDate;
}
}
But now I have a new error after executing the program:
Welcome to Drive-Rite Insurance Company
Choose a menu option:
(1) Create New Policies
(2) Search by age
(3) Search by due date
(4) Exit
Input Option Number ---> Exception in thread "main" java.lang.NullPointerException
at Asst_3.main(Asst_3.java:23)
Here's an updated version with that NPE fixed:
import java.util.Scanner;
public class Asst_3 {
private static Scanner keyboard;
public static void main(String[]args){
System.out.println("Welcome to Drive-Rite Insurance Company");
showMenuOptions();
this.keyboard = new Scanner(System.in);
int choice = keyboard.nextInt();
intiateMenuSelection(choice);
}
private static void intiateMenuSelection(int selectedOption) {
switch (selectedOption){
case 1: newPolicy(new Policy());
break;
case 2: returnFromAge();
break;
case 3: returnFromDue();
break;
case 4: System.out.println("Goodbye");
System.exit(0);
break;
default: break;
}
}
private static void newPolicy(Policy insurance) {
System.out.println("Enter Customer's Policy Number: ");
int poliNum = keyboard.nextInt();
insurance.setPolicyNumber(poliNum);
System.out.println("Customer's Policy Number is: " + insurance.getPolicyNumber());
System.out.println("Enter Customer's Last Name: ");
String custLast = keyboard.nextLine();
insurance.setCustomerLast(custLast);
System.out.println("Customer's Last Name is: " + insurance.getCustomerLast());
System.out.println("Enter Customer's First Name: ");
String custFirst = keyboard.nextLine();
insurance.setCustomerFirst(custFirst);
System.out.println("Customer's First Name is: " + insurance.getCustomerFirst());
System.out.println("Enter Customer's Age: ");
int custAge = keyboard.nextInt();
insurance.setAge(custAge);
System.out.println("Customer's Age is: " + insurance.getAge());
System.out.println("Enter Customer's Amount of Previous Accident Reaports in Past 3 years: ");
int custAccident = keyboard.nextInt();
insurance.setAccidentNumber(custAccident);
System.out.println("Customer's Amount of Accidents is: " + insurance.getAccidentNumber());
System.out.println("Enter Customer's next Premium Due Date: ");
int dueDate = keyboard.nextInt();
insurance.setPremiumDueDate(dueDate, dueDate, dueDate);
System.out.println("Customer's Next Due Date is: " + insurance.getPremiumDueDate());
insurance.toString();
returnToMenu();
}
private static void returnFromDue() {
showMenuOptions();
}
private static void returnFromAge() {
showMenuOptions();
}
private static void returnToMenu() {
intiateMenuSelection(0);
}
private static void showMenuOptions() {
System.out.println("Choose a menu option: ");
System.out.println("----------------------------------------");
System.out.println("(1) Create New Policies");
System.out.println("(2) Search by age");
System.out.println("(3) Search by due date");
System.out.println("(4) Exit");
System.out.print("Input Option Number ---> ");
}
}
The errors are I'm having issues with they keyboard variables.
null pointer occurring in
private static void newPolicy(Policy insurance)
this method. For these lines
insurance.getPolicyNumber();
insurance.get....();
insurance.get....();
because the reference/object insurance coming as a parameter from where its being called . in you case you are passing null to the method
newPolicy(null); //try to pass a reference of Policy like 'newPolicy(new Policy())' .
You declare keybord twice.
remove the Scanner from this line:
Scanner keyboard = new Scanner(System.in);
So you have:
keyboard = new Scanner(System.in);
You're shadowing you variables, that is, you've declared keyboard as a class variable
public class Asst_3 {
private static Scanner keyboard;
But in the main, you've re-declared it as a local variable...
Scanner keyboard = new Scanner(System.in);
Which means that the class variable is still null when you call newPolicy.
Start by removing the re-declaration...
//Scanner keyboard = new Scanner(System.in);
keyboard = new Scanner(System.in);
Which will lead you smack bang into you next NullPointerException in newPolicy
insurance.getPolicyNumber();
Caused by the fact that you call the method passing it a null value...
newPolicy(null);
I'll leave you to fix that ;)
Hint: newPolicy should take no parameters and should return an new instance of Policy which can then manipulated by the other methods ;)
The insurance that you are passing to newPolicy is null
case 1: newPolicy(null);
hence
insurance.getPolicyNumber();
will throw a NPE