The program should contain the customers plus a list of the calories and the distance during the week.
My question is, how can I put together the customer's name and the distance?
public class TestCustomer {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
ArrayList<String> customersNames = new ArrayList<String>();
char userInput = ' ';
System.out.println("A to show all");
userInput = scan.next().charAt(0);
if(userInput == 'A') {
System.out.println("All results ");
for(int i = 0; i < customersNames.size(); i++) {
System.out.println(customersNames.get(i));
}
}
}
And here's my Customer class
public class Customer {
private String name;
private double calories;
private double distance;
public Customer(String name, double distance) {
this.name = name;
this.distance = distance;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setCalories(double calories) {
this.calories = calories;
}
public double getCalories() {
return calories;
}
public void setDistance(double distance) {
this.distance = distance;
}
public double getDistance() {
return distance;
}
}
This uses a list of customers instead of customernames.
I put the Customer class as static in the testclass for brevity(keep everything in one file). Better to have it seperate as you do.
Also I did not want to change the whole design or do a complete rewrite - it is your design. So this is only making it work, fixing the behavior to the one required.
Eg with having the customers in HashMap that is indexed by name one could retrieve a dataset more elegantly in O(1). But thats maybe another improvement.
This only has the list. So for simplicity I added an equals, that makes users equal if they have the same name.
I create a new User that can be searched in the list. If not found I add this user with the given input to the list.
If found I search for existing the user in the list with indexOf and retrieve that existing user. I do it in one step.
import java.util.ArrayList;
import java.util.Objects;
import java.util.Scanner;
public class TestCustomer {
public static class Customer {
private String name;
private double calories;
private double distance;
public Customer(String name, double calories, double distance) {
this.name = name;
this.calories = calories;
this.distance = distance;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setCalories(double calories) {
this.calories = calories;
}
public double getCalories() {
return calories;
}
public void setDistance(double distance) {
this.distance = distance;
}
public double getDistance() {
return this.distance;
}
#Override
public int hashCode() {
int hash = 5;
hash = 71 * hash + Objects.hashCode(this.name);
return hash;
}
#Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
return Objects.equals(this.name, ((Customer)obj).name);
}
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
ArrayList<Customer> customers = new ArrayList<>();
char userInput = ' ';
while (userInput != 'q') {
System.out.println("Press 'a' to show all customers or press 's' to search for customer ");
userInput = scan.next().charAt(0);
userInput = Character.toUpperCase(userInput);
if (userInput == 'A') {
System.out.println("Here's the list of all customers: ");
for (int i = 0; i < customers.size(); i++) {
System.out.println(customers.get(i).getName());
}
// here I should show the list of all customers and their data
} else if (userInput == 'S') {
System.out.println("You selected to search for a customer");
createCustomer(customers);
}
}
}
public static ArrayList<Customer> createCustomer(ArrayList<Customer> customers) {
Scanner scan2 = new Scanner(System.in);
System.out.println("Enter customer's first name: ");
String fName = scan2.next();
System.out.println("Enter customer's last name: ");
String lName = scan2.next();
String fullName = fName + " " + lName;
Customer newCustomer = new Customer(fullName,0,0);
if (customers.contains(newCustomer)) {
newCustomer=customers.get(customers.indexOf(newCustomer));
System.out.println("Customer already on the list. Here's the information: ");
System.out.println(fullName + " " + newCustomer.distance + " " + newCustomer.calories );
} else{
System.out.println("Customer not found. Would you like to create a new customer? y/n ");
char createUserPrompt = scan2.next().charAt(0);
if (createUserPrompt == 'y') {
String[] daysOfWeek = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"};
for (String daysOfWeek1 : daysOfWeek) {
System.out.println("Enter calories consumed on " + daysOfWeek1);
newCustomer.calories = scan2.nextDouble();
System.out.println("Enter distance walked on " + daysOfWeek1);
newCustomer.distance = scan2.nextDouble();
}
customers.add(newCustomer);
} else if (createUserPrompt == 'n') {
System.out.println("User will not be added.");
}
}
return customers;
}
}
sample run:
Press 'a' to show all customers or press 's' to search for customer
a
Here's the list of all customers:
Press 'a' to show all customers or press 's' to search for customer
s
You selected to search for a customer
Enter customer's first name:
kai
Enter customer's last name:
last
Customer not found. Would you like to create a new customer? y/n
y
Enter calories consumed on Monday
5
Enter distance walked on Monday
5
Enter calories consumed on Tuesday
5
Enter distance walked on Tuesday
5
Enter calories consumed on Wednesday
5
Enter distance walked on Wednesday
5
Enter calories consumed on Thursday
5
Enter distance walked on Thursday
5
Enter calories consumed on Friday
5
Enter distance walked on Friday
5
Enter calories consumed on Saturday
5
Enter distance walked on Saturday
5
Enter calories consumed on Sunday
5
Enter distance walked on Sunday
5
Press 'a' to show all customers or press 's' to search for customer
a
Here's the list of all customers:
kai last
Press 'a' to show all customers or press 's' to search for customer
s
You selected to search for a customer
Enter customer's first name:
kai
Enter customer's last name:
last
Customer already on the list. Here's the information:
kai last 5.0 5.0
Press 'a' to show all customers or press 's' to search for customer
With some modifications to your Customer class in which the calories and distance will be stored ad an array for each day,
An ArrayList<Customer> will be used to store the list of customers.
Possible solution:
import java.util.*;
public class Main {
private static Scanner scan;
private static ArrayList<Customer> customers;
public static Customer customerExists(String customerName) {
for (int i = 0; i < customers.size(); i++) {
if (customers.get(i).getName().equals(customerName)) {
return customers.get(i);
}
}
return null;
}
public static void addCustomer() {
System.out.println(">> Add Customer <<\n");
System.out.print("Enter customer's first name: ");
String fName = scan.nextLine();
System.out.print("Enter customer's last name: ");
String lName = scan.nextLine();
String fullName = fName + " " + lName;
Customer existingCustomer = customerExists(fullName);
if (existingCustomer != null) {
System.out.println("\nCustomer already on the list. Here's the information: ");
System.out.println("#\tName\t\tCalories [Mon-Sun]\t\t\t\t\t\tDistance [Mon-Sun]");
System.out.println(existingCustomer.getName() + "\t" + Arrays.toString(existingCustomer.getCalories()) + "\t" + Arrays.toString(existingCustomer.getDistance()));
return;
}
String[] daysOfWeek = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"};
double calories[] = new double[daysOfWeek.length];
double distance[] = new double[daysOfWeek.length];
for (int j = 0; j < daysOfWeek.length; j++) {
System.out.print("Enter calories consumed on " + daysOfWeek[j] + ": ");
calories[j] = scan.nextDouble();
System.out.print("Enter distance walked on " + daysOfWeek[j] + ": ");
distance[j] = scan.nextDouble();
}
Customer customer = new Customer(fullName, calories, distance);
customers.add(customer);
System.out.println("\nCustomer added successfully!\n");
}
public static void showCustomers() {
System.out.println(">> All Customers <<\n");
System.out.println("#\tName\t\tCalories [Mon-Sun]\t\t\t\t\t\tDistance [Mon-Sun]");
for (int i = 0; i < customers.size(); i++) {
System.out.println(i+1 + "\t" + customers.get(i).getName() + "\t" + Arrays.toString(customers.get(i).getCalories()) + "\t\t\t" + Arrays.toString(customers.get(i).getDistance()));
}
System.out.println("\n");
}
public static void searchCustomers() {
System.out.println(">> Search for a Customer <<\n");
System.out.print("Enter customer's full name: ");
String fullName = scan.nextLine();
Customer customer = customerExists(fullName);
System.out.println(fullName);
if (customer == null) {
System.out.println("\nNo such customer exists.\n");
return;
}
System.out.println("\nCustomer information:\n");
System.out.println("#\tName\t\tCalories [Mon-Sun]\t\t\t\t\t\tDistance [Mon-Sun]");
System.out.println(customer.getName() + "\t" + Arrays.toString(customer.getCalories()) + "\t" + Arrays.toString(customer.getDistance()) + "\n");
}
public static void main(String[] args) {
boolean cont = true;
int option = -1;
scan = new Scanner(System.in);
customers = new ArrayList<>();
do {
System.out.println("=== Select an Option ===");
System.out.println("1. Add a customer");
System.out.println("2. Show all customers");
System.out.println("3. Search for customer");
System.out.println("0. Exit");
System.out.print("\n > ");
try {
option = Integer.parseInt(scan.nextLine());
System.out.println("\n");
switch(option) {
case 1:
addCustomer();
break;
case 2:
showCustomers();
break;
case 3:
searchCustomers();
break;
case 0:
System.out.println("Good Bye!");
cont = false;
break;
default:
System.err.println("'" + option + "' is not a valid option. Please try again.\n");
break;
}
} catch (NumberFormatException e) {
System.err.println("Invalid option selected.\n");
}
} while (cont == true);
}
}
Related
I am learning Java. I just want to write a method that generates random numbers that comes in a specific set, like a bank credit card " xxxx - xxxx - xxxx - xxxx ". Each chunk needs to be exactly 4 digit long. anybody has any solution?
public class Main {
public static User accountHolders[] = new User[100];
public static int index = 0;
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
while (true) {
System.out.println("\t-----\tWelcome to The Bank portal\t-----");
System.out.println("\nPlease enter the number of your required action");
System.out.println("\n1) Make a Deposit");
System.out.println("2) Get balance");
System.out.println("3) Register new account");
System.out.println("0) Quit the portal");
int command = input.nextInt();
switch (command) {
case 1:
InputController.deposit();
break;
case 2:
InputController.balance();
break;
case 3:
User user = InputController.register();
accountHolders[index] = user;
index++;
break;
default:
System.out.println("Wrong input! please enter a number between 1 - 4!!!");
break;
}
}
}
}
public class Account {
private int uniID;
private int password;
private int balance;
private String cardNum;
public int getUniID() {
return uniID;
}
public int getPassword() {
return password;
}
public int getBalance() {
return balance;
}
public void makeDeposit(int amount) {
this.balance = this.balance + amount;
}
public Account(int password, int balance) {
this.password = password;
this.balance = balance;
Random rand = new Random();
this.uniID = rand.nextInt(100);
}
}
public class User {
private String name;
private Account account;
public String getName() {
return name;
}
public Account getAccount() {
return account;
}
public User(String name, Account account) {
this.name = name;
this.account = account;
}
}
public class InputController {
static Scanner input = new Scanner(System.in);
public static User register() {
System.out.print("Enter your name: ");
String name = input.next();
System.out.print("Enter your password: ");
int password = input.nextInt();
System.out.print("Please enter the amount of your initial deposit: ");
int balance = input.nextInt();
Account account = new Account(password, balance);
User user = new User(name, account);
System.out.print("Your account number is: " + account.getUniID());
return user;
}
public static void balance() {
int index = findAccount();
if (index != -1) {
System.out.print("Enter your password: ");
int password = input.nextInt();
if (Main.accountHolders[index].getAccount().getPassword() == password) {
System.out.println("Your balance is: " +
Main.accountHolders[index].getAccount().getBalance());
} else {
System.out.println("Wrong password");
}
}
}
public static void deposit() {
int index = findAccount();
if (index != -1) {
System.out.print("Enter the required amount: ");
int money = input.nextInt();
Main.accountHolders[index].getAccount().makeDeposit(money);
System.out.println("Deposit successful");
}
}
private static int findAccount() {
System.out.print("Please Enter your account number: ");
int accountNum = input.nextInt();
for (int i = 0; i < Main.index; i++) {
User user = Main.accountHolders[i];
int id = user.getAccount().getUniID();
if (id == accountNum) {
return i;
} else if (id != accountNum){
System.out.println("Account number not found");
}
}
return -1;
}
}
sorry, It's a bit long but right now this the whole thing. I want to introduce a new variable for credit card number users every time they register a new account.
Can you try below code.if you wants only one time just remove for loop.
public class RandomSetGenerator {
public static void main(String[] args) {
Random generator = new Random();
for (int i = 0; i < 10; i++) {
String string = Integer.toString(generator.nextInt(9000) + 1000) + "-" + Integer.toString(generator.nextInt(9000) + 1000) + "-" + Integer.toString(generator.nextInt(9000) + 1000) + "-" + Integer.toString(generator.nextInt(9000) + 1000);
System.out.println("Specific set of random number generated :" + string);
}
}}
create a function which gives you the random number within a range and use it generate the same:
public class RandomSetGenerator {
public String genNumberToString(int i, int j){
Random generator = new Random();
return Integer.toString(generator.nextInt(i) + j)
}
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
String str = genNumberToString(9000, 1000) + "-" + genNumberToString(9000, 1000) + "-" + genNumberToString(9000, 1000) + "-" + genNumberToString(9000, 1000);
System.out.println("Specific set of random number generated :" + str);
}
}}
I'm currently a beginner student in computer science, and I have been working on a "Movie Library" application for class. In my original code it seems as though whenever I call the .printLibrary() and .averageRating() methods there is nothing that prints out, even though I have initialized the array objects and input new information into them.
public class MovieApp {
public static void main(String [] args) {
MovieUX mu = new MovieUX();
mu.run();
}
}
import java.util.Scanner;
public class MovieUX {
public void run(){
Scanner input = new Scanner (System.in);
char continueProcess = 'y';
while(continueProcess == 'y'){
System.out.println(" Welcome to the Movie Data Base");
System.out.println("-----------------------------------------------");
System.out.println("Please select from the following options: (Please make sure to create your library"+
" and movie(s) first.)");
System.out.println("1. Create a library.");
System.out.println("2. Create a Movie.");
System.out.println("3. Add a movie to a library.");
System.out.println("4. Add an actor to a movie.");
System.out.println("5. Print a library.");
System.out.println("6. Print average movie rating for a library.");
System.out.println("-----------------------------------------------");
int option = input.nextInt();
int i = 0;
int j = 0;
Library [] libraryArr = new Library[10];
for(int a=0; a<libraryArr.length; a++)
libraryArr[a] = new Library(0);
Movie [] movieArr = new Movie[10];
for(int b=0; b<movieArr.length; b++)
movieArr[b] = new Movie("","",0,0.0,0);
switch (option){
case 1:
System.out.println("Please input the amount of movies in your library");
int numOfMovies = input.nextInt();
libraryArr [i] = new Library(numOfMovies);
i++;
break;
case 2:
System.out.println("Please enter the name of the movie");
String title = input.next();
System.out.println("Please enter the director of the movie");
String director = input.next();
System.out.println("Please enter the year the movie was released");
int year = input.nextInt();
System.out.println("Please enter the movie's rating");
double rating = input.nextDouble();
System.out.println("Please enter the number of actors");
int maxActors = input.nextInt();
movieArr [j] = new Movie(title, director, year, rating, maxActors);
j++;
break;
case 3:
System.out.println("Below is your list of movies, select the corresponding movie" +
" to add it to your desired library.");
System.out.println();
for(int k=0; k<movieArr.length; k++){
System.out.println((k)+". "+movieArr[k].getTitle());
}
int movieChoice = input.nextInt();
System.out.println("Below are some libraries, chose the library that you wish to" +
" add your movie into.");
System.out.println();
for(int l=0; l<libraryArr.length; l++){
System.out.println("Library #" +(l));
}
int desiredLibrary = input.nextInt();
libraryArr[desiredLibrary].addMovie(movieArr[movieChoice]);
break;
case 4:
System.out.println("Below is your list of movies, please select the movie"+
" that you desire to add an actor into.");
System.out.println();
for(int k=0; k<movieArr.length; k++){
System.out.println((k)+". "+movieArr[k].getTitle());
}
movieChoice = input.nextInt();
System.out.println("Please input the actor's name that you would like to"+
" add to your movie.");
String addedActor = input.next();
movieArr[movieChoice].addActor(addedActor);
break;
case 5:
System.out.println("To print out a library's contents, please select from the following"+
" list.");
for(int l=0; l<libraryArr.length; l++){
System.out.println("Library #" +(l));
}
desiredLibrary = input.nextInt();
libraryArr[desiredLibrary].printLibrary();
break;
case 6:
System.out.println("To print out the average movie rating for a library, please"+
" select a library from the following list.");
for(int l=0; l<libraryArr.length; l++){
System.out.println("Library #" +(l));
}
desiredLibrary = input.nextInt();
System.out.println(libraryArr[desiredLibrary].averageRating());
break;
default:
System.out.println("Not a valid input.");
}
System.out.println("If you would like to continue customizing and adjusting your library"+
" and movie settings, please input 'y'. Otherwise, press any key and hit 'enter'.");
continueProcess = input.next().charAt(0);
}
}
}
import java.util.Arrays;
public class Movie {
private String title;
private String director;
private int year;
private double rating;
private String [] actors;
private int numberOfActors;
public Movie(String title, String director, int year, double rating, int maxActors) {
this.title = title;
this.director = director;
this.year = year;
this.rating = rating;
actors = new String[maxActors];
numberOfActors = 0;
}
public String getTitle() {
return title;
}
public String getDirector() {
return director;
}
public int getYear() {
return year;
}
public double getRating() {
return rating;
}
public void setRating(double rating) {
this.rating = rating;
}
public String [] getActors() {
return Arrays.copyOf(actors, actors.length);
}
public boolean addActor(String actor) {
if (numberOfActors < actors.length) {
actors[numberOfActors] = actor;
numberOfActors++;
return true;
}
return false;
}
public String toString() {
StringBuffer sb = new StringBuffer();
sb.append("Title: " + title + "\n");
sb.append("Director: " + director + "\n");
sb.append("Year: " + year + "\n");
sb.append("Rating: " + rating + "\n");
sb.append("Starring:\n");
for (int i=0; i<numberOfActors; i++)
sb.append("\t" + actors[i] + "\n");
return sb.toString();
}
}
public class Library {
private Movie [] movies;
private int numberOfMovies;
public Library(int maxMovies) {
movies = new Movie[maxMovies];
numberOfMovies = 0;
}
public int getNumberOfMovies() {
return numberOfMovies;
}
public boolean addMovie(Movie movie) {
if (numberOfMovies < movies.length) {
movies[numberOfMovies] = movie;
numberOfMovies++;
return true;
}
return false;
}
public double averageRating() {
double total = 0.0;
for (int i=0; i<numberOfMovies; i++)
total += movies[i].getRating();
return total / numberOfMovies;
}
public void printLibrary() {
for (int i=0; i<numberOfMovies; i++)
System.out.println(movies[i]);
}
}
I was wondering, was the reason why when I call the .printLibrary() and .averageRating() methods in Switch Case #5 and #6 respectively of Class MovieUX do not print anything because they are embedded in a switch statement, and information is not stored whenever the program processes the switch statement, or some other reason?
Thank you all for your help.
replace printLibrary() method with:
public void printLibrary() {
System.out.println(numberOfMovies);
for (int i=0; i<numberOfMovies; i++)
System.out.println(movies[i]);
}
you will find it output:
0
and so the for loop cant be executed. and
the same as averageRating()
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
Here is my issue. I am trying to build an array of HomeLoan in my main, and then from my main, call the printHLoans(hLoans) from my main, so that I can list them and then add more functionality. Unfortunately, it is saying that hLoan cannot be resolved as a variable.
Main Class
import java.util.InputMismatchException;
import java.util.Scanner;
public class LoanTest
{
static int term;
static int loanID=0;
static int hHowMany=0;
static int cHowMany=0;
public static void main(String[] args)
{
Scanner input = new Scanner (System.in);
System.out.print("Enter name: ");
String name = input.nextLine();
System.out.print("Enter Customer ID: ");
int custID=0;
do
{
try
{
custID = input.nextInt();
}
catch (InputMismatchException e)
{
System.out.println("Customer IDs are numbers only");
input.next();
}
}while (custID<1);
boolean aa=true;
while(aa)
{
System.out.println("Do you have a (h)ome loan or a (c)ar loan?");
String a = input.next();
switch (a)
{
case "h": System.out.println("You selected Home Loan");
System.out.println("How many Home Loans would you like to enter?");
hHowMany = input.nextInt();
HomeLoan[] hLoans = new HomeLoan[hHowMany];
int z=0;
while (hHowMany>z)
{
hLoans[z] = new HomeLoan(name, custID);
z++;
}
break;
case "c": System.out.println("You selected Car Loan");
System.out.println("How many Car Loans would you like to enter?");
cHowMany = input.nextInt();
int x=0;
CarLoan[] carLoans = new CarLoan[cHowMany];
while (x<cHowMany)
{
System.out.print("Enter Loan ID: ");
loanID=0;
do
{
try
{
loanID=input.nextInt();
}
catch (InputMismatchException e)
{
System.out.println("Loan IDs are number only");
input.next();
}
}while (loanID<1);
boolean b=true;
while(b)
{
System.out.print("Enter term: ");
term=input.nextInt();
boolean t = CarLoan.termCorrect(term);
if(t){System.out.println("Error: Maximum of 6 year");}
else {b=false; System.out.println("You entered: " + term + " years");}
}
carLoans[x] = new CarLoan(name, custID, loanID, term);
x++;
}
break;
default: System.out.println("Invalid input");
break;
}
System.out.print("Would you like to enter another loan?");
System.out.print("(y)es or (n)o:");
String m = input.next();
System.out.println("");
switch (m)
{
case "y": break;
case "n": aa=false;
break;
default: System.out.print("Invalid entry");
}
}
printHLoans(hLoans);
System.out.println("Thank you for using Loan Software");
System.out.println("Have a nice day");
}
public static void printHLoans(HomeLoan hLoans[])
{
System.out.println("Here are the loans you entered . . .");
int zzz=0;
while (zzz<hHowMany)
{
term = hLoans[zzz].getTerm();
loanID=hLoans[zzz].getLoanID();
String address=hLoans[zzz].getAddress();
double loanAmount = hLoans[zzz].getLoanAmount();
System.out.print(zzz + ": ");
System.out.print(hLoans[zzz].toString(loanID, address, term, loanAmount));
System.out.println();
zzz++;
}
}
}
HomeLoan Class
import java.util.InputMismatchException;
import java.util.Scanner;
public class HomeLoan extends Loan
{
private String address;
int howMany;
private double loanAmount;
private int term;
private int loanID;
public HomeLoan()
{
}
public HomeLoan(String name, int custID)
{
//super(name, custID, loanID);
Scanner input = new Scanner (System.in);
System.out.print("Enter Loan ID: ");
loanID=0;
do
{
try
{
loanID=input.nextInt();
}
catch (InputMismatchException e)
{
System.out.println("Loan IDs are number only");
input.next();
}
}while (loanID<1);
boolean l=true;
while (l)
{
System.out.print("Enter term: ");
term=input.nextInt();
boolean s = HomeLoan.termCorrect(term);
if (s){System.out.println("Error: Maximum of 30 years");}
else {l=false;}
}
//System.out.println();
input.nextLine();
System.out.print("Enter your address: ");
address=input.nextLine();
System.out.print("Enter loan ammount: ");
loanAmount = input.nextDouble();
double annualInterest = 10.99;
double monthlyPayment = amortization(loanAmount, annualInterest, term);
double newBalance=payment(monthlyPayment, loanAmount);
//System.out.println("Payment: " + monthlyPayment);
//System.out.println("New balance after payment: " + newBalance);
}
public static boolean termCorrect(int term)
{
boolean a;
if (term>30) {a=true; return a;}
else {a=false; return a;}
}
public String toString(String name, int custID, int loanID)
{
String display = "Name: " + name + " Customer ID: " + custID + " Address: "+ address+ " Loan ID: " + loanID + " Loan Amount: $" + loanAmount
+ " Current Balance: $";
return display;
}
public String getAddress()
{
return address;
}
public double getLoanAmount()
{
return loanAmount;
}
public int getTerm()
{
return term;
}
public int getLoanID()
{
return loanID;
}
public String toString(int loanID, String address, int term, double loanAmmount)
{
String displa = "ID: " + loanID + " Address:" + address + " Term: " + term + " Loan Ammount: " + loanAmmount;
return displa;
}
private void equals()
{
}
public void printHLoans(HomeLoan hLoans[], int xxx)
{
}
}
How do I make this work?
That's because you've declared the HomeLoan[] hLoans = new HomeLoan[hHowMany]; within the while loop and are trying to access it after that. That's why once the while loop is over, the hLoans goes out of scope. In your case, its more specifically within the case "h" of the switch, which further narrows down the scope of hLoans to just within it.
To be able to access it outside the while, you need to declare it at a scope higher than the while. Do something like this.
HomeLoan[] hLoans; // Before while
while(aa) {
...
switch..
case "h": hLoans = new HomeLoan[hHowMany];
}
printHLoans(hLoans);