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.
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'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()
So basically this is homework/classwork and we are asked to refrain from usin J.Frame and databases and all that stuff. So how do I create a login system that has 4 usernames and that for each user they have their own first name and last name? As you can see below currently it only asks for password and not username, password and the user's first and last name. Also I found the code for that but I'm not sure how to add a new username and the other two variables and the code was created by someone on stackoverflow so I'm not sure if I can post it here or not.
/**
* #param args the command line arguments
*/
static Scanner s = new Scanner(System.in);
public static void main(String[] args) throws IOException{
// TODO code application logic here
login("James");
String[][] data = generateData();
while(true){
System.out.println("\n1 for printing");
System.out.println("2 for charges");
System.out.println("3 for payment");
System.out.println("4 for adding a new account");
System.out.println("0 to exit");
System.out.print("What you want to do: ");
int input = 0;
try{
input = Integer.parseInt(s.nextLine());
} catch(NumberFormatException e){
System.out.println("Wrong input, must enter an integer!");
continue;
}
if (input == 0){
printToFile(data);
break;
} else{
switch(input){
case 1: printing(data);
break;
case 2: charges(data);
break;
case 3: payment(data);
break;
case 4: add(data);
data = generateData();
break;
default: System.out.println("Wrong input, must enter 0-4!");
}
}
}
}
public static void add(String[][] x) throws IOException{
System.out.print("Enter your student ID: ");
String a = s.nextLine();
System.out.print("Enter your First Name: ");
String b = s.nextLine();
System.out.print("Enter your Last Name ");
String c = s.nextLine();
System.out.print("Enter your Contact Number: ");
String d = s.nextLine();
System.out.print("Enter your Email Address: ");
String e = s.nextLine();
System.out.print("Enter your Car Plate Number: ");
String f = s.nextLine();
System.out.print("Enter Today's Date: ");
String g = s.nextLine();
int counter = x.length;
File data = new File("data.txt");
PrintWriter y = new PrintWriter(data);
y.println(counter+1);
for(int i=0; i<counter; i++){
y.println();
y.println(x[i][0]);
y.println(x[i][1]);
y.println(x[i][2]);
y.println(x[i][3]);
y.println(x[i][4]);
y.println(x[i][5]);
y.println(x[i][6]);
}
y.println();
y.println(a);
y.println(b);
y.println(c);
y.println(d);
y.println(e);
y.println(f);
y.println(g);
y.close();
}
public static void printToFile(String[][] x) throws IOException{
int counter = x.length;
File data = new File("data.txt");
PrintWriter y = new PrintWriter(data);
y.println(counter);
for(int i=0; i<counter; i++){
y.println();
y.println(x[i][0]);
y.println(x[i][1]);
y.println(x[i][2]);
y.println(x[i][3]);
y.println(x[i][4]);
y.println(x[i][5]);
y.println(x[i][6]);
}
y.close();
}
public static void login(String password){
System.out.print("Enter your password: ");
String input = s.nextLine();
int i = 0;
while(true){
if( !(input.equals(password)) ){
System.out.println("Wrong password!");
if(i==1){
System.exit(0);
}
System.out.println("Last chance!");
System.out.print("Enter your password: ");
input = s.nextLine();
i++;
} else{
break;
}
}
}
public static String[][] generateData() throws IOException{
File x = new File("data.txt");
Scanner y = new Scanner(x);
int counter = Integer.parseInt(y.nextLine());
String[][] data = new String[counter][7];
for(int i=0; i<counter; i++){
y.nextLine();
data[i][0] = y.nextLine();
data[i][1] = y.nextLine();
data[i][2] = y.nextLine();
data[i][3] = y.nextLine();
data[i][4] = y.nextLine();
data[i][5] = y.nextLine();
data[i][6] = y.nextLine();
}
y.close();
return data;
}
public static void printing(String[][] data){
int length1 = data.length;
int length2 = data[0].length;
for(int i=0; i<length1; i++){
System.out.println(" ID "+Integer.parseInt(data[i][0])+", First Name: "+data[i][1]+", Last Name: "+data[i][2]+", Contact Number: "+data[i][3]+", Email Address: "+data[i][4]+", Car Number: "+data[i][5]+", Date Registered: "+data[i][6]);
}
}
public static void charges(String[][] data){
int length1 = data.length;
for(int i=0; i<length1; i++){
System.out.println((i+1)+" for "+data[i][0]);
}
System.out.print("Who you want to charge: ");
int input = Integer.parseInt(s.nextLine());
System.out.print("How much you want to charge "+data[input-1][0]+": ");
data[input-1][2] = ""+(Double.parseDouble(data[input-1][2]) + Double.parseDouble(s.nextLine()));
}
public static void payment(String[][] data){
int length1 = data.length;
for(int i=0; i<length1; i++){
System.out.println(" (ID "+Integer.parseInt(data[i][1]));
}
System.out.print("Who want to pay: ");
int input = Integer.parseInt(s.nextLine());
System.out.print("How much "+data[input-1][0]+" want to pay: ");
data[input-1][2] = ""+(Double.parseDouble(data[input-1][2]) - Double.parseDouble(s.nextLine()));
}
}
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
If anyone can see where I've gone made a mistake in my code I would be eternally grateful. I recognize that it's an obscene amount of code, but I've been pulling my hair out with it over the last few days and simply cannot fathom what to do with it. I've asked others for help in my class but they cannot see where I have gone wrong. It's to do with carriage return scanner problem.
java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Unknown Source)
at PropertyMenu.runMenu(PropertyMenu.java:109)
at PropertyMenu.main(PropertyMenu.java:7)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at
edu.rice.cs.drjava.model.compiler.JavacCompiler.runCommand(JavacCompiler.java:272)
Any thoughts would be much appreciated.
Joe.
//ROOM CLASS
import java.util.Scanner;
public class Room{
private String description;
private double length;
private double width;
public Room (String description, double length, double width) {
this.description = description;
this.length = length;
this.width = width;
}
public Room(){
Scanner scan = new Scanner(System.in);
scan.useDelimiter("\n");
System.out.println("Enter description of room:");
description = scan.next();
System.out.println("Enter length of room:");
length = scan.nextDouble();
System.out.println("Enter width of room:");
width = scan.nextDouble();
}
public double getArea () {
return length*width;
}
#Override
public String toString() {
String result = ("***********************************\n");
result +=(" Room Viewing \n");
result +=("************************************\n");
result +=("The width of the room is " + width + "m.\n");
result +=("the length of the room is " + length + "m.\n");
result +=("the name of the room is: " + description +".\n");
return result;
}
}
//HOUSE CLASS
import java.util.*;
public class House {
private ArrayList<Room> abode;
private int idNum, numRooms;
private double totalArea;
private static int internalCount = 1;
private String address, roomInfo, houseType;
public House (String address, String houseType, int numRooms){
System.out.println("THIS IS THE START OF MY 3 ARGUMENT CONSTRUCTOR");
idNum = internalCount++;
this.address = address;
this.houseType = houseType;
this.numRooms = numRooms;
System.out.println("THIS IS THE END OF MY 3 ARGUMENT CONSTRUCTOR");
}
public House (String address, String houseType, int numRooms, String roomInfo){
System.out.println("THIS IS THE START OF MY 4 ARGUMENT CONSTRUCTOR");
idNum = internalCount++;
this.address = address;
this.houseType = houseType;
this.numRooms = numRooms;
this.roomInfo = roomInfo;
Scanner scan = new Scanner(roomInfo);
String desc;
Double l;
Double w;
while (scan.hasNext()){
desc= scan.next();
l = Double.parseDouble(scan.next());
System.out.println("the length from here"+l);
w = Double.parseDouble(scan.next());
System.out.println("the width from here"+w);
new Room (desc,l,w);
}
System.out.println("THIS IS THE END OF MY 4 ARGUMENT CONSTRUCTOR");
}
public void addRoom (){
totalArea=0;
abode.add(new Room ());
for (int i=0; i<abode.size(); i++){
totalArea += abode.get(i).getArea();
}
}
public House () {
totalArea = 0;
abode = new ArrayList<Room>();
idNum = ++internalCount;
Scanner scan = new Scanner(System.in);
scan.useDelimiter("\n");
System.out.println("Enter address of house:");
address = scan.next();
System.out.println("Enter number of rooms:");
numRooms = scan.nextInt();
System.out.println("Enter type of house:");
houseType = scan.next();
for (int i=1; i<=numRooms; i++){
addRoom();
}
}
int getIdNum() {
return idNum;
}
#Override
public String toString() {
String result =("************************************\n");
result +=(" House Viewing \n");
result +=("************************************\n");
result +=("The house ID is " + idNum +".\n");
result +=("The house address is " + address +".\n");
result +=("The number of rooms here is " + numRooms +".\n");
result +=("The house type is " + houseType +".\n");
result +=("The total area of the house is " + totalArea +".\n");
result +=(abode);
return result;
}
}
//DRIVER
import java.util.*;
import java.io.*;
public class PropertyMenu {
private ArrayList<House> properties =new ArrayList<House>();
public static void main (String[] args) throws IOException{
PropertyMenu menu = new PropertyMenu();
menu.runMenu();
}
public void runMenu() {
House h = null;
char selection = ' ';
Scanner s = new Scanner(System.in);
while (selection != 'e') {
System.out.println();
System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
System.out.println("Welcome to my Property database");
System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
System.out.println("What do you want to do?");
System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
System.out.println("To ADD a house enter......A");
System.out.println("To VIEW a house enter.....V");
System.out.println("To DELETE a house enter...D");
System.out.println("To USE a file.............F");
System.out.println("To QUIT enter.............E");
selection = s.next().toLowerCase().charAt(0);
switch (selection) {
case 'a':
properties.add(new House());
break;
case 'v':
System.out.println("Do you want to view all houses (y/n)?");
String all = "";
all = s.next();
if (all.equalsIgnoreCase("y")){
for (int i=0; i<properties.size(); i++){
System.out.println("Property ID: "+ (properties.get(i)));
}
}
else if(all.equalsIgnoreCase("n")){
System.out.println(""+ properties.size() +" houses have been created, choose the id of the house you wish to view.. (1/2/3 etc...)");
System.out.println("List of property ID's: ");
for (int i=0; i<properties.size(); i++){
System.out.println("Property ID: "+ (properties.get(i)).getIdNum());
}
System.out.println("Enter ID of the house you wish to view:");
int viewHouse = s.nextInt();
if (viewHouse <= properties.size() && viewHouse >= 1){
System.out.println(properties.get(viewHouse-1));
}
else{
System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
System.out.println(" House Not Present ");
System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
}
}
else{
System.out.println("Do you want to view all houses (y/n)?");
all = s.next();
}
break;
case 'd':
System.out.println(""+ properties.size() +" houses have been created, choose the id of the house you wish to delete.. (1/2/3 etc...)");
System.out.println("List of property ID's: ");
for (int i=0; i<properties.size(); i++){
System.out.println("Property ID: "+ (properties.get(i)).getIdNum());
}
System.out.println("Enter ID of the house you wish to delete:");
int deleteHouse = s.nextInt();
if (deleteHouse <= properties.size() && deleteHouse >= 1){
properties.remove(deleteHouse -1);
}
else{
System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
System.out.println(" House Not Present ");
System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
}
break;
case 'e':
System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
System.out.println(" Goodbye ");
System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
break;
//*********************************THIS IS WHERE MY PROBLEM IS, FROM HERE*************
case 'f':
try{
Scanner fileScan = new Scanner (new File("property.txt"));
while (fileScan.hasNext()){
System.out.println("THIS IS A FRESH LOOP");
String a;
String ht;
String rms1;
int rms;
String yn;
String rmInfo;
a = fileScan.nextLine();
System.out.println("ADDRESS"+a);
ht = fileScan.nextLine();
System.out.println("HOUSE TYPE"+ht);
rms1 = fileScan.next();
rms = Integer.parseInt(rms1);
System.out.println("HOUSEROOMs"+rms);
yn = fileScan.next();
String overflow = fileScan.nextLine();
System.out.println("Yes/no"+yn);
if (yn.equalsIgnoreCase("Y")){
System.out.println("THIS IS THE START OF CHOICE = Y");
rmInfo = fileScan.nextLine();
properties.add(new House(a, ht, rms, rmInfo));
System.out.println("THIS IS THE END OF CHOICE = Y");
}
else{
System.out.println("THIS IS THE START OF CHOICE = N");
properties.add(new House(a, ht, rms));
System.out.println("THIS IS THE END OF CHOICE = N");
}
}
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
break;
//******************************************TO HERE^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
default:
System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
System.out.println(" Try again! ");
System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
}
}
System.out.println("Exiting program.");
}
}
This is could be a guess that you are not reading file correctly. Whatever I see from your block of file reading code and input file "property.txt" , make following changes.
In your while use following, as you are reading file line by line.
while (fileScan.hasNextLine()){
Only use nextLine() method
rms1 = fileScan.nextLine();
yn = fileScan.nextLine();
I hope these will solve your problem.