Switch Statements, Pointers/References, and Object Arrays in Java - 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()

Related

Create user with list of data

The program should contain the customers plus a list of the calories and the distance during the week.
My question is, how can I put together the customer's name and the distance?
public class TestCustomer {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
ArrayList<String> customersNames = new ArrayList<String>();
char userInput = ' ';
System.out.println("A to show all");
userInput = scan.next().charAt(0);
if(userInput == 'A') {
System.out.println("All results ");
for(int i = 0; i < customersNames.size(); i++) {
System.out.println(customersNames.get(i));
}
}
}
And here's my Customer class
public class Customer {
private String name;
private double calories;
private double distance;
public Customer(String name, double distance) {
this.name = name;
this.distance = distance;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setCalories(double calories) {
this.calories = calories;
}
public double getCalories() {
return calories;
}
public void setDistance(double distance) {
this.distance = distance;
}
public double getDistance() {
return distance;
}
}
This uses a list of customers instead of customernames.
I put the Customer class as static in the testclass for brevity(keep everything in one file). Better to have it seperate as you do.
Also I did not want to change the whole design or do a complete rewrite - it is your design. So this is only making it work, fixing the behavior to the one required.
Eg with having the customers in HashMap that is indexed by name one could retrieve a dataset more elegantly in O(1). But thats maybe another improvement.
This only has the list. So for simplicity I added an equals, that makes users equal if they have the same name.
I create a new User that can be searched in the list. If not found I add this user with the given input to the list.
If found I search for existing the user in the list with indexOf and retrieve that existing user. I do it in one step.
import java.util.ArrayList;
import java.util.Objects;
import java.util.Scanner;
public class TestCustomer {
public static class Customer {
private String name;
private double calories;
private double distance;
public Customer(String name, double calories, double distance) {
this.name = name;
this.calories = calories;
this.distance = distance;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setCalories(double calories) {
this.calories = calories;
}
public double getCalories() {
return calories;
}
public void setDistance(double distance) {
this.distance = distance;
}
public double getDistance() {
return this.distance;
}
#Override
public int hashCode() {
int hash = 5;
hash = 71 * hash + Objects.hashCode(this.name);
return hash;
}
#Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
return Objects.equals(this.name, ((Customer)obj).name);
}
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
ArrayList<Customer> customers = new ArrayList<>();
char userInput = ' ';
while (userInput != 'q') {
System.out.println("Press 'a' to show all customers or press 's' to search for customer ");
userInput = scan.next().charAt(0);
userInput = Character.toUpperCase(userInput);
if (userInput == 'A') {
System.out.println("Here's the list of all customers: ");
for (int i = 0; i < customers.size(); i++) {
System.out.println(customers.get(i).getName());
}
// here I should show the list of all customers and their data
} else if (userInput == 'S') {
System.out.println("You selected to search for a customer");
createCustomer(customers);
}
}
}
public static ArrayList<Customer> createCustomer(ArrayList<Customer> customers) {
Scanner scan2 = new Scanner(System.in);
System.out.println("Enter customer's first name: ");
String fName = scan2.next();
System.out.println("Enter customer's last name: ");
String lName = scan2.next();
String fullName = fName + " " + lName;
Customer newCustomer = new Customer(fullName,0,0);
if (customers.contains(newCustomer)) {
newCustomer=customers.get(customers.indexOf(newCustomer));
System.out.println("Customer already on the list. Here's the information: ");
System.out.println(fullName + " " + newCustomer.distance + " " + newCustomer.calories );
} else{
System.out.println("Customer not found. Would you like to create a new customer? y/n ");
char createUserPrompt = scan2.next().charAt(0);
if (createUserPrompt == 'y') {
String[] daysOfWeek = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"};
for (String daysOfWeek1 : daysOfWeek) {
System.out.println("Enter calories consumed on " + daysOfWeek1);
newCustomer.calories = scan2.nextDouble();
System.out.println("Enter distance walked on " + daysOfWeek1);
newCustomer.distance = scan2.nextDouble();
}
customers.add(newCustomer);
} else if (createUserPrompt == 'n') {
System.out.println("User will not be added.");
}
}
return customers;
}
}
sample run:
Press 'a' to show all customers or press 's' to search for customer
a
Here's the list of all customers:
Press 'a' to show all customers or press 's' to search for customer
s
You selected to search for a customer
Enter customer's first name:
kai
Enter customer's last name:
last
Customer not found. Would you like to create a new customer? y/n
y
Enter calories consumed on Monday
5
Enter distance walked on Monday
5
Enter calories consumed on Tuesday
5
Enter distance walked on Tuesday
5
Enter calories consumed on Wednesday
5
Enter distance walked on Wednesday
5
Enter calories consumed on Thursday
5
Enter distance walked on Thursday
5
Enter calories consumed on Friday
5
Enter distance walked on Friday
5
Enter calories consumed on Saturday
5
Enter distance walked on Saturday
5
Enter calories consumed on Sunday
5
Enter distance walked on Sunday
5
Press 'a' to show all customers or press 's' to search for customer
a
Here's the list of all customers:
kai last
Press 'a' to show all customers or press 's' to search for customer
s
You selected to search for a customer
Enter customer's first name:
kai
Enter customer's last name:
last
Customer already on the list. Here's the information:
kai last 5.0 5.0
Press 'a' to show all customers or press 's' to search for customer
With some modifications to your Customer class in which the calories and distance will be stored ad an array for each day,
An ArrayList<Customer> will be used to store the list of customers.
Possible solution:
import java.util.*;
public class Main {
private static Scanner scan;
private static ArrayList<Customer> customers;
public static Customer customerExists(String customerName) {
for (int i = 0; i < customers.size(); i++) {
if (customers.get(i).getName().equals(customerName)) {
return customers.get(i);
}
}
return null;
}
public static void addCustomer() {
System.out.println(">> Add Customer <<\n");
System.out.print("Enter customer's first name: ");
String fName = scan.nextLine();
System.out.print("Enter customer's last name: ");
String lName = scan.nextLine();
String fullName = fName + " " + lName;
Customer existingCustomer = customerExists(fullName);
if (existingCustomer != null) {
System.out.println("\nCustomer already on the list. Here's the information: ");
System.out.println("#\tName\t\tCalories [Mon-Sun]\t\t\t\t\t\tDistance [Mon-Sun]");
System.out.println(existingCustomer.getName() + "\t" + Arrays.toString(existingCustomer.getCalories()) + "\t" + Arrays.toString(existingCustomer.getDistance()));
return;
}
String[] daysOfWeek = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"};
double calories[] = new double[daysOfWeek.length];
double distance[] = new double[daysOfWeek.length];
for (int j = 0; j < daysOfWeek.length; j++) {
System.out.print("Enter calories consumed on " + daysOfWeek[j] + ": ");
calories[j] = scan.nextDouble();
System.out.print("Enter distance walked on " + daysOfWeek[j] + ": ");
distance[j] = scan.nextDouble();
}
Customer customer = new Customer(fullName, calories, distance);
customers.add(customer);
System.out.println("\nCustomer added successfully!\n");
}
public static void showCustomers() {
System.out.println(">> All Customers <<\n");
System.out.println("#\tName\t\tCalories [Mon-Sun]\t\t\t\t\t\tDistance [Mon-Sun]");
for (int i = 0; i < customers.size(); i++) {
System.out.println(i+1 + "\t" + customers.get(i).getName() + "\t" + Arrays.toString(customers.get(i).getCalories()) + "\t\t\t" + Arrays.toString(customers.get(i).getDistance()));
}
System.out.println("\n");
}
public static void searchCustomers() {
System.out.println(">> Search for a Customer <<\n");
System.out.print("Enter customer's full name: ");
String fullName = scan.nextLine();
Customer customer = customerExists(fullName);
System.out.println(fullName);
if (customer == null) {
System.out.println("\nNo such customer exists.\n");
return;
}
System.out.println("\nCustomer information:\n");
System.out.println("#\tName\t\tCalories [Mon-Sun]\t\t\t\t\t\tDistance [Mon-Sun]");
System.out.println(customer.getName() + "\t" + Arrays.toString(customer.getCalories()) + "\t" + Arrays.toString(customer.getDistance()) + "\n");
}
public static void main(String[] args) {
boolean cont = true;
int option = -1;
scan = new Scanner(System.in);
customers = new ArrayList<>();
do {
System.out.println("=== Select an Option ===");
System.out.println("1. Add a customer");
System.out.println("2. Show all customers");
System.out.println("3. Search for customer");
System.out.println("0. Exit");
System.out.print("\n > ");
try {
option = Integer.parseInt(scan.nextLine());
System.out.println("\n");
switch(option) {
case 1:
addCustomer();
break;
case 2:
showCustomers();
break;
case 3:
searchCustomers();
break;
case 0:
System.out.println("Good Bye!");
cont = false;
break;
default:
System.err.println("'" + option + "' is not a valid option. Please try again.\n");
break;
}
} catch (NumberFormatException e) {
System.err.println("Invalid option selected.\n");
}
} while (cont == true);
}
}

Counting occurrence of attributes inside the objects of a Java Array

I have created an array of 25 Flower objects. Each flower object holds the flower name(String), flower color(String), presence of thorns(boolean), and flower scent(String). These attributes are handled by the 'Flower' class. I have pasted both classes in case the error is being caused by either class. The user inputs all of the attributes of the flowers when the menu prompts for the information. After the user enters all of the flowers they want to, I need to be able to print out the entire array and a counter of how many of each flower there are. For instance, if the user puts in 10 flowers and there are 3 Roses, 2 Lilly's, 3 Dandelions, and 2 Orchids, I need to print the entire array and then print the number each flower was present. The format for the display is:
Flower name: Rose Flower color: Red Flower has thorns: true Flower scent: Sweet
Rose - 3
Lilly - 3
Dandelion - 3
Orchid - 2
I am able to print out the array as shown, but cannot get the count variable to work properly. I do not need to sort this array.
Another issue I am getting in an OutOfBounds error. I can only put in 24 flowers before I encounter this error. The 25th flower triggers it. I thought this was covered by the addFlower index counter, but obviously, I was incorrect.
This assignment does not allow the use of ArrayList, which would make this much simpler. We have not explored error handling yet either.
Current code is:
package assignment2;
import java.util.Scanner;
public class Assignment2
{
public static void main(String[] args)
{
new Assignment2();
}
public Assignment2()
{
Scanner input = new Scanner(System.in);
Flower flowerPack[] = new Flower[25];
System.out.println("Welcome to my flower pack interface.");
System.out.println("Please select a number from the options below");
System.out.println("");
while (true)
{
// Give the user a list of their options
System.out.println("1: Add an item to the pack.");
System.out.println("2: Remove an item from the pack.");
System.out.println("3: Search for a flower.");
System.out.println("4: Display the flowers in the pack.");
System.out.println("0: Exit the flower pack interfact.");
// Get the user input
int userChoice = input.nextInt();
switch (userChoice)
{
case 1:
addFlower(flowerPack);
break;
case 2:
removeFlower(flowerPack);
break;
case 3:
searchFlowers(flowerPack);
break;
case 4:
displayFlowers(flowerPack);
break;
case 0:
System.out.println("Thank you for using the flower pack interface. See you again soon!");
input.close();
System.exit(0);
}
}
}
private void addFlower(Flower flowerPack[])
{
String flowerName; // Type of flower
String flowerColor; // Color of the flower
Boolean hasThorns = false; // Have thorns?
String flowerScent; // Smell of the flower
int index = 0;
Scanner input = new Scanner(System.in);
System.out.println("What is the name of flower is it?");
flowerName = input.nextLine();
System.out.println("What color is the flower?");
flowerColor = input.nextLine();
System.out.println("Does the flower have thorns?");
System.out.println("Choose 1 for yes, 2 for no");
int thorns = input.nextInt();
if(thorns == 1)
{
hasThorns = true;
}
input.nextLine();
System.out.println("What scent does the flower have?");
flowerScent = input.nextLine();
Flower fl1 = new Flower(flowerName, flowerColor, hasThorns, flowerScent);
for(int i = 0; i < flowerPack.length; i++)
{
if(flowerPack[i] != null)
{
index++;
if(index == flowerPack.length)
{
System.out.println("The pack is full");
}
}
else
{
flowerPack[i] = fl1;
break;
}
}
}
private void removeFlower(Flower flowerPack[])
{
Scanner input = new Scanner(System.in);
System.out.println("What student do you want to remove?");
displayFlowers(flowerPack);
System.out.println("Choose 1 for the first flower, 2 for the second, etc" );
int index = input.nextInt();
index = index - 1;
for (int i = 0; i < flowerPack.length - 1; i++)
{
if(flowerPack[i] != null && flowerPack[i].equals(flowerPack[index]))
{
flowerPack[i] = flowerPack[i + 1];
}
}
}
private void searchFlowers(Flower flowerPack[])
{
Scanner input = new Scanner(System.in);
String name;
System.out.println("What flower would you like to search for?");
name = input.nextLine();
boolean found = false;
for (int i = 0; i < flowerPack.length; i++)
{
if (flowerPack[i].getFlowerName().equalsIgnoreCase(name))
{
found = true;
break;
}
}
if (found)
{
System.out.println("We found your flower.");
}
else
{
System.out.println("That flower was not found.");
}
}
private void displayFlowers(Flower flowerPack[])
{
int count = 1;
for(int i = 0; i < flowerPack.length; i++)
{
if (flowerPack[i] != null)
{
if (flowerPack[i].equals(flowerPack[i+1]))
{
count++;
}
else
{
System.out.println(flowerPack[i]);
count = 1;
}
}
else
{
if (flowerPack[i] == null)
{
break;
}
}
}
}
}
The Flower class is below.
package assignment2;
public class Flower
{
#Override
public String toString()
{
return "Flower name: " + this.getFlowerName() + "\t" +
"Flower color: " + this.getFlowerColor() + "\t" +
"Flower has thorns: " + this.getHasThorns() + "\t" +
"Flower scent: " + this.getFlowerScent() + "\t" ;
}
private String flowerName;
private String flowerColor;
private Boolean hasThorns;
private String flowerScent;
Flower(String flowerName, String flowerColor, Boolean hasThorns, String flowerScent)
{
this.flowerName = flowerName;
this.flowerColor = flowerColor;
this.hasThorns = hasThorns;
this.flowerScent = flowerScent;
}
String getFlowerName()
{
return flowerName;
}
private void setFlowerName(String flowerName)
{
this.flowerName = flowerName;
}
private String getFlowerColor()
{
return flowerColor;
}
private void setFlowerColor()
{
this.flowerColor = flowerColor;
}
private Boolean getHasThorns()
{
return hasThorns;
}
private void setHasThorns()
{
this.hasThorns = hasThorns;
}
private String getFlowerScent()
{
return flowerScent;
}
private void setFlowerScent()
{
this.flowerScent = flowerScent;
}
}
private void displayFlowers(Flower flowerPack[])
{
String[] usedNames = new String[flowerPack.length];
int[] nameCounts = new int[flowerPack.length];
int usedNamesCount = 0;
for (int i = 0; i < flowerPack.length; i++)
{
Flower flower = flowerPack[i];
if (flower == null)
{
continue;
}
int nameIndex = -1;
for (int j = 0; j < usedNamesCount; j++)
{
String usedName = usedNames[j];
if (flower.getFlowerName().equals(usedName))
{
nameIndex = j;
break;
}
}
if (nameIndex != -1)
{
nameCounts[nameIndex] += 1;
}
else
{
usedNames[usedNamesCount] = flower.getFlowerName();
nameCounts[usedNamesCount] += 1;
usedNamesCount++;
}
}
for (int i = 0; i < usedNamesCount; i++)
{
System.out.println(usedNames[i] + "s - " + nameCounts[i]);
}
}

ArrayList empties out when moving to another class

completely basic java student here. I am having a problem with my project for AP Comp sci in which when I create an object for my cartClass in my MenuClass, I get this very long list of errors(repeats these lines over and over):
Exception in thread "main" java.lang.StackOverflowError
at ICSMenuClass.<init>(ICSMenuClass.java:27)
at ICSCartClass.<init>(ICSCartClass.java:20)
Now my other concern is the fact that when I add elements to my item and itemprice ArrayLists, they arnt stored in the ArrayList when I go to my cart class(The code is VERY messy, also im only adding items to the 'item' and 'itemprice' ArrayLists):
import java.util.*;
public class ICSMenuClass extends Objclass{
// public static void main(String[] args)
// {
//
// ICSMenuClass i1 = new ICSMenuClass();
// System.out.println(i1);
// }
ArrayList<String> ItemName = new ArrayList<String>();
ArrayList<Double> ItemPrice = new ArrayList<Double>();
public ArrayList<String> item = new ArrayList<String>();
public ArrayList<Double> itemprice = new ArrayList<Double>();
ICSCartClass icsc2 = new ICSCartClass();
ICSMenuClass icsm2 = new ICSMenuClass();
//public ArrayList<String> item = new ArrayList<String>();
//public ArrayList<Double> itemprice = new ArrayList<Double>();
//public ICSCartClass icsc1 = new ICSCartClass();
public Scanner scan = new Scanner(System.in);
public ICSMenuClass()
{
//super(item, itemprice);
//item.add("Lemon");
// this.item = item;
// this.ItemPrice = ItemPrice;
iteminfo();
}
public void iteminfo()
{
String user = "admin";
String uselessfiller = "null";
String addItem = "addItem";
String removeItem = "removeItem";
String changePrice = "changePrice";
String gocart1 = "GoCart";
//final ArrayList<String> combined = new ArrayList<String>();
//item.addAll(itemprice);
System.out.println("Who is this?");
String userused = scan.nextLine();
String viewInventory = "SeeInventory";
if(userused.equalsIgnoreCase(user))
{
int j = 1;
while(j < 2)
{
System.out.println("Would you like to edit an item? y/n");
String answer;
String yes1 = "y";
answer = scan.nextLine();
if(answer.equals(yes1))
System.out.println("What would you like to do? (Type: addItem, removeitem, changePrice, SeeInventory, GoCart)");
//scan.nextLine();
String ans1 = scan.nextLine();
//------------------------------------------------------------------------------------------------
//Add Item
//------------------------------------------------------------------------------------------------
if(ans1.equals(addItem))
{
AddItemtoInventory();
}else{
//---------------------------------------------------------------------------------------------------------------
//Remove Items
//---------------------------------------------------------------------------------------------------------------
if(ans1.equals(removeItem))
{
RemoveItemfromInventory();
}else{
//-------------------------------------------------------------------------------------------------------------
//Change Price
//-------------------------------------------------------------------------------------------------------------
if(ans1.equals(changePrice))
{
ChangePriceofItem();
}else{
//------------------------------------------------------------------------------------------------------------------------------------
//View Inventory
//------------------------------------------------------------------------------------------------------------------------------------
if(ans1.equals(viewInventory))
{
CheckInventory();
}else{
if(ans1.equals(gocart1)){
this.item = ItemName;
this.itemprice = ItemPrice;
icsm2.GotoCart();
}else{
if(ans1 == "n"){
//AccountLogin acctlogn1 = new AccountLogin();
//System.out.println(acctlogn1);
System.out.println("Ok");
}
}
} }}}}}
}
//Adding item to inventory
public void AddItemtoInventory()
{
System.out.println("Ok, how many items would you like to add?");
int i = 1;
int desireditemnumb1 = scan.nextInt();
while (i <= desireditemnumb1)
{
String filler1 = "null";
String useless1 = scan.nextLine();
useless1 = filler1;
System.out.println("Ok, enter item #" + i + " and the ISBN number after it.");
String itemname = scan.nextLine();
item.add(itemname);
System.out.println("Please add a price to the item: ");
Double itemprice1 = scan.nextDouble();
itemprice.add(itemprice1);
// System.out.println("Please set the amount of the item to add to the inventory: ");
// int i2 = scan.nextInt();
// for(int j = 0; j < i2; j++)
// {
// invAmount.add(itemname);
// }
System.out.println("Added " + itemname + " to inventory");
i++;
}
System.out.println("would you like to see your inventory?");
scan.nextLine();
String seeinventory1 = scan.nextLine();
if(seeinventory1.equals("y"))
{
System.out.println(item + "\n" + itemprice);
}else{
System.out.println("Ok...");
}
}
//Removing item method
public void RemoveItemfromInventory()
{
System.out.println("Ok, how many items would you like to remove?");
int i = 1;
int desireditemnumb1 = scan.nextInt();
while(i <= desireditemnumb1)
{
System.out.println("Ok, type the number which the item is allocated");
System.out.println(item);
int index1 = scan.nextInt();
item.remove(index1);
itemprice.remove(index1);
System.out.println("Removed " + item.get(index1) + " from inventory");
i++;
}
String yes1 = "y";
System.out.println("Would you like to see your inventory?");
String yes2 = scan.nextLine();
if(yes2.equals(yes1))
System.out.println(item + "\n" + itemprice);
}
public void ChangePriceofItem()
{
System.out.println("Ok, type the number which the item is allocated");
System.out.println(item);
int index1 = scan.nextInt();
System.out.println("Ok, now choose the price the item will cost");
double itemprice1 = scan.nextDouble();
itemprice.set(index1, itemprice1);
System.out.println("Changed price of " + item.get(index1) + " within inventory");
}
public void CheckInventory()
{
System.out.println(item + "\n" + itemprice + "\n" + invAmount);
double sum = 0;
for (double i : itemprice)
sum += i;
System.out.println("The value of the inventory: " + "$" + sum);
}
public void GotoCart()
{
System.out.println(icsc2);
}
}
And my cart class:
import java.util.*;
public class ICSCartClass extends ICSMenuClass{
public Scanner scan = new Scanner(System.in);
public ArrayList<Double> ItemPrice1 = new ArrayList<Double>();
// public static void main(String[] args)
// {
//
//
// ICSCartClass c1 = new ICSCartClass();
// System.out.println(c1);
// }
public ICSCartClass()
{
//super(item, itemprice);
addItemDefaults();
}
public void addItemDefaults()
{
ItemName.addAll(item);
ItemPrice.addAll(itemprice);
WhatDoCart();
}
public void WhatDoCart()
{
System.out.println("What do you want to do with the cart? ");
System.out.println("Plese choose the number that shows what you want to do: ");
System.out.println("Add an item = 1" + "\t\t" + "Remove an item = 2" + "\t" + "Exchange an item = 3" + "\t" + "Checkout cart = 4");
int cartans1 = scan.nextInt();
if(cartans1 == 1)
AddItemstoCart();
if(cartans1 == 2)
RemoveItemsfromCart();
if(cartans1 == 3)
ExcangeItemsinCart();
if(cartans1 == 4)
CheckoutCartNow();
}
public void AddItemstoCart()
{
int i = -1;
while(i < cart.size())
{
System.out.println("What item do you want to add? Press 9 to checkout.");
System.out.println(ItemName + "\n" + ItemPrice1);
int ItemAns1 = scan.nextInt();
if(ItemAns1 == 9)
{
WhatDoCart();
}else{
String Itemname2 = item.get(ItemAns1);
int index1 = item.indexOf(ItemAns1);
double getprice = itemprice.indexOf(index1);
cartPrice.add(getprice);
cart.add(Itemname2);
System.out.println(cart);
i++;
}
}
}
public void RemoveItemsfromCart()
{
int i = -1;
while(i < cart.size())
{
System.out.println("What item do you want to remove (You must have at least 2 items for checkout)? Press 9 to checkout.");
System.out.println(cart);
int ItemAns1 = scan.nextInt();
if(ItemAns1 == 9)
{
WhatDoCart();
}else{
String Itemname2 = cart.get(ItemAns1);
cart.remove(Itemname2);
int index1 = cartPrice.indexOf(ItemAns1);
cartPrice.remove(index1);
System.out.println(cart);
i++;
}
}
}
public void ExcangeItemsinCart()
{
int i = -1;
while(i < cart.size())
{
System.out.println("What item do you want to exchange? Press 9 to checkout.");
System.out.println(ItemName);
int ItemAns1 = scan.nextInt();
if(ItemAns1 == 9)
{
WhatDoCart();
}else{
String Itemname2 = ItemName.get(ItemAns1);
cart.set(ItemAns1, Itemname2);
System.out.println(cart);
i++;
}
}
}
public void CheckoutCartNow()
{
System.out.println(" Do you want to check out the cart now? y/n");
scan.nextLine();
String Ans1 = scan.nextLine();
if(Ans1 == "y")
{
CarttoString();
}else{
if(Ans1 == "n")
{
WhatDoCart();
}
}
}
public void CarttoString()
{
cart.clear();
//ItemAmount.add(ItemPrice);
}
}
Another error I have is when I want to got to the cart class, it takes me back to the beginning of the itemInfo() method, and I have to type anything but "Admin" in there to go to the cartClass.
Thank you for you help, and sorry about the long code, i'm not good at cropping what I need. Also, I want to know how to get my item/itemprice ArrayLists keep their elements when I go to the cart class. Thank you!
Ok, so I've done some fixes to it, but it still goes back to asking: "Who is this?" after I type GoCart. Plus the array still shows up empty.
public void iteminfo()
{
String user = "admin";
// String addItem = "addItem";
// String removeItem = "removeItem";
// String changePrice = "changePrice";
// String gocart1 = "GoCart";
//final ArrayList<String> combined = new ArrayList<String>();
//item.addAll(itemprice);
System.out.println("Who is this?");
String userused = scan.nextLine();
String viewInventory = "SeeInventory";
if(userused.equalsIgnoreCase(user))
{
int j = 1;
while(j < 2)
{
System.out.println("Would you like to edit an item? y/n");
String answer;
//String yes1 = "y";
answer = scan.nextLine();
if(answer.equals("y"))
System.out.println("What would you like to do? (Type: addItem, removeitem, changePrice, SeeInventory, GoCart)");
//scan.nextLine();
String ans1 = scan.nextLine();
//------------------------------------------------------------------------------------------------
//Add Item
//------------------------------------------------------------------------------------------------
if(ans1.equals("addItem"))
{
AddItemtoInventory();
}else{
//---------------------------------------------------------------------------------------------------------------
//Remove Items
//---------------------------------------------------------------------------------------------------------------
if(ans1.equals("removeItem"))
{
RemoveItemfromInventory();
}else{
//-------------------------------------------------------------------------------------------------------------
//Change Price
//-------------------------------------------------------------------------------------------------------------
if(ans1.equals("changePrice"))
{
ChangePriceofItem();
}else{
//------------------------------------------------------------------------------------------------------------------------------------
//View Inventory
//------------------------------------------------------------------------------------------------------------------------------------
if(ans1.equals("SeeInventory"))
{
CheckInventory();
}else{
if(ans1.equals("GoCart")){
j++;
this.item = ItemName;
this.itemprice = ItemPrice;
GotoCart();
}else{
if(ans1 == "n"){
//AccountLogin acctlogn1 = new AccountLogin();
//System.out.println(acctlogn1);
System.out.println("Ok");
break;
}
}
}
}
}
}
}
}
}
When you are initializing your J in the iteminfo() method ICSMenuClass. You are not decrementing it in your function any where. Which means that your loop would never end while(j < 2) would always be true.
There are many useless variables declared which makes it hard to understand the flow, e.g.
String yes1 = "y";
You can do if(answer.equals("y")) to avoid the extra variable being declared.

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

Scanner carriage return Overflow

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.

Categories

Resources