Scanner carriage return Overflow - java

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.

Related

Professor gets a java.io.FileNotFoundException but I don't?

I had a project for my Java class where the user enters patients for a hospital then the program reads a file and the user can choose to amend their added patients to the file, print it out to the screen, or both. The program works perfectly in NetBeans for me but in the professor's comments, he says his compiler got a FileNotFoundException(Edit: It is actually a runtime error), even though I included the file in the package. When I emailed him, he only repeated that he received a FileNotFoundException.
Here is the code:
package realworldproblem3;
import java.util.*;
import java.io.*;
public class xyzHospital {
static int numOfPat;
static Scanner input = new Scanner(System.in);
static String inp;
static ArrayList<Patient> p = new ArrayList<>();
public static void main(String[] args) throws IOException {
boolean done = false;
importPatients();
System.out.print("Add new patients to the report:\n");
while (done == false){
addPatient();
System.out.print("Are you done adding patients? (Y or N)\n");
inp = input.nextLine();
switch (inp.toLowerCase()){
case "y": done = true;
break;
case "n": done = false;
break;
default: System.out.print("You did not enter a valid character. The program will print results then exit.\n\n");
done = true;
break;
}
}
printAll();
}
static public void addPatient(){
numOfPat++;
Patient pat = new Patient();
p.add(pat);
pat.addInfo(numOfPat);
}
static public void printAll() throws IOException{
System.out.print("Do you want to output the report to the screen ('S'), to a file ('F'), or both('B')?\n");
inp = input.next();
PrintWriter writer = new PrintWriter("XYZHospitalExampleData-1.txt");
switch (inp.toLowerCase()){
case "s":
System.out.print("\t\t\t\t\tXYZ Community Hospital\t\t\n=============================================================================================================\n");
System.out.printf("%-14s%30s%38s%n", " Name", "Address", "Payment Information");
System.out.printf("%-8s%-8s%15s%10s%10s%8s%15s%15s%15s %n", "Last", "First", "Address Line 1", "City", "State", "Zip", "Payment Date", "Payment Amt.","Amount Owed");
System.out.print("=============================================================================================================\n");
for(int i = 0; i<numOfPat;i++){
p.get(i).print();
}
break;
case "f":
writer.print(""); //writes over file so there is no duplicate patients
writer.close();
for(int i = 0; i<numOfPat;i++){
p.get(i).printToFile();
}
break;
case "b":
System.out.print("\t\t\t\t\tXYZ Community Hospital\t\t\n=============================================================================================================\n");
System.out.printf("%-14s%30s%38s%n", " Name", "Address", "Payment Information");
System.out.printf("%-8s%-8s%15s%10s%10s%8s%15s%15s%15s %n", "Last", "First", "Address Line 1", "City", "State", "Zip", "Payment Date", "Payment Amt.","Amount Owed");
System.out.print("=============================================================================================================\n");
writer.print("");
writer.close();
for(int i = 0; i<numOfPat;i++){
p.get(i).printToFile();
p.get(i).print();
}
break;
}
}
//each patient from the file is added as a patient object
static public void importPatients() throws IOException{
try(Scanner read = new Scanner(new BufferedReader(new FileReader("XYZHospitalExampleData-1.txt")))) {
while(read.hasNextLine()){ //one more line means that there is another patient to add
numOfPat++;
read.nextLine();
}
read.close();
try(Scanner r = new Scanner(new BufferedReader(new FileReader("XYZHospitalExampleData-1.txt")))) {
for (int j=0; j < numOfPat; j++){
String line = r.nextLine();
Patient pat = new Patient();
p.add(pat);
String[] str = line.split("\\^"); //the delimiter ^ is used to separate information in the file
for (int i = 0; i < str.length; i++){
if(str[i].isEmpty()||str[i].matches("0")||str[i] == null){ //if str[i] is empty, that means that it will be skipped over
i++;
}
switch (i){
case 0: p.get(j).ID = Integer.parseInt(str[i]);
break;
case 1: p.get(j).nameLast = str[i];
break;
case 2: p.get(j).nameFirst = str[i];
break;
case 3: p.get(j).address = str[i];
break;
case 4: p.get(j).opAddr = str[i];
break;
case 5: p.get(j).city = str[i];
break;
case 6: p.get(j).state = str[i];
break;
case 7: p.get(j).zip = Integer.parseInt(str[i]);
break;
case 8: p.get(j).optZip = Integer.parseInt(str[i]);
break;
case 9: p.get(j).payDate = str[i];
break;
case 10: p.get(j).payment = Double.parseDouble(str[i]);
break;
case 11: p.get(j).owed = Double.parseDouble(str[i]);
break;
default: System.out.print("Error.\n");
break;
}
}
}
r.close();
}
}
}
}
Here is the patient class:
package realworldproblem3;
import java.util.*;
import java.io.*;
public class Patient {
Scanner input = new Scanner(System.in);
String nameFirst, nameLast, address, opAddr,city, state, payDate;
int zip, optZip, ID;
double owed, payment;
public void print() {
System.out.printf("%-8s%-9s%-20s%-10s%-8s%-7s%-15s%-11.2f%-10.2f%n", nameLast, nameFirst, address, city, state, zip, payDate, owed, payment);
}
public void printToFile()throws IOException{
try (PrintWriter writer = new PrintWriter(new FileWriter("XYZHospitalExampleData-1.txt", true))) {
writer.write(ID + "^" + nameLast+ "^" + nameFirst + "^" + address + "^" + opAddr + "^" + city + "^" + state + "^" + zip + "^" + optZip + "^"+ payDate + "^" + payment + "^" + owed +"\n");
writer.close();
}
}
private void setName(){
System.out.print("Enter patient's first name.\n"); //user is asked for all information
nameFirst = input.nextLine(); //first three inputs use nextLine so it consumes the end of line character, so the address will be put in the string correctly.
System.out.print("Enter patient's last name.\n"); //if next() is used, the address is cut off at the first whitespace and the other elements of the address
nameLast = input.nextLine(); //are stored in the upcoming inputs.
if (nameFirst.isEmpty()||nameLast.isEmpty()){
System.out.print("You must enter the first and last name.\n");
setName();
}
}
public String getName(){
return nameFirst + " " + nameLast;
}
private void setAddr(){
System.out.print("Enter patient's address.\n");
address = input.nextLine();
if (address.isEmpty()){
System.out.print("You must enter the patients address.\n");
setAddr();
}
}
public String getAddr(){
return address;
}
private void setCity(){
System.out.print("Enter patient's home city.\n");
city = input.nextLine();
if(city.isEmpty()){
System.out.print("You must enter the patients city.\n");
setCity();
}
}
public String getCity(){
return city;
}
private void setState(){
System.out.print("Enter patient's state.\n");
state = input.nextLine();
if(state.isEmpty()){
System.out.print("You must enter the patients state.\n");
setState();
}
}
public String getState(){
return state;
}
private void setDate(){
System.out.print("Enter the payment date.\n");
payDate = input.next();
if(payDate.isEmpty()){
System.out.print("You must enter a payment date.\n");
setDate();
}
}
public String getDate(){
return payDate;
}
private void setZip(){
System.out.print("Enter patient's zipcode.\n");
try{
zip = input.nextInt();
}
catch(Exception e){
System.out.print("You must enter a valid 5-digit zipcode.\n");
input.next();
setZip(); //if it says that the setZip call will make the function loop infinitely, it is just a warning, it will not loop infinitely.
}
int length = String.valueOf(zip).length();
if(length != 5 && zip > 0){
System.out.print("You must enter a valid 5-digit zipcode.\n");
setZip();
}
}
public int getZip(){
return zip;
}
private void setOwed(){
System.out.print("Enter patient's due balance.\n");
try{
owed = input.nextDouble();
}
catch(Exception e){
System.out.print("Amount has to be a non-negative number.\n");
input.next();
setOwed();
}
int length = String.valueOf(owed).length();
if (owed <0 || length == 0){
System.out.print("Amount has to be a non-negative number.\n");
setOwed();
}
}
public double getOwed(){
return owed;
}
private void setPayment(){
System.out.print("Enter patient's payment amount.\n");
try{
payment = input.nextDouble();
}
catch(Exception e){
System.out.print("Payment amount has to be a positive number less than the amount owed.\n");
input.next();
setPayment();
}
int length = String.valueOf(payment).length();
if(payment < 0 || length ==0 || payment > owed){
System.out.print("Payment amount has to be a positive number less than the amount owed.\n");
setPayment();
}
}
public double getPayment(){
return payment;
}
private void setID(int Id){
ID = Id;
}
public int getID(){
return ID;
}
public void addInfo(int ID){
setID(ID);
setName();
setAddr();
setCity();
setState();
setZip();
setOwed();
setPayment();
setDate();
}
}
And here is the file XYZHospitalExampleData-1.txt:
12345^Jones^John^1234 Test Drive^PO box 123^Test City^IN^11234^1234^12/05/2015^250.0^25000.0
12346^Jones^Sara^1234 Test Drive^PO box 123^Test City^IN^11234^1234^12/20/2017^50.0^50000.0
12347^Doe^John^1235 XYZ Drive^null^Test City^IN^11234^0^01/05/2016^350.0^56799.0
12348^Doe^Sara^1235 XYZ Drive^null^Test City^IN^11234^0^11/09/2017^100.0^5020.52
12349^Lawson^Lonnie^12 South Drive^null^Test City^IN^11236^0^03/15/2013^253.51^25065.52
12349^Anderson^Sara^156 North Avenue^null^Test City^IN^11246^0^05/05/2013^21.33^251.56
12350^Smith^Andy^2455 East Street^null^Test City^IN^11246^0^12/05/2017^365.21^2543.33
It starts with their ID and ends with the amount that they owe. Any help to understand why my professor's compiler is giving him an error would be appreciated, and what I can do to be sure that it will be able to find the file so I do not have this problem again.
In the beginning of your main method you call importPatients which reads data from the XYZHospitalExampleData-1.txt file. If this file is not present, you'll get an exception (in the runtime, not a compiler error).
Most probably something went wrong when your package was unpackaged. Maybe the file was not copied to the expected location, something like that. One of the ways to address this would be to catch the FileNotFoundException and to display a message describing what went wrong and what is expected.

Switch Statements, Pointers/References, and Object Arrays in Java

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()

Beginner Java: Understanding error message: Exception in thread "main" java.util.NoSuchElementException

I am very new to Java and I'm having trouble understanding the errors I get from these classes. Even though I have searched it up throughout stackoverflow and various other sites, I am not able to grasp the meaning of them. Any help would be great in understanding these errors messages.
Main Class
import java.io.IOException;
import java.util.Scanner;
public class Assignment4 {
public static void main (String[] args) throws IOException{
int command = 0;
Scanner kb=new Scanner(System.in);
System.out.print("Enter the name of the input file:Enter data.txt: ");
String fileName=kb.next();
ClassRoll cr = new ClassRoll("data.txt");
cr.display();
prompt();
System.out.print("Enter a command: ");
String ans=kb.next();
while (!(ans.equalsIgnoreCase("q") || ans.equalsIgnoreCase("quit")))
{
if(!(ans.equalsIgnoreCase("a") ||ans.equalsIgnoreCase("add") ||
ans.equalsIgnoreCase("sa") || ans.equalsIgnoreCase("average") ||
ans.equalsIgnoreCase("sn") || ans.equalsIgnoreCase("names") ||
ans.equalsIgnoreCase("r") || ans.equalsIgnoreCase("remove") ||
ans.equalsIgnoreCase("s") || ans.equalsIgnoreCase("save") ||
ans.equalsIgnoreCase("c1") || ans.equalsIgnoreCase("change1") ||
ans.equalsIgnoreCase("c2") || ans.equalsIgnoreCase("change2") ||
ans.equalsIgnoreCase("c3") || ans.equalsIgnoreCase("change3") ||
ans.equalsIgnoreCase("f") || ans.equalsIgnoreCase("find") ||
ans.equalsIgnoreCase("d") || ans.equalsIgnoreCase("display")))
System.out.println("Bad Command");
else
switch (command)
{
case 1: cr.add();
break;
case 2: cr.sortAverage();
cr.display();
break;
case 3: cr.sortNames();
cr.display();
break;
case 4: cr.remove();
cr.display();
break;
case 5: cr.save();
cr.display();
break;
case 6: ClassRoll.changeScore1();
cr.display();
break;
case 7: ClassRoll.changeScore2();
cr.display();
break;
case 8: ClassRoll.changeScore3();
cr.display();
break;
case 9: Student s=cr.find();
if (s == null)
System.out.println("Student not found");
else System.out.println(s.toString());
break;
case 10: cr.display();
break;
case 11 : System.out.println("Are you sure you want to quit? "
+ "Yes or No");
String quit = kb.next();
if (quit.equalsIgnoreCase("y") ||
quit.equalsIgnoreCase("yes")){
System.exit(0);
}
else
{
prompt();
System.out.print("Enter a command --> ");
ans=kb.next();
}
cr.save();
System.out.println("Thank you for using this program");
}
}
}
public static void prompt(){
System.out.println("Enter one of the following commands: ");
System.out.println("a or add to add a student in the class roll");
System.out.println("sa or average to sort the students based "
+ "on their average");
System.out.println("sn or names to sort the students "
+ "based on their last names");
System.out.println("r or remove to remove a student from the class roll");
System.out.println("s or save to save the list of students back to the input"
+ "datafile");
System.out.println("d or display to display the class roll");
System.out.println("c1 or change1 to change score 1 of a student");
System.out.println("c2 or change2 to change score 2 of a student");
System.out.println("c3 or change3 to change score 3 of a student");
System.out.println("d or display to display the class roll");
System.out.println("q or quit to exit the program");}
Class Roll
public class ClassRoll {
ArrayList students = new ArrayList();
private String title;
private String fileName;
public ClassRoll(String f) throws IOException{
//acquires title of file
Scanner fileScan;
Scanner lineScan;
String line;
fileName = f;
fileScan = new Scanner(new File(f));
title = fileScan.nextLine();
System.out.println("Course Title: " + title);
while (fileScan.hasNext()) {
line = fileScan.nextLine();
lineScan = new Scanner(line);
lineScan.useDelimiter("\t");
String lastName = lineScan.next();
String firstName = lineScan.next();
Student name = new Student(firstName, lastName);
name.setScore1(lineScan.nextInt());
name.setScore2(lineScan.nextInt());
name.setScore3(lineScan.nextInt());
students.add(name);
ClassRoll cr = new ClassRoll("data.txt");
cr.display();
}
}
void display(){
double classAverage = 0.0;
DecimalFormat f = new DecimalFormat("0.00");
System.out.println("\t" + title );
for (int i = 0; i < students.size(); i++){
//fix this part of the code, get average
Student name = (Student) students.get(i);
System.out.println(name.toString());
System.out.println("\n" + f.format(name.getAverage()));
classAverage = classAverage + name.getAverage();
}
System.out.println("\t\t\t" + f.format(classAverage / students.size()));
}
void add(){
Scanner input = new Scanner(System.in);
System.out.print("First Name: ");
String firstName = input.next();
System.out.print("Last Name: ");
String lastName = input.next();
System.out.print("Score 1: ");
int score1 = input.nextInt();
System.out.print("Score 2: ");
int score2 = input.nextInt();
System.out.print("Score 3: ");
int score3 = input.nextInt();
Student s = new Student(firstName, lastName);
s.setScore1(score1);
s.setScore2(score2);
s.setScore3(score3);
students.add(s);
}
static void changeScore1(){
Scanner kb = new Scanner(System.in);
System.out.println("Student's first Name: ");
String f = kb.next();
System.out.println("Student's last Name: ");
String n = kb.next();
System.out.println("Student's first Exam score: ");
Integer score1 = kb.nextInt();
System.out.println("New score of Exam 1: ");
Integer newScore1 = kb.nextInt();
score1 = newScore1;
}
static void changeScore2(){
Scanner kb = new Scanner(System.in);
System.out.println("Student's first Name: ");
String f = kb.next();
System.out.println("Student's last Name: ");
String n = kb.next();
System.out.println("Student's second Exam score: ");
Integer score2 = kb.nextInt();
System.out.println("New score of Exam 2: ");
Integer newScore2 = kb.nextInt();
score2 = newScore2;
}
static void changeScore3(){
Scanner kb = new Scanner(System.in);
System.out.println("Student's first Name: ");
String f = kb.next();
System.out.println("Student's last Name: ");
String n = kb.next();
System.out.println("Student's third Exam score: ");
Integer score3 = kb.nextInt();
System.out.println("New score of Exam 3: ");
Integer newScore3 = kb.nextInt();
score3 = newScore3;
}
private int search(String fn, String ln) {
int i = 0;
while (i < students.size()) {
Student s = (Student) students.get(i);
if (s.equals(fn, ln)) {
return i;
} else {
i++;
}}
return -1;
}
Student find(){
Scanner input = new Scanner(System.in);
System.out.print("First Name: ");
String firstName = input.next();
System.out.print("Last Name: ");
String lastName = input.next();
int i = search(firstName, lastName);
if (i >= 0) {
return (Student) students.get(i);
} else {
return null;
}
}
void remove(){
Scanner input = new Scanner(System.in);
System.out.print("First Name: ");
String firstName = input.next();
System.out.print("Last Name: ");
String lastName = input.next();
int i = search(firstName, lastName);
if (i >= 0) {
students.remove(i);
} else {
System.out.println("Student was not found within the list");
}
}
void sortAverage(){
for (int i = 0; i < students.size() - 1; i++) {
for (int j = i + 1; j < students.size(); j++) {
Student s1 = (Student) students.get(i);
Student s2 = (Student) students.get(j);
if (s1.getAverage() < s2.getAverage()) {
students.set(i, s2);
students.set(j, s1);
}
}}
}
void sortNames(){
for (int i = 0; i < students.size() - 1; i++) {
for (int j = i + 1; j < students.size(); j++) {
Student s1 = (Student) students.get(i);
Student s2 = (Student) students.get(j);
if (s1.compareTo(s2) > 0) {
students.set(i, s2);
students.set(j, s1);
}
}}}
void save() throws IOException{
OutputStream file = new FileOutputStream("data.txt");
OutputStream buffer = new BufferedOutputStream(file);
ObjectOutput output = new ObjectOutputStream(buffer);
PrintWriter out = new PrintWriter(fileName);
out.println(title);
for (int i = 0; i < students.size(); i++) {
Student s = (Student) students.get(i);
out.println(s.toString());
output.close();
}}
}
Error Messages
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:862)
at java.util.Scanner.next(Scanner.java:1371)
at ClassRoll.<init>(ClassRoll.java:38)
at Assignment4.main(Assignment4.java:16)
hasNext() is a precondition for next(), or else you will get those exceptions. So hasNext() must match the corresponding next()

Scanner ignoring the String "name"

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.

Getting a Null Pointer Exception and not sure how to fix it [duplicate]

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

Categories

Resources