i need help with my code. I am stuck at 2 (View student record), we only allowed to use arrays and not arraylist or linked list. Any advice and help will do.
Heres the instructions:
Write a menu driven program that performs the following:
1.Add record
- can add N students record into the list (ID num, name, course, year)
2.View record
- can view record by ID number, by course, by course and year
- or view all
3.Update record
- can edit/modify the records attribute excluding the ID
4.Delete
- can remove student record
Heres my code:
import java.util.Scanner;
public class StudentArray {
public static void main(String[] args){
getMenu();
}
public static void getMenu( ){
Student[] stud = new Student[100];
Scanner sc = new Scanner(System.in);
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(stud);
getMenu();
break;
case 2:
viewStud(stud);
getMenu();
break;
case 3:
break;
case 4:
break;
case 0:
break;
default:
}
}
public static void addStud(Student[] stud){
Scanner sc = new Scanner(System.in);
int numID, year;
String userName, course;
int addMore;
int i = 0;
do{
System.out.println("1. Enter Student ID: ");
numID = sc.nextInt();
sc.nextLine();
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[i] = new Student(numID, year, userName, course);
++i;
System.out.println("To add another Student Record Press 1");
addMore = sc.nextInt();
}while (addMore == 1 );
}
public static void viewStud(Student[] stud){
for(int x = 0; x < stud.length ; ++x){
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");
}
}
}
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;
}
}
Hello thank you SNJ,
I remove my getMenu method and put the code in the main instead.But I'm unable to set the Student array and i to static
import java.util.Scanner;
public class StudentArray {
public static void main(String[] args) {
static Student[] stud = new Student[100];
static int i = 0;
Scanner sc = new Scanner(System.in);
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(stud);
break;
case 2:
viewStud(stud);
break;
case 3:
break;
case 4:
break;
case 0:
return;
default:
System.out.println("Invalid Option");
}
}
}
public static void addStud(Student[] stud) {
Scanner sc = new Scanner(System.in);
int numID, year;
String userName, course;
int addMore;
do {
System.out.println("1. Enter Student ID: ");
numID = sc.nextInt();
sc.nextLine();
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[i] = new Student(numID, year, userName, course);
++i;
System.out.println("To add another Student Record Press 1");
addMore = sc.nextInt();
} while (addMore == 1);
}
public static void viewStud(Student[] stud) {
for (Student element : stud) {
if (null != element) {
System.out.println("1. Student ID: " + element.getNumID());
System.out.println("2. Student Name: " + element.getUserName());
System.out.println("3. Student Course: " + element.getCourse());
System.out.println("4. Student Year: " + element.getYear() + "\n");
}
}
}
You are loosing student value in between method calls.If you make Student array and i as static, it will retain your values between method calls.
import java.util.Scanner;
public class StudentArray {
public static void main(String[] args){
static Student[] stud = new Student[100];
static int i = 0;
public static void main(String[] args) {
getMenu();
}
public static void getMenu() {
Scanner sc = new Scanner(System.in);
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(stud);
break;
case 2:
viewStud(stud);
break;
case 3:
break;
case 4:
break;
case 0:
return;
default:
System.out.println("Invalid Option");
}
}
}
public static void addStud(Student[] stud) {
Scanner sc = new Scanner(System.in);
int numID, year;
String userName, course;
int addMore;
do {
System.out.println("1. Enter Student ID: ");
numID = sc.nextInt();
sc.nextLine();
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[i] = new Student(numID, year, userName, course);
++i;
System.out.println("To add another Student Record Press 1");
addMore = sc.nextInt();
} while (addMore == 1);
}
public static void viewStud(Student[] stud) {
for (Student element : stud) {
if (null != element) {
System.out.println("1. Student ID: " + element.getNumID());
System.out.println("2. Student Name: " + element.getUserName());
System.out.println("3. Student Course: " + element.getCourse());
System.out.println("4. Student Year: " + element.getYear() + "\n");
}
}
}
Related
I need to create a functioning To-Do list in java that allows a user to:
Add an item
Delete an item
Show the list
Delete all tasks
Exit the program
I am currently having trouble adding an item to my list. Each time I enter an item to add this is the output I receive:
Exception in thread "main" java.util.InputMismatchException
at java.base/java.util.Scanner.throwFor(Scanner.java:939)
at java.base/java.util.Scanner.next(Scanner.java:1594)
at java.base/java.util.Scanner.nextInt(Scanner.java:2258)
at java.base/java.util.Scanner.nextInt(Scanner.java:2212)
at Test.menu(Test.java:50)
at Test.main(Test.java:11)
Here is what I have tried so far, any help would be greatly appreciated:
import java.util.Scanner;
import java.util.ArrayList;
public class Test {
public static void main(String[] args) {
int menuItem = -1;
while(menuItem !=0) {
menuItem = menu();
switch(menuItem) {
case 1:
showList();
break;
case 2:
addItem();
break;
case 3:
removeItem();
break;
case 0:
break;
default:
System.out.println("Enter a valid option");
}
}
}
public static int menu() {
int choice;
Scanner keyboard = new Scanner(System.in);
System.out.println("Main Menu");
System.out.println();
System.out.println("0. Exit the program");
System.out.println("1. Display to-do list");
System.out.println("2. Add item to list");
System.out.println("3. Remove item from list");
System.out.println();
System.out.print("Enter choice: ");
choice = keyboard.nextInt();
return choice;
}
public static void showList() {
System.out.println("To-Do List");
Scanner input = new Scanner(System.in);
String line;
int number = 1;
while (input.hasNextLine()){
line = input.nextLine();
System.out.println(number + " ");
System.out.println(line);
++number;
}
System.out.println();
}
public static void addItem() {
System.out.println("Add Item");
Scanner input = new Scanner(System.in);
System.out.println("Enter an item: ");
String item = input.nextLine();
System.out.println(item);
}
public static void removeItem() {
int choice;
showList();
Scanner input = new Scanner(System.in);
System.out.println("What do you want to remove?");
choice = input.nextInt();
ArrayList<String> items = new ArrayList<String>();
int number = 1;
Scanner input2 = new Scanner(System.in);
String item;
while (input2.hasNextLine()) {
item = input2.nextLine();
if (number != choice)
items.add(item);
++number;
}
for(int i = 0; i < items.size(); i++)
System.out.println(items.get(i));
}
}
You are missing the actual operation of adding removing from the list. #DrMe go through these program you can find where you'r doing wrong. I hope this can help you
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class TestToDoList {
private static List<String> currentList = new ArrayList<String>();
public static void main(String[] args) {
int menuItem = -1;
while (menuItem != 0) {
menuItem = menu();
switch (menuItem) {
case 1:
showList();
break;
case 2:
addItem();
break;
case 3:
removeItem();
break;
case 0:
break;
default:
System.out.println("Enter a valid option");
}
}
}
public static int menu() {
System.out.println();
System.out.println("----------------------");
System.out.println("Main Menu");
System.out.println("----------------------");
System.out.println("0. Exit the program");
System.out.println("1. Display to-do list");
System.out.println("2. Add item to list");
System.out.println("3. Remove item from list");
System.out.println();
System.out.print("Enter choice: ");
int choice = scanner.nextInt();
return choice;
}
public static void showList() {
System.out.println();
System.out.println("----------------------");
System.out.println("To-Do List");
System.out.println("----------------------");
int number = 0;
for (String item : currentList) {
System.out.println(++number + " " + item);
}
System.out.println("----------------------");
}
public static void addItem() {
System.out.println("Add Item");
System.out.println("----------------------");
System.out.print("Enter an item: ");
Scanner scanner = new Scanner(System.in);
String item = scanner.nextLine();
currentList.add(item);
showList();
}
public static void removeItem() {
System.out.println("Remove Item");
System.out.println("----------------------");
Scanner scanner = new Scanner(System.in);
System.out.print("What do you want to remove?");
int index = scanner.nextInt();
if((index-1)<0 || index>currentList.size()) {
System.out.println("Wrong index number! Please enter in range of 1 to "+currentList.size());
}else {
currentList.remove(index-1);
}
System.out.println("----------------------");
showList();
}
}
Further improve using generic and utils methods.
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();
}
...
public class LibraryMenu {
static Scanner input = new Scanner(System.in);
static Holding[]holding = new Holding[15];
static Member[]member = new Member[15];
static int hold = 0;
private static Scanner scanner;
public static void main(String[] args){
int options;
do{
scanner = new Scanner(System.in);
System.out.println();
System.out.println("Library Management System");
System.out.println("1. Add Holding");
System.out.println("2. Print All Holding");
options = scanner.nextInt();
switch(options){
case 1:
addHolding();
break;
case 2:
print();
break;
default:
System.out.println("Please");
}
}while(options != 3);
System.out.println("I'm out");
}
public static void addHolding(){
int options1;
do{
System.out.println();
System.out.println("1. Book");
System.out.println("2. Video");
System.out.println("3. Return");
options1 = input.nextInt();
switch(options1){
case 1:
addBook();
break;
case 2:
addVideo();
break;
default:
System.out.println("Please enter the following options");
}
}while(options1 != 3);
}
public static void addBook(){
System.out.println("Title: " + "\t");
String title = input.next();
System.out.println("ID: " + "\t");
String holdingId = input.next();
Book tempbook = new Book(title, holdingId);
holding[hold] = tempbook;
++hold;
}
public static void addVideo(){
System.out.println("Title: ");
String title = input.next();
System.out.println("ID: ");
String holdingId = input.next();
System.out.println("Loan Fee: ");
int loanFee = input.nextInt();
Video tempvideo = new Video(holdingId, title, loanFee);
holding[hold] = tempvideo;
++hold;
}
public static void print(){
for(int i = 0; i < holding.length; i++){
System.out.println(holding[i]);
}
}
}
When I use the print() method, nothing shows up. Wondering what is wrong with the code and why it is not printing out. Using user input to add books and video etc. Tried to look around the internet for this problem, but cant seem to find it.
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
Basically i have a hashmap and the search method is missing a keyboard.next which should allow the user to input the name they want to search for. There are no errors. The output does not allow an opportunity for the user to enter the name they want to search. The weird thing is i can use the userInput method and it works perfectly. Here is my code:
Store declaration
//Imports.
import java.util.Scanner;
//********************************************************************
public class MainApp
{
//The Scanner is declared here for use throughout the whole MainApp.
private static Scanner keyboard = new Scanner(System.in);
public static void main(String[] args)
{
new MainApp().start();
}
public void start()
{
//Create a Store named Store and add Employee's to the Store.
EmployeeStore Store = new EmployeeStore();
Store.add(new Employee ("James O' Carroll", 18,"hotmail.com"));
Store.add(new Employee ("Andy Carroll", 1171,"yahoo.com"));
Store.add(new Employee ("Luis Suarez", 7,"gmail.com"));
//********************************************************************
/*Test Code.
Store.searchByName("James O' Carroll");
Store.print();
Store.searchByEmail("gmail.com");
Employee andy = Store.searchByEmail("hotmail.com");
System.out.println(andy);
Employee employee = Store.searchByName("James O' Carroll");
if (employee != null)
{
employee.setEmployeeName("Joe");
employee.setEmployeeId(1);
employee.setEmployeeEmail("webmail.com");
Store.edit(employee);
Store.print();
}*/
//********************************************************************
int choice ;
System.out.println("Welcome to the Company Database.");
do
{
choice = MenuMethods.getMenuChoice(
"1.\tView All" +
"\n2.\tAdd" +
"\n3.\tDelete" +
"\n4.\tDelete All " +
"\n5.\tEdit" +
"\n6.\tSearch" +
"\n7.\tPrint"+
"\n8.\tExit", 8, "Please enter your choice:", "Error [1,8] Only");
//String temp = keyboard.nextLine(); This prevented entering the choice.
switch (choice)
{
case 1:
System.out.println("View All");
Store.print();
break;
case 2:
System.out.println("Add");
Employee employee = MenuMethods.userInput();
Store.add(employee);
break;
case 3:
System.out.println("Delete");
//Store.delete();
break;
case 4:
System.out.println("Delete All");
Store.clear();
break;
case 5:
System.out.println("Edit");
Employee employee2 = MenuMethods.userInput();
Store.searchByName(employee2.getEmployeeName());
if (employee2 != null)
{
employee2.setEmployeeName("Joe");
employee2.setEmployeeId(1);
employee2.setEmployeeEmail("webmail.com");
Store.edit(employee2);
Store.print();
}
break;
case 6:
System.out.println("Search");
Employee employee1 = MenuMethods.userInputByName();
Store.searchByName(employee1.getEmployeeName());
break;
case 7:
System.out.println("Print");
Store.print();
break;
case 8:
System.out.println("Exit");
break;
}
} while (choice != 8);
}
}
//Imports
import java.util.Scanner;
//********************************************************************
public class MenuMethods
{
private static Scanner keyboard = new Scanner(System.in);
//Methods for the Company Application menu.
//Method for validating the choice.
public static int getMenuChoice(String menuString, int limit, String prompt, String errorMessage)
{
System.out.println(menuString);
int choice = inputAndValidateInt(1, limit, prompt, errorMessage);
return choice;
}
//********************************************************************
//This method is used in the getMenuChoice method.
public static int inputAndValidateInt(int min, int max, String prompt, String errorMessage)
{
int number;
boolean valid;
do {
System.out.print(prompt);
number = keyboard.nextInt();
valid = number <= max && number >= min;
if (!valid) {
System.out.println(errorMessage);
}
} while (!valid);
return number;
}
//********************************************************************
public static Employee userInput()
{
String temp = keyboard.nextLine();
Employee e = null;
System.out.println("Please enter the Employee Name:");
String employeeName = keyboard.nextLine();
System.out.println("Please enter the Employee ID:");
int employeeId = keyboard.nextInt();
temp = keyboard.nextLine();
System.out.println("Please enter the Employee E-mail address:");
String employeeEmail = keyboard.nextLine();
return e = new Employee(employeeName , employeeId, employeeEmail);
}
//********************************************************************
public static Employee userInputByName()
{
Employee e = null;
System.out.println("Please enter the Employee Name:");
String employeeName = keyboard.nextLine();
System.out.println("Please enter the Employee Name:");
return e = new Employee(employeeName);
}
//********************************************************************
}
Search Method in the mainApp
case 6:
System.out.println("Search");
Employee employee1 = MenuMethods.userInputByName();
Store.searchByName(employee1.getEmployeeName());
break;
The actual Search method.
public Employee searchByName(String employeeName)
{
Employee employee = map.get(employeeName);
System.out.println(employee);
return employee;
}
//********************************************************************
The userInputByName method. This is where the problem seems to lie.
public static Employee userInput()
{
String temp = keyboard.nextLine();
Employee e = null;
System.out.println("Please enter the Employee Name:");
String employeeName = keyboard.nextLine();
System.out.println("Please enter the Employee ID:");
int employeeId = keyboard.nextInt();
temp = keyboard.nextLine();
System.out.println("Please enter the Employee E-mail address:");
String employeeEmail = keyboard.nextLine();
return e = new Employee(employeeName , employeeId, employeeEmail);
}
//********************************************************************
public static Employee userInputByName()
{
Employee e = null;
System.out.println("Please enter the Employee Name:");
String employeeName = keyboard.nextLine();
System.out.println("Please enter the Employee Name:");
return e = new Employee(employeeName);
}
//********************************************************************
Let me try my best.
First of all, why is there two println statements in your userInputByName()?
public static Employee userInputByName()
{
Employee e = null;
System.out.println("Please enter the Employee Name:");
String employeeName = keyboard.nextLine();
System.out.println("Please enter the Employee Name:"); //!???
return e = new Employee(employeeName);
}
Then, in the case 6, you just call the method searchByName and does not check if the search is successful or not. I suggest:
case 6:
System.out.println("Search");
Employee employee1 = MenuMethods.userInputByName();
Employee foundEmployee = Store.searchByName(employee1.getEmployeeName());
if (foundEmployee != null) {
System.out.println("Found employee!");
} else {
System.out.println("Not Found!");
}
break;