I've implemented a boolean to a kennel system I'm developing in Java and I'm getting an InputMismatchError when loading the data from the file.
I've read through a few times and tried to work it out but the solutions I'm trying aren't working. So far I've:
restructured the read in method (initialise) to read the data in properly and in the correct order, then assign it the newPet (local variable) in the correct order.
I then read through the .txt file (below) and made sure everything corresponded the the correct data, strings are being read as strings, ints as ints etc and that hasn't helped.
Can anybody spot the problem that's through the InputMismatch here?
Here is the error:
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextBoolean(Unknown Source)
at KennelDemo.initialise(KennelDemo.java:79)
at KennelDemo.main(KennelDemo.java:337)
with line 79 and 337 being:
boolean mutualBoolean = infile.nextBoolean(); //and
demo.initialise();
Main class (apologises for the length)
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Scanner;
public class KennelDemo {
private String filename; // holds the name of the file
private Kennel kennel; // holds the kennel
private Scanner scan; // so we can read from keyboard
private String tempFileName;
private String dogsFile = "dogs.txt";
private String catsFile = "cats.txt";
/*
* Notice how we can make this private, since we only call from main which
* is in this class. We don't want this class to be used by any other class.
*/
private KennelDemo() {
scan = new Scanner(System.in);
boolean fileCorrect = false;
do {
System.out.print("Which animal are you looking to check into the kennel?: " + "\n");
System.out.println("Dog");
System.out.println("Cat");
tempFileName = scan.next();
if(tempFileName.toLowerCase().equals("dog") || tempFileName.toLowerCase().equals("cat")) {
filename = tempFileName.toLowerCase().equals("dog") ? dogsFile : catsFile;
fileCorrect = true;
}
else {
System.out.println("That is not a valid filename, please enter either 'Dog' or 'cat' in lowercase.");
}
}
while(!fileCorrect);
}
/*
* initialise() method runs from the main and reads from a file
*/
private void initialise() {
kennel = new Kennel();
System.out.println("Using file " + filename);
// Using try-with-resource (see my slides from session 15)
try(FileReader fr = new FileReader(filename);
BufferedReader br = new BufferedReader(fr);
Scanner infile = new Scanner(br)){
String kennelName = infile.nextLine();
int kennelSize = infile.nextInt();
infile.nextLine();
kennel.setCapacity(kennelSize);
int numPets = infile.nextInt();
infile.nextLine();
kennel.setName(kennelName);
for(int i=0; i < numPets; i++){
String PetName = infile.nextLine();
int numOwners = infile.nextInt();
infile.nextLine();
ArrayList<Owner> owners = new ArrayList<>();
for(int oCount=0; oCount < numOwners; oCount++){
String name = infile.nextLine();
String phone = infile.nextLine();
Owner owner = new Owner(name, phone);
owners.add(owner);
}
boolean mutualBoolean = infile.nextBoolean();
infile.nextLine();
String favFood = infile.nextLine();
infile.nextLine();
int feedsPerDay = infile.nextInt();
Pet Pet = new Pet(PetName, owners, mutualBoolean, favFood, feedsPerDay);
kennel.addPet(Pet);
}
} catch (FileNotFoundException e) {
System.err.println("The file: " + " does not exist. Assuming first use and an empty file." +
" If this is not the first use then have you accidentally deleted the file?");
} catch (IOException e) {
System.err.println("An unexpected error occurred when trying to open the file " + filename);
System.err.println(e.getMessage());
}
}
/*
* runMenu() method runs from the main and allows entry of data etc
*/
private void runMenu() {
String response;
do {
printMenu();
System.out.println("What would you like to do:");
scan = new Scanner(System.in);
response = scan.nextLine().toUpperCase();
switch (response) {
case "1":
admitPet();
break;
case "2":
changeKennelName();
break;
case "3":
printPetsWithBones();
break;
case "4":
searchForPet();
break;
case "5":
removePet();
break;
case "6":
setKennelCapacity();
break;
case "7":
printAll();
break;
case "Q":
break;
default:
System.out.println("Try again");
}
} while (!(response.equals("Q")));
}
private void setKennelCapacity() {
// set the boolean to check if the user REALLY wants to change the kennel size. We can never be too careful.
// boolean doContinue = false;
// Turns out the boolean does nothing, go figure.
// Still the error check works perfectly, now just a case of losing the temporary data if the program isn't closed through the menu.
// Kennel currently doesn't save until you use "q" at the menu to save the information. Possible solutions?
// Hello? Is this thing on?
int currentKennelCapacity = kennel.getCapacity();
System.out.println("The current kennel holds " + currentKennelCapacity + ", are you sure you want to change the current kennel size?");
String userWantsToContinue;
userWantsToContinue = scan.nextLine().toUpperCase();
if(userWantsToContinue.equals("Y")){
// doContinue = true;
System.out.print("Please enter the new size of the kennel you'd like: ");
int max = scan.nextInt();
scan.nextLine();
kennel.setCapacity(max);
System.out.println("The new kennel size is " + max + ", we'll now return you to the main menu. Please make sure the quit the program at the end of your session to save any changes. \n");
}
else System.out.println("No problem, we'll return you back to the main menu. \n");
//Duplicate code that caused an error when running through the conditions above, saved in case of future reference.
/* System.out.print("Enter max number of Pets: ");
int max = scan.nextInt();
scan.nextLine();
kennel.setCapacity(max);
*/
}
private void printPetsWithBones() {
Pet[] PetsWithBones = kennel.obtainDogsWhoLikeBones();
System.out.println("Pets with bones: ");
for (Pet d: PetsWithBones){
System.out.println("Pet name: " + d.getName());
}
}
/*
* printAll() method runs from the main and prints status
*/
private void printAll() {
Pet[] allPets = kennel.displayAllPets();
for (Pet p: allPets){
System.out.println("Animal name: " + p.getName());
System.out.println("Original owner(s): " + p.getOriginalOwners());
if(filename.equals(dogsFile)){
System.out.println("Do they like bones? " + Dog.getLikesBones());
}
else if(filename.equals(catsFile)){
System.out.println("Can they share a run? " + Cat.getShareRun());
}
System.out.println("Favourite food: " + p.getFavouriteFood());
System.out.println("Feeds per day: " + p.getFeedsPerDay());
System.out.println("====================================");
}
}
/*
* save() method runs from the main and writes back to file
*/
private void save() {
try(FileWriter fw = new FileWriter(filename);
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter outfile = new PrintWriter(bw);){
outfile.println(kennel.getName());
outfile.println(kennel.getCapacity());
outfile.println(kennel.getNumOfPets());
Pet[] Pets = kennel.obtainAllPets();
for (Pet d: Pets){
outfile.println(d.getName());
Owner[] owners = d.getOriginalOwners();
outfile.println(owners.length);
for(Owner o: owners){
outfile.println(o.getName());
outfile.println(o.getPhone());
}
// TODO outfile.println(d.getLikesBones());
outfile.println(d.getFeedsPerDay());
outfile.println(d.getFavouriteFood());
}
} catch (IOException e) {
System.err.println("Problem when trying to write to file: " + filename);
}
}
private void removePet() {
System.out.println("which Pet do you want to remove");
String Pettoberemoved;
Pettoberemoved = scan.nextLine();
kennel.removePet(Pettoberemoved);
}
private void searchForPet() {
String allNames = kennel.getName();
System.out.println("Current pet in the kennel: " + allNames + "\n");
System.out.println("Which pet would you like to get the details for?");
String name = scan.nextLine();
Pet Pet = kennel.search(name);
if (Pet != null){
System.out.println(Pet.toString());
} else {
System.out.println("Could not find Pet: " + name);
}
}
private void changeKennelName() {
String name = scan.nextLine();
kennel.setName(name);
}
private void admitPet() {
boolean mutualBoolean = false;
if(filename.equals(dogsFile)){
System.out.println("enter on separate lines: name, owner-name, owner-phone, do they like bones?, favourite food, number of times fed");
}
else if(filename.equals(catsFile)){
System.out.println("enter on separate lines: name, owner-name, owner-phone, can they share a run?, favourite food, number of times fed");
}
String name = scan.nextLine();
ArrayList<Owner> owners = getOwners();
if(filename.equals(dogsFile)){
System.out.println("Does he like bones? (Y/N)");
}
else if(filename.equalsIgnoreCase(catsFile)){
System.out.println("Can the cat share a run? (Y/N)");
}
String booleanCheck;
booleanCheck = scan.nextLine().toUpperCase();
if (booleanCheck.equals("Y")) {
mutualBoolean = true;
}
System.out.println("What is his/her favourite food?");
String fav;
fav = scan.nextLine();
System.out.println("How many times is he/she fed a day? (as a number)");
int numTimes;
numTimes = scan.nextInt(); // This can be improved (InputMismatchException?)
numTimes = scan.nextInt();
Pet newPet = new Pet(name, owners, mutualBoolean, fav, numTimes);
kennel.addPet(newPet);
System.out.println("Pet " + newPet.getName() + " saved.");
// Save when you add new Pet in case the program isn't closed via the correct menu.
// Everything will still save when case "q" is used though.
save();
}
private ArrayList<Owner> getOwners() {
ArrayList<Owner> owners = new ArrayList<Owner>();
String answer;
do {
System.out
.println("Enter on separate lines: owner-name owner-phone");
String ownName = scan.nextLine();
String ownPhone = scan.nextLine();
Owner own = new Owner(ownName, ownPhone);
owners.add(own);
System.out.println("Another owner (Y/N)?");
answer = scan.nextLine().toUpperCase();
} while (!answer.equals("N"));
return owners;
}
private void printMenu() {
if(filename.equals(catsFile)) {
System.out.println("1 - add a new cat ");
System.out.println("2 - set up Kennel name");
System.out.println("4 - search for a cat");
System.out.println("5 - remove a cat");
System.out.println("6 - set kennel capacity");
System.out.println("7 - print all cats");
System.out.println("q - Quit");
}
else if(filename.equals(dogsFile)) {
System.out.println("1 - add a new dog ");
System.out.println("2 - set up Kennel name");
System.out.println("3 - print all dogs who like bones");
System.out.println("4 - search for a dog");
System.out.println("5 - remove a dog");
System.out.println("6 - set kennel capacity");
System.out.println("7 - print all dogs");
System.out.println("q - Quit");
}
}
// /////////////////////////////////////////////////
public static void main(String args[]) {
System.out.println("**********HELLO***********");
KennelDemo demo = new KennelDemo();
demo.initialise();
demo.runMenu();
demo.printAll();
demo.save();
System.out.println("***********GOODBYE**********");
}
}
and here is the .txt file being read from:
DogsRUs // kennel name
20 // capacity
3 // number of pets
Rover //pet name
2 // number of owners
Chris Loftus // first owner
1234 // phone number
Pete Hoskins // second owner
2222 // phone number
1 // boolean for mutualBoolean
biscuits // favourite food
// NOTE: for some reason favFood wasn't being added but it wasn't causing an error at all, it's the boolean that's throwing the input error. Structure above repeats for the data below.
Dinky
1
James Bond
007007
1
Gold fingers
catTest
1
Billy
456789
1
Curry
Clearly the problem is the boolean being read in but I really can't see the solution to it at all unfortunately. When mutualBoolean was likeBones (originally the program was only being used to check dogs in rather than dogs and cats) it was working fine.
Here is the code I've used to inherit for the mutualBoolean that's being used
import java.util.ArrayList;
public class Pet {
protected ArrayList<Owner> originalOwners;
protected boolean mutualBoolean;
protected String petName;
protected String favFood;
protected int foodPerDay;
public Pet(String name, ArrayList<Owner> owners, boolean mutualBoolean, String food, int mealsPerDay) {
petName = name;
this.favFood = food;
this.foodPerDay = mealsPerDay;
originalOwners = new ArrayList<Owner>();
for(Owner o: owners){
Owner copy = new Owner(o.getName(), o.getPhone());
originalOwners.add(copy);
}
this.mutualBoolean = mutualBoolean;
}
public String getName() {
return petName;
}
public void setName(String newName) {
petName = newName;
}
/*protected boolean mutualBoolean() {
return mutualBoolean;
}*/
/**
* Returns a copy of the original owners
* #return A copy of the original owners as an array
*/
public Owner[] getOriginalOwners(){
Owner[] result = new Owner[originalOwners.size()];
result = originalOwners.toArray(result);
return result;
}
/**
* How many times a day to feed the dog
* #param feeds The number of feeds per day
*/
public void setFeedsPerDay(int feeds){
foodPerDay = feeds;
}
/**
* The number of feeds per day the dog is fed
* #return The number of feeds per day
*/
public int getFeedsPerDay(){
return foodPerDay;
}
/**
* What's his favourite food?
* #param food The food he likes
*/
public void setFavouriteFood(String food){
favFood = food;
}
/**
* The food the dog likes to eat
* #return The food
*/
public String getFavouriteFood(){
return favFood;
}
/**
* Note that this only compares equality based on a
* dog's name.
* #param The other dog to compare against.
*/
#Override
public boolean equals(Object obj) { // Generated by Eclipse to be more robust
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Dog other = (Dog) obj;
if (petName == null) {
if (other.petName != null)
return false;
} else if (!petName.equals(other.petName))
return false;
return true;
}
/**
* A basic implementation to just return all the data in string form
*/
public String toString() {
return "Dog name:" + petName + "Original Owner:" + originalOwners + "Favfood:" + favFood
+ "FoodPerDay:" + foodPerDay;
}
}
and the Dog class
import java.util.ArrayList;
public class Dog extends Pet {
public static boolean likesBones;
public Dog(String name, ArrayList<Owner> owners, String food, int mealsPerDay, boolean likeBones) {
super(name, owners, likeBones, food, mealsPerDay);
Dog.likesBones = likeBones;
}
/**
* Does the dog like bones?
* #return true if he does
*/
public static boolean getLikesBones() {
return likesBones;
}
}
Related
I am working on a text-based adventure game and need some help handling the IndexOutOfBounds exception on the getUserRoomChoice() function. I have an index of 3 on the menu so when the user enters a number > 3, it throws that exception. I tried using a try-catch on the line where it prompts the user to "Select a Number" but it is not catching it.
Here is my main class:
import java.util.Scanner;
public class Game {
private static Room library, throne, study, kitchen;
private static Room currentLocation;
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
initialSetupGame();
String reply;
do {
printNextRooms();
int nextRoomIndex = getUserRoomChoice();
Room nextRoom = getNextRoom(nextRoomIndex);
updateRoom(nextRoom);
System.out.print("Would you like to continue? Yes/No: ");
reply = input.nextLine().toLowerCase();
} while ('y' == reply.charAt(0));
goodbye();
}
public static void initialSetupGame() {
// Instantiate room objects of type Room
library = new Room("Library");
throne = new Room("Throne");
study = new Room("Study");
kitchen = new Room("Kitchen");
// Connect the objects to each other
library.addConnectedRoom(throne);
library.addConnectedRoom(study);
library.addConnectedRoom(kitchen);
throne.addConnectedRoom(library);
throne.addConnectedRoom(study);
throne.addConnectedRoom(kitchen);
study.addConnectedRoom(library);
study.addConnectedRoom(throne);
study.addConnectedRoom(kitchen);
kitchen.addConnectedRoom(library);
kitchen.addConnectedRoom(study);
kitchen.addConnectedRoom(throne);
// Welcome message
System.out.println("Welcome to Aether Paradise, "
+ "a game where you can explore"
+ " the the majestic hidden rooms of Aether.");
// Prompt user for a name
Scanner input = new Scanner(System.in);
System.out.print("\nBefore we begin, what is your name? ");
String playerName = input.nextLine();
System.out.print("\n" + playerName +"? Ah yes. The Grand Warden told us"
+ " to expect you. Nice to meet you, " + playerName + "."
+ "\nMy name is King, a member of the Guardian Aethelorian 12"
+ " who protect the sacred rooms of Aether."
+ "\nAs you hold the Warden's signet ring, you have permission"
+ " to enter.\n\nAre you ready to enter? ");
String response = input.nextLine().toLowerCase();
if ('n' == response.charAt(0)) {
System.out.println("Very well then. Goodbye.");
System.exit(0);
}
if ('y' == response.charAt(0)) {
System.out.println("\nA shimmering blue portal appeared! You leap "
+ "inside it and your consciousness slowly fades...");
}
else {
System.out.println("Invalid input. Please try again.");
System.exit(1);
}
// Set the player to start in the library
currentLocation = library;
System.out.print("\nYou have spawned at the library.");
System.out.println(currentLocation.getDescription());
}
public static void printNextRooms() {
// Lists room objects as menu items
System.out.println("Where would you like to go next?");
currentLocation.printListOfNamesOfConnectedRooms();
}
// How to handle the exception when input > index?
public static int getUserRoomChoice() {
Scanner input = new Scanner(System.in);
System.out.print("(Select a number): ");
int choice = input.nextInt();
return choice - 1;
}
public static Room getNextRoom(int index) {
return currentLocation.getConnectedRoom(index);
}
public static void updateRoom(Room newRoom) {
currentLocation = newRoom;
System.out.println(currentLocation.getDescription());
}
public static void goodbye() {
System.out.println("You walk back to the spawn point and jump into"
+ "the portal... \n\nThank you for exploring the hidden rooms "
+ "of Aether Paradise. Until next time.");
}
}
Room Class
import java.util.ArrayList;
public class Room {
// Instance variables
private String name;
private String description;
private ArrayList<Room> connectedRooms;
// Overloaded Constructor
public Room(String roomName) {
this.name = roomName;
this.description = "";
connectedRooms = new ArrayList<>();
}
// Overloaded Constructor
public Room(String roomName, String roomDescription) {
this.name = roomName;
this.description = roomDescription;
connectedRooms = new ArrayList<>();
}
// Get room name
public String getName() {
return name;
}
// Get room description
public String getDescription() {
return description;
}
// Add connected room to the array list
public void addConnectedRoom(Room connectedRoom) {
connectedRooms.add(connectedRoom);
}
// Get the connected room from the linked array
public Room getConnectedRoom(int index) {
if (index > connectedRooms.size()) {
try {
return connectedRooms.get(index);
} catch (Exception ex) {
System.out.println(ex.toString());
}
}
return connectedRooms.get(index);
}
// Get the number of rooms
public int getNumberOfConnectedRooms() {
return connectedRooms.size();
}
// Print the connected rooms to the console
public void printListOfNamesOfConnectedRooms() {
for(int index = 0; index < connectedRooms.size(); index++) {
Room r = connectedRooms.get(index);
String n = r.getName();
System.out.println((index + 1) + ". " + n);
}
}
}
You have to use try-catch in function call of getNextRoom().
Because getNextRoom(nextRoomIndex) is causing the exception. You have to put those two statements in try block.
Change this to
Room nextRoom = getNextRoom(nextRoomIndex);
updateRoom(nextRoom);
this
try{
Room nextRoom = getNextRoom(nextRoomIndex);
updateRoom(nextRoom);
} catch(Exception e){
System.out.println("print something");
}
You must have a closer look to the piece of code, where you try to access the list (or array). That is the part, where the exception is thrown, not when the user enters it. There you have to check, if the given index is larger than the size of your list.
if( index >= list.size()) {
// handle error / print message for user
} else {
// continue normaly
}
In your case, it would probably be in the method getConnectedRoom(int index) in class Room.
Where is your try/catch block for the specific part? anyway, you can use IndexOutOfBound or Custome Exception for it.
1.create a custom Exception Class
class RoomeNotFoundException extends RuntimeException
{
public RoomeNotFoundException(String msg)
{
super(msg);
}
}
add try/catch block for the specific part
public class Game
{
do {
printNextRooms();
int nextRoomIndex = getUserRoomChoice();
if(nextRoomeIndex>3)
{
throw new RoomNotFoundException("No Rooms Available");
}else{
Room nextRoom = getNextRoom(nextRoomIndex);
updateRoom(nextRoom);
System.out.print("Would you like to continue? Yes/No: ");
reply = input.nextLine().toLowerCase();
}
} while ('y' == reply.charAt(0));
}
Or you can use IndexOutOfBoundException instead of RoomNotFoundException
I have an ArrayList that is being filled with customer information using a Customer class. In my addCustomerRecord method, I am calling findAddIndex within the addCustomerRecord method so the data entered will be sorted prior to displaying the data. Here is my code and do not mind the fileWhatever method, I don't use it.
public class CustomerDemo
{
//arrayList of customer objects
public static ArrayList<Customer> customerAL = new ArrayList<>();
public static void main (String[] args)
{
//to hold menu choice
String menuChoice = "";
Scanner kb = new Scanner(System.in);
System.out.println("To add a record press 'A': \n"
+ "to display all records press 'D': \n"
+ "to exit press 'Q': \n");
//loop priming read
menuChoice = kb.nextLine();
//make input case insensitive
menuChoice = menuChoice.toLowerCase();
do
{
if(menuChoice.equals("a"))
addCustomerRecord(kb);
else if(menuChoice.equals("d"))
{
displayCustomerRecords();
}
else if(menuChoice.equals("q"))
{
System.out.println("Program exiting..");
System.exit(0);
}
else
{
System.out.println("incorrect entry. Please re-enter a valid entry: \n");
menuChoice = kb.nextLine();
menuChoice = menuChoice.toLowerCase();
}
System.out.println("To add a record press 'A': \n"
+ "to display all records press 'D': \n"
+ "to exit press 'Q': \n");
menuChoice = kb.nextLine();
menuChoice = menuChoice.toLowerCase();
}while(menuChoice.equals("a") || menuChoice.equals("d") || menuChoice.equals("q"));
kb.close();
}
/* public static void displayCustomerRecords()
{
System.out.println();
for (int i = 0; i < customerAL.size(); ++i)
{
System.out.printf("%-15s", customerAL.get(i).getLastName());
System.out.printf("%-15s", customerAL.get(i).getFirstName());
System.out.printf("%-6s", customerAL.get(i).getCustID());
System.out.printf("%15s\n", customerAL.get(i).getPhoneNumber());
}
System.out.println();
}
/**
* prompts to enter customer data and mutator methods called
* with a Scanner object passed as an argument to set data
* #param location index position of where the element will be added.
* #param kb a Scanner object to accept input
*/
public static void addCustomerRecord(Scanner kb)
{
Customer currentCustomerMemoryAddress = new Customer();
System.out.println("Enter first name: \n");
String fName = kb.nextLine();
currentCustomerMemoryAddress.setFirstName(fName);
System.out.println("Enter last name: \n");
String lName = kb.nextLine();
currentCustomerMemoryAddress.setLastName(lName);
System.out.println("Enter customer phone number: \n");
String pNum = kb.nextLine();
currentCustomerMemoryAddress.setPhoneNumber(pNum);
System.out.println("Enter customer ID number: \n");
String ID = kb.nextLine();
currentCustomerMemoryAddress.setCustID(ID);
int addLocation = findAddLocation(currentCustomerMemoryAddress);
customerAL.add(addLocation, currentCustomerMemoryAddress);
currentCustomerMemoryAddress = null;
}
public static int findAddLocation(Customer cust)
{
int location = 0;
if(!customerAL.isEmpty())
{
for(int i = 0; i < customerAL.size(); i++)
{
//Stumped here
}
}
else
return location;
return location;
}
}
It looks like you are reinventing the wheel here William
Replace your code for displayCustomerRecords with this:
public static void displayCustomerRecords()
{
System.out.println();
customerAL.stream().map(c -> String.format("%-15s%-15s%-6s%15s\n",
c.getLastName(), c.getFirstName(), c.getCustID(), c.getPhoneNumber()))
.sorted()
.forEach(System.out::print);
System.out.println();
}
Update
Taking into account your comment you can replace your findAddLocationmethod by the following:
private static Comparator<Customer> comparator = Comparator.comparing(Customer::getLastName)
.thenComparing(Customer::getFirstName)
.thenComparing(Customer::getCustID)
.thenComparing(Customer::getPhoneNumber);
public static int findAddLocation(Customer cust)
{
int location = 0;
if(!customerAL.isEmpty())
{
for(Customer customerInList : customerAL)
{
if(comparator.compare(customerInList, cust) > 0) {
break;
}
location++;
}
}
return location;
}
We are traversing the array using Java's enhanced for-loop and comparing the objects using a Java 8 declared comparator (which I believe is the key to this assignment).
It would be a good idea if you could look into the Comparable interface and implement it in your Customer class. That way you could simply do a simple call to customerInList.compareTo(cust) to compare both objects.
As already stated, this is not a good practice and shouldn't be used in production code.
I'm trying to create an array of math students, science students, and computer students based on the user input.
So basically the user should choose what student they want to add and then enter the student details.
Below I have added the code I have so far:
Main Java class:
public class Lab4 {
public static final int DEBUG = 0;
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Student s[] = new Student[10];
s[0] = new MathStudent(4,5);
s[1] = new MathStudent(5,7);
s[2] = new MathStudent(2,8);
s[3] = new MathStudent(3,6);
s[4] = new ScienceStudent(8,9);
s[5] = new ScienceStudent(3,6);
s[6] = new ScienceStudent(4,9);
s[7] = new ComputerStudent(6,12);
s[8] = new ComputerStudent(11,14);
s[9] = new ComputerStudent(13,17);
}
}
Student class:
public class Student {
private String name;
private int age;
public String gender = "na";
public static int instances = 0;
// Getters
public int getAge(){
return this.age;
}
public String getName(){
return this.name;
}
// Setters
public void setAge(int age){
this.age = age;
}
public void setName(String name){
if (Lab4.DEBUG > 3) System.out.println("In Student.setName. Name = "+ name);
this.name = name;
}
/**
* Default constructor. Populates name,age,gender,course and phone Number
* with defaults
*/
public Student(){
instances++;
this.age = 18;
this.name = "Not Set";
this.gender = "Not Set";
}
/**
* Constructor with parameters
* #param age integer
* #param name String with the name
*/
public Student(int age, String name){
this.age = age;
this.name = name;
}
/**
* Gender constructor
* #param gender
*/
public Student(String gender){
this(); // Must be the first line!
this.gender = gender;
}
/**
* Destructor
* #throws Throwable
*/
protected void finalize() throws Throwable{
//do finalization here
instances--;
super.finalize(); //not necessary if extending Object.
}
public String toString (){
return "Name: " + this.name + " Age: " + this.age + " Gender: "
+ this.gender;
}
public String getSubjects(){
return this.getSubjects();
}
}
MathStudent class:
public class MathStudent extends Student {
private float algebraGrade;
private float calculusGrade;
public MathStudent(float algebraGrade, float calculusGrade) {
this.algebraGrade = algebraGrade;
this.calculusGrade = calculusGrade;
}
public MathStudent() {
super();
algebraGrade = 6;
calculusGrade = 4;
}
// Getters
public void setAlgebraGrade(float algebraGrade){
this.algebraGrade = algebraGrade;
}
public void setCalculusGrade(float calculusGrade){
this.calculusGrade = calculusGrade;
}
// Setters
public float getAlgebraGrade() {
return this.algebraGrade;
}
public float getCalculusGrade() {
return this.calculusGrade;
}
/**
* Display information about the subject
* #return
*/
#Override
public String getSubjects(){
return("Algebra Grade: " + algebraGrade + " Calculus Grade: "
+ calculusGrade);
}
}
scienceStudent class:
public class ScienceStudent extends Student {
private float physicsGrade;
private float astronomyGrade;
/**
* Default constructor
*/
public ScienceStudent() {
super();
physicsGrade = 6;
astronomyGrade = 7;
}
public ScienceStudent(float physicsGrade, float astronomyGrade) {
this.physicsGrade = physicsGrade;
this.astronomyGrade = astronomyGrade;
}
// Getters
public void setPhysicsGrade(float physicsGrade){
this.physicsGrade = physicsGrade;
}
public void setAstronomyGrade(float astronomyGrade){
this.astronomyGrade = astronomyGrade;
}
// Setters
public float getPhysicsGrade() {
return this.physicsGrade;
}
public float getAstronomyGrade() {
return this.astronomyGrade;
}
/**
* Display information about the subject
* #return
*/
#Override
public String getSubjects(){
return("Physics Grade: " + physicsGrade + " Astronomy Grade: "
+ astronomyGrade);
}
}
computerStudent class:
public class ComputerStudent extends Student {
private float fortanGrade;
private float adaGrade;
/**
* Default constructor
*/
public ComputerStudent() {
super();
fortanGrade = 4;
adaGrade = 9;
}
public ComputerStudent(float fortanGrade, float adaGrade) {
this.fortanGrade = fortanGrade;
this.adaGrade = adaGrade;
}
// Getters
public void setFortanGrade(float fortanGrade){
this.fortanGrade = fortanGrade;
}
public void setAdaGrade(float adaGrade){
this.adaGrade = adaGrade;
}
// Setters
public float getFortanGrade() {
return this.fortanGrade;
}
public float getAdaGrade() {
return this.adaGrade;
}
/**
* Display information about the subject
* #return
*/
#Override
public String getSubjects(){
return("Fortan Grade: " + fortanGrade + " Ada Grade: " + adaGrade);
}
}
How Would I go about this?
You can ask for the number of students with type on each input and dynamically create the object.
Here is an example
System.out.println("Enter total number of students");
int n = scannerObject.nextInt();
Student students[] = new Students[n];
for(int i=0;i<n;i++){
int type = scannerObject.nextInt();
if(type == 1)
students[i] = new MathStudent();
}
Similarly, you can write for others.
For allowing user to enter his choice as input
You can do this(interpreted by your comments)
Pseudo code -
Print:
Enter 1 for math student
Enter 2 for Science student
Enter 3 for Comp student
Input choice
Now in your code use either multiple if else or better switch statement
switch(choice){
case 1: create object of math student
break;
case 2: create object of science student
break;
case 3:create object of comp student
break;
default: if not above by default do this
}
You could use an ArrayList and switch case to make your life easier. Your code should be like this:
import java.util.ArrayList;
import java.util.Scanner;
public class Students {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
ArrayList<Student> students = new ArrayList<>();
int age;
boolean addMore = true;
String name, gender;
Student st;
while (addMore) {
System.out.print("Give lesson (Computers, Math, Science): ");
String lesson = input.nextLine();
switch (lesson) {
case "Math":
// Read student's info
System.out.print("Give student's name: ");
name = input.nextLine();
System.out.print("Give student's gender: ");
gender = input.nextLine();
System.out.print("Give student's age: ");
age = input.nextInt();
System.out.print("Give student's Algebra grade: ");
int alg = input.nextInt();
System.out.print("Give student's Calculus grade: ");
int calc = input.nextInt();
input.nextLine(); // This is needed in order to make the next input.nextLine() call work (See here: https://stackoverflow.com/questions/13102045/scanner-is-skipping-nextline-after-using-next-nextint-or-other-nextfoo )
// Create the student object and pass info
st = new MathStudent(alg, calc);
st.setName(name);
st.setAge(age);
st.gender = gender;
students.add(st); // Adding the student in the list
System.out.println(st);
System.out.println(((MathStudent) st).getSubjects());
break;
case "Science":
// Read student's info
System.out.print("Give student's name: ");
name = input.nextLine();
System.out.print("Give student's gender: ");
gender = input.nextLine();
System.out.print("Give student's age: ");
age = input.nextInt();
System.out.print("Give student's Physics grade: ");
int physics = input.nextInt();
System.out.print("Give student's Astronomy grade: ");
int astronomy = input.nextInt();
input.nextLine();// This is needed in order to make the next input.nextLine() call work (See here: https://stackoverflow.com/questions/13102045/scanner-is-skipping-nextline-after-using-next-nextint-or-other-nextfoo )
// Create the student object and pass info
st = new ScienceStudent(physics, astronomy);
st.setName(name);
st.setAge(age);
st.gender = gender;
students.add(st); // Adding the student in the list
System.out.println(st);
System.out.println(((ScienceStudent) st).getSubjects());
break;
case "Computers":
// Read student's info
System.out.print("Give student's name: ");
name = input.nextLine();
System.out.print("Give student's gender: ");
gender = input.nextLine();
System.out.print("Give student's age: ");
age = input.nextInt();
System.out.print("Give student's Fortran grade: ");
int fortran = input.nextInt();
System.out.print("Give student's Ada grade: ");
int ada = input.nextInt();
input.nextLine();// This is needed in order to make the next input.nextLine() call work (See here: https://stackoverflow.com/questions/13102045/scanner-is-skipping-nextline-after-using-next-nextint-or-other-nextfoo )
// Create the student object and pass info
st = new ComputerStudent(fortran, ada);
st.setName(name);
st.setAge(age);
st.gender = gender;
students.add(st); // Adding the student in the list
System.out.println(st);
System.out.println(((ComputerStudent) st).getSubjects());
break;
default:
System.out.println("Wrong lesson");
addMore = false;
break;
}
if (addMore) {
System.out.println("Add another student? (y/n)");
String ans = input.nextLine();
addMore = ans.equals("y");
} else {
addMore = true;
}
}
System.out.println("Students");
for (Student student : students) {
System.out.println(student);
}
}
}
The code above asks for the lesson name (Computers, Math, Science) and if it is one of them it reads all the info about the student and the grades for the corresponding lesson. It creates the objects and adds them in the list students. When all info is added, it asks the user if he/she wants to add another student and if he writes the letter y, then all these are made again, until the user answers something different than the letter y (the letter n in most cases). After these it prints all the students' info by itterating the list.
Note: I think in your code for the ComputerStudent class, you meant to name the variable fortranGrade and not fortanGrade (change it also in the getSubjects function).
Links:
Java ArrayList
Switch Case in Java
Scanner is skipping nextLine() after using next(), nextInt() or other nextFoo() methods
I hope this helped you. If you have any questions or wanted something more you can do it.
UPDATE
The code below does the same things, but it uses for loop instead of switch case, as you asked in your comment.
package students;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;
public class Lab4 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
ArrayList<Student> students = new ArrayList<>();
int age;
boolean addMore = true;
String name, gender;
Student st;
ArrayList<Class<?>> studentClasses = new ArrayList<>();
studentClasses.add(MathStudent.class);
studentClasses.add(ComputerStudent.class);
studentClasses.add(ScienceStudent.class);
while (addMore) {
System.out.print("Give lesson (Computers, Math, Science): ");
String lesson = input.nextLine();
addMore = false;
for (Class studentClass : studentClasses) {
try {
st = (Student) studentClass.newInstance();
if (st.getLessonName().equals(lesson)) {
// Read student's info
System.out.print("Give student's name: ");
name = input.nextLine();
System.out.print("Give student's gender: ");
gender = input.nextLine();
System.out.print("Give student's age: ");
age = input.nextInt();
System.out.print("Give student's " + st.getSubjectsNames()[0] + " grade: ");
float firstSubj = input.nextFloat();
System.out.print("Give student's " + st.getSubjectsNames()[1] + " grade: ");
float secondSubj = input.nextFloat();
input.nextLine(); // This is needed in order to make the next input.nextLine() call work (See here: https://stackoverflow.com/questions/13102045/scanner-is-skipping-nextline-after-using-next-nextint-or-other-nextfoo )
// Create the student object and pass info
st = (Student) studentClass.getConstructor(float.class, float.class).newInstance(firstSubj, secondSubj);
st.setName(name);
st.setAge(age);
st.gender = gender;
students.add(st); // Adding the student in the list
System.out.println(st);
System.out.println(st.getSubjects());
addMore = true;
break;
}
} catch (NoSuchMethodException | SecurityException | InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException ex) {
Logger.getLogger(Lab4.class.getName()).log(Level.SEVERE, null, ex);
}
}
if (addMore) {
System.out.println("Add another student? (y/n)");
String ans = input.nextLine();
addMore = ans.equals("y");
} else {
System.out.println("Wrong lesson. Try again.");
addMore = true;
}
}
System.out.println("Students");
for (Student student : students) {
System.out.println(student);
}
}
}
You also need to add the functions in the classes as mentioned bellow:
Student class:
public String getLessonName(){
return "";
}
public String[] getSubjectsNames(){
return new String[] {"", ""};
}
MathStudent class:
#Override
public String[] getSubjectsNames(){
return new String[] {"Algebra", "Calculus"};
}
#Override
public String getLessonName(){
return "Math";
}
ComputerStudent class:
#Override
public String[] getSubjectsNames(){
return new String[] {"Fortran", "Ada"};
}
#Override
public String getLessonName(){
return "Computers";
}
ScienceStudent class:
#Override
public String[] getSubjectsNames(){
return new String[] {"Physics", "Astronomy"};
}
#Override
public String getLessonName(){
return "Science";
}
Changes: The code firstly creates an arraylist with the student classes (studdentClasses) and adds all the classes for the students that are currently in the project (MathStudent, ComputerStudent, ScienceStudent). Then the user adds the lesson's name. Then (instead of the switch case) there is a for loop which itterates through the studdentClasses list and checks if the lesson's name that the user has written is the same with a student's class by using the getLessonName function. After that all the info for the student are asked and the grades for the subjects, and for the question (Give student's Physics grades) it uses the function getSubjectsNames. All the other things are like before.
You have a main class, that's what you need essentially, but you need to read from command line. Great, run from command line. Once you run, pay attention to what you did, you can pass parameters there as well. once you pass parameters, they go in line. This line is logically splitable, so split it within you code. for instance by pair of numbers after some key word like science and until next keyword and put again from java and ask a new question once you there.
I'm supposed to create a library program in java that allows you to create patrons and check out a maximum of 3 books. I'm really beginner at java so I apologize that my code is all over the place and may not make sense.
Below is the library class that I attempted(i also have a separate Patron, Book and Book Interface class)
My main concerns:
I have 2 ArrayLists, one for a list of inputed Users and another for a list of inputed Books. However how would i be able to assign certain checked out books to a certain user & make sure they borrow no more than 3?
I put a lot of the code in the main method but i end up having a lot of problems with static and non static stuff
How would I be able to create status' for each book? for example if "great expectations" is checked out, how can assign "borrowed" to it and make sure no one else can borrow it?
The program runs so far but its lacking depth because I'm lost as to how to check out/in books under a certain specified patron.
SORRY again for all the inconsistencies in my code and i really really appreciate the help!
import java.awt.List;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
import java.util.Collections;
public class Library
{
static ArrayList <Patron> UserList = new ArrayList<Patron>();
static ArrayList <String> BookList = new ArrayList <String> ();
public static String status;
public static String borrower;
public static String borrowDate;
public static String returnDate;
public String status1 = "Available";
public String status2 = "Borrowed";
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int choice = 0;
System.out.println("********************Welcome to the Public Library!********************");
System.out.println(" Please Select From The Following Options: ");
System.out.println("**********************************************************************");
while(choice != 9)
{
System.out.println("1: Add new patron");
System.out.println("2: Add new book");
System.out.println("3: Edit patron");
System.out.println("4: Edit book");
System.out.println("5: Display all patrons");
System.out.println("6: Display all books");
System.out.println("7: Check out book");
System.out.println("8: Check in book");
System.out.println("9: Search book");
System.out.println("10: Search Patron");
System.out.println("9: Exit");
choice = input.nextInt();
switch(choice)
{
case 1: //Add new patron
System.out.print("Enter patron first name: ");
String firstName = input.next(); //read name from input
System.out.print("Enter patron last name: ");
String lastName = input.next();
UserList.add(new Patron(firstName, lastName)); //add name to list
System.out.println("-----You have successfully added a new patron!-----");
break;
case 2: //Add new book
System.out.print("Enter book title: ");
String title1 = input.next();
Scanner input1 = new Scanner(System.in);
System.out.print("Enter book author: ");
String author1 = input.next();
Book book1 = new Book(title1);
BookList.add(title1);
FullBookList.add(fullBook);
System.out.println("-----You have successfully added a new book!-----");
status = "available";
borrowDate = "none";
returnDate = "none";
borrower = "none";
break;
case 3: //Edit patron name
System.out.println("Enter original patron name: ");
String originalName = input.next();
System.out.println("Enter edited patron name: ");
String editedName = input.next();
//Collections.replaceAll(UserList, originalName, editedName);
if(UserList.contains(originalName))
{
}
case 4: //edit book
case 5: //display all patrons
System.out.println(UserList);
break;
case 6: //display all books
System.out.println(BookList);
break;
case 7: //check out a book
Patron.CheckOutBook();
break;
case 8: //check in a book
Patron.CheckInBook();
break;
}
}
}
}
import java.util.ArrayList;
import java.util.Scanner;
public class Patron
{
Scanner input = new Scanner(System.in);
private String first;
private String last;
int bookCount = 0; //amount books user has in pocket
int books = 0;
//constructor to "add new patron" by entering their name.
public Patron(String f, String l)
{
first = f;
last = l;
}
public String toString()
{
return first + " " + last;
}
public String getName()
{
return first + " " + last;
}
public static void CheckOutBook()
{
System.out.println("Enter book title to be check out: ");
Scanner input = new Scanner(System.in);
String bookCheckOut = input.next();
if(Library.BookList.contains(bookCheckOut))
{
Library.BookList.remove(bookCheckOut);
System.out.println("-----" + bookCheckOut + " has been checked out!-----");
System.out.println ("-------" + bookCheckOut + " is due in 7 days!-------");
}
else
System.out.println(bookCheckOut + " is not in the library. Please enter "
+ "a different book to be checked out");
}
public static void CheckInBook()
{
System.out.println("Enter book title to be checked in: ");
Scanner input = new Scanner(System.in);
String bookCheckIn = input.next();
if(Library.BookList.contains(bookCheckIn))
{
Library.BookList.add(bookCheckIn);
System.out.println("-----" + bookCheckIn + " has been checked in!-----");
}
else
System.out.println(bookCheckIn + " is not in the library. Please enter "
+ "a different book to be checked out");
}
public boolean canBorrow()
{
if(bookCount <= 3)
{
return true;
}
else
{
return false;
}
}
}
Note: This will likely involve some refactoring to your main loop.
Alright so the way I see it, we have three classes at play here: some Patrons, which can check books out and in, some Books, which have statuses like "available" and "checked out," and a Library, which contains books. So, we need 3 classes:
I'll start with Book and use pseudo code to explain the concepts for you to implement.
class Book
{
//private fields
private final String title;
private final String author;
private Status available = true;
//note--i would prefer using an Enum called status for this,
//but a boolean true/false value works adequately
//Constructor
public Book(string title, string author) {}
//accessors for title, author, available
//setter for available--used for Library only--there are better ways to ensure
//Patrons can't set the status of the book, but for now this is the simplest way
}
As you can see, Books have immutable fields that don't need to change, and one field that tracks it status. A better implementation might make Library track book status, as that makes more logical sense and better code, but this a simple implementation.
Next, Library, which needs lots of books:
class Library
{
private final ArrayList<Book> books;
//Constructor
public Library ()
{
books = loadBooks();
}
//some methods
private ArrayList<Book> loadBooks () {}
//however you want to create all your books (file input, whatever)
public bool isBookAvailable (Book b)
{
if b isn't in library: return false
else return (b in books).isAvailable()
}
public Book checkoutBook (Book b)
{ get book (checking availability, possibly returning a null Book), set status to unavailable, return it }
public Book checkinBook (Book b)
{ check that this the book belongs to library, set status to available }
}
As I said earlier, this isn't perfect. I could spend quite some time going on and on about how to improve the design, but for the sake of simplicity won't.
Now, Patrons. One question is, should Patrons have only one library that the visit? Or do they visit multiple libraries? I'll assume they visit more than one, since sometimes a library doesn't have all the books you want.
class Patron
{
private final String name;
private final Book[] books = new Book[3];//you can see I'm limiting them to 3 books
private int index = 0;
//Constructor
public Patron (String name) {}
//methods
public void checkoutBook (Book b, Library l)
{//could be tricky
check books status in l (l.isBookAvailable(b))
if available:
if space (index < 2) Book newBook = l.checkoutBook(b); books[index++] = newBook;
else: no space
else: not available
}
public void checkinBook (int bookIndex, Library l)
{
if bookIndex < 3:
if books[index] != null:
l.checkinBook (books[index]);
books[index--] = null;
else: no book
else: not valid index
}
}
Of course, other utilities like displaying books (library, patron) and toString methods might be useful. But now the responsibility of the main method is to create some patrons, a library, and give patrons the chance to check out and check in books via a menu. You have the heavy lifting done; you can work on input and output now.
Any questions?
A Beginner Level "Student Library Program" in JAVA, which interacts the Students and the Books. This Library Program can do following functions:
1-Adding a Book to Library.
2-Update Book Quantity.
3-Search a Book with its Serial number.
4-Search Books With Author Name.
5-Show all Books and their related Information.
6-Registering a Student.
7-Show All Registered Students.
8-Student can Check Out Book From Library(if registered).
:- Student can not Check Out more than 3 Books
:- You can only borrow a Book If it is Available in Library
9-Student can Check In Book to Library.
10-You can also see the Books which a Student has Checked Out(only while checking in)
Note: At the time it can store only 50 books for simlicity in program
I Have created this program with the maximum skill and knowledge i had in java. As I'm a Beginner so I couldn't do more
Kindly give reviews about Program
Also tell me refinements which are to be made in program
Kindly Tell me the better way to do this Program
package library;
import java.util.Scanner;
public class book {
public int sNo;
public String bookName;
public String authorName;
public int bookQty;
public int bookQtyCopy;
Scanner input = new Scanner(System.in);
public book(){
System.out.println("Enter Serial No of Book:");
this.sNo = input.nextInt();
input.nextLine();
System.out.println("Enter Book Name:");
this.bookName = input.nextLine();
System.out.println("Enter Author Name:");
this.authorName = input.nextLine();
System.out.println("Enter Quantity of Books:");
this.bookQty = input.nextInt();
bookQtyCopy = this.bookQty;
}
}
package library;
import java.util.Scanner;
public class books {
book theBooks[] = new book[50]; // Array that stores 'book' Objects.
public static int count; // Counter for No of book objects Added in Array.
Scanner input = new Scanner(System.in);
public int compareBookObjects(book b1, book b2){
if (b1.bookName.equalsIgnoreCase(b2.bookName)){
System.out.println("Book of this Name Already Exists.");
return 0;
}
if (b1.sNo==b2.sNo){
System.out.println("Book of this Serial No Already Exists.");
return 0;
}
return 1;
}
public void addBook(book b){
for (int i=0; i<count; i++){
if (this.compareBookObjects(b, this.theBooks[i]) == 0)
return;
}
if (count<50){
theBooks[count] = b;
count++;
}
else{
System.out.println("No Space to Add More Books.");
}
}
public void searchBySno(){
System.out.println("\t\t\t\tSEARCH BY SERIAL NUMBER\n");
int sNo;
System.out.println("Enter Serial No of Book:");
sNo = input.nextInt();
int flag = 0;
System.out.println("S.No\t\tName\t\tAuthor\t\tAvailable Qty\t\tTotal Qty");
for (int i=0; i<count; i++){
if (sNo == theBooks[i].sNo){
System.out.println(theBooks[i].sNo + "\t\t" + theBooks[i].bookName + "\t\t" + theBooks[i].authorName + "\t\t" +
theBooks[i].bookQtyCopy + "\t\t" + theBooks[i].bookQty);
flag++;
return;
}
}
if (flag == 0)
System.out.println("No Book for Serial No " + sNo + " Found.");
}
public void searchByAuthorName(){
System.out.println("\t\t\t\tSEARCH BY AUTHOR'S NAME");
input.nextLine();
System.out.println("Enter Author Name:");
String authorName = input.nextLine();
int flag = 0;
System.out.println("S.No\t\tName\t\tAuthor\t\tAvailable Qty\t\tTotal Qty");
for (int i=0; i<count; i++){
if (authorName.equalsIgnoreCase(theBooks[i].authorName)){
System.out.println(theBooks[i].sNo + "\t\t" + theBooks[i].bookName + "\t\t" + theBooks[i].authorName + "\t\t" +
theBooks[i].bookQtyCopy + "\t\t" + theBooks[i].bookQty);
flag++;
}
}
if (flag == 0)
System.out.println("No Books of " + authorName + " Found.");
}
public void showAllBooks(){
System.out.println("\t\t\t\tSHOWING ALL BOOKS\n");
System.out.println("S.No\t\tName\t\tAuthor\t\tAvailable Qty\t\tTotal Qty");
for (int i=0; i<count; i++){
System.out.println(theBooks[i].sNo + "\t\t" + theBooks[i].bookName + "\t\t" + theBooks[i].authorName + "\t\t" +
theBooks[i].bookQtyCopy + "\t\t" + theBooks[i].bookQty);
}
}
public void upgradeBookQty(){
System.out.println("\t\t\t\tUPGRADE QUANTITY OF A BOOK\n");
System.out.println("Enter Serial No of Book");
int sNo = input.nextInt();
for (int i=0; i<count; i++){
if (sNo == theBooks[i].sNo){
System.out.println("Enter No of Books to be Added:");
int addingQty = input.nextInt();
theBooks[i].bookQty += addingQty;
theBooks[i].bookQtyCopy += addingQty;
return;
}
}
}
public void dispMenu(){
System.out.println("----------------------------------------------------------------------------------------------------------");
System.out.println("Enter 0 to Exit Application.");
System.out.println("Enter 1 to Add new Book.");
System.out.println("Enter 2 to Upgrade Quantity of a Book.");
System.out.println("Enter 3 to Search a Book.");
System.out.println("Enter 4 to Show All Books.");
System.out.println("Enter 5 to Register Student.");
System.out.println("Enter 6 to Show All Registered Students.");
System.out.println("Enter 7 to Check Out Book. ");
System.out.println("Enter 8 to Check In Book");
System.out.println("-------------------------------------------------------------
---------------------------------------------");
}
public int isAvailable(int sNo){
//returns the index number if available
for (int i=0; i<count; i++){
if (sNo == theBooks[i].sNo){
if(theBooks[i].bookQtyCopy > 0){
System.out.println("Book is Available.");
return i;
}
System.out.println("Book is Unavailable");
return -1;
}
}
System.out.println("No Book of Serial Number " + " Available in Library.");
return -1;
}
public book checkOutBook(){
System.out.println("Enter Serial No of Book to be Checked Out.");
int sNo = input.nextInt();
int bookIndex =isAvailable(sNo);
if (bookIndex!=-1){
//int bookIndex = isAvailable(sNo);
theBooks[bookIndex].bookQtyCopy--;
return theBooks[bookIndex];
}
return null;
}
public void checkInBook(book b){
for (int i=0; i<count; i++){
if (b.equals(theBooks[i]) ){
theBooks[i].bookQtyCopy++;
return;
}
}
}
}
package library;
import java.util.Scanner;
public class student {
String studentName;
String regNum;
book borrowedBooks[] = new book[3];
public int booksCount = 0;
Scanner input = new Scanner(System.in);
public student(){
System.out.println("Enter Student Name:");
this.studentName = input.nextLine();
System.out.println("Enter Reg Number:");
this.regNum = input.nextLine();
}
}
package library;
import java.util.Scanner;
public class students {
Scanner input = new Scanner(System.in);
student theStudents[] = new student[50];
//books book;
public static int count = 0;
public void addStudent(student s){
for (int i=0; i<count; i++){
if(s.regNum.equalsIgnoreCase(theStudents[i].regNum)){
System.out.println("Student of Reg Num " + s.regNum + " is Already Registered.");
return;
}
}
if (count<=50){
theStudents[count] = s;
count++;
}
}
public void showAllStudents(){
System.out.println("Student Name\t\tReg Number");
for (int i=0; i<count; i++){
System.out.println(theStudents[i].studentName + "\t\t" + theStudents[i].regNum);
}
}
public int isStudent(){
//return index number of student if available
//System.out.println("Enter Student Name:");
//String studentName = input.nextLine();
System.out.println("Enter Reg Number:");
String regNum = input.nextLine();
for (int i=0; i<count; i++){
if (theStudents[i].regNum.equalsIgnoreCase(regNum)){
return i;
}
}
System.out.println("Student is not Registered.");
System.out.println("Get Registered First.");
return -1;
}
public void checkOutBook(books book){
int studentIndex =this.isStudent();
if (studentIndex!=-1){
System.out.println("checking out");
book.showAllBooks();//jjjjjjjjjjjj
book b = book.checkOutBook();
System.out.println("checking out");
if (b!= null){
if (theStudents[studentIndex].booksCount<=3){
System.out.println("adding book");
theStudents[studentIndex].borrowedBooks[theStudents[studentIndex].booksCount] = b;
theStudents[studentIndex].booksCount++;
return;
}
else {
System.out.println("Student Can not Borrow more than 3 Books.");
return;
}
}
System.out.println("Book is not Available.");
}
}
public void checkInBook(books book){
int studentIndex = this.isStudent();
if (studentIndex != -1){
System.out.println("S.No\t\t\tBook Name\t\t\tAuthor Name");
student s = theStudents[studentIndex];
for (int i=0; i<s.booksCount; i++){
System.out.println(s.borrowedBooks[i].sNo+ "\t\t\t" + s.borrowedBooks[i].bookName + "\t\t\t"+
s.borrowedBooks[i].authorName);
}
System.out.println("Enter Serial Number of Book to be Checked In:");
int sNo = input.nextInt();
for (int i=0; i<s.booksCount; i++){
if (sNo == s.borrowedBooks[i].sNo){
book.checkInBook(s.borrowedBooks[i]);
s.borrowedBooks[i]=null;
return;
}
}
System.out.println("Book of Serial No "+sNo+"not Found");
}
}
}
package library;
import java.util.Scanner;
public class Library {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("********************Welcome to the Student Library!********************");
System.out.println(" Please Select From The Following Options: ");
System.out.println("**********************************************************************");
books ob = new books();
students obStudent = new students();
int choice;
int searchChoice;
do{
ob.dispMenu();
choice = input.nextInt();
switch(choice){
case 1:
book b = new book();
ob.addBook(b);
break;
case 2:
ob.upgradeBookQty();
break;
case 3:
System.out.println("Enter 1 to Search with Serial No.");
System.out.println("Enter 2 to Search with Author Name(Full Name).");
searchChoice = input.nextInt();
switch(searchChoice){
case 1:
ob.searchBySno();
break;
case 2:
ob.searchByAuthorName();
}
break;
case 4:
ob.showAllBooks();
break;
case 5:
student s = new student();
obStudent.addStudent(s);
break;
case 6:
obStudent.showAllStudents();
break;
case 7:
obStudent.checkOutBook(ob);
break;
case 8:
obStudent.checkInBook(ob);
break;
default:
System.out.println("CHOICE SHOULD BE BETWEEN 0 TO 8.");
}
}
while (choice!=0);
}
}
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
I have this issue where I can populate a LinkedList with objects which I can manipulate later in this shop system I am designing. The problem is that when I populate the list with more than one Object and then search for that object in the List; my program will tell me that the object I am looking for doesn't exist even though I can list the contents of the list and it will show.
Any help would be appreciated.
import java.io.*;
import java.util.*;
public class Sales extends addVideoGame implements java.io.Serializable{
private static LinkedList<VideoGames> sellGame = new LinkedList<>();
private static String searchTerm;
private static int searchQ;
public static void sellItem(){
sellGame = games;
int listLength = sellGame.size();
searchTerm = IBIO.inputString("What item would you like to sell: ");
for(VideoGames v : sellGame){
if(v.getTitle().contains(searchTerm)){
IBIO.output("Item found: " + searchTerm);
searchQ = v.getQuantity();
IBIO.output("Available Quantity: " + searchQ);
int sellQ = IBIO.inputInt("How much of this item would you like to sell: ");
if(sellQ > searchQ){
IBIO.output("The amount you have specified is greater than the \ncurrent stock.");
sellItem();
} else {
searchQ = searchQ - sellQ;
v.setQuantity(searchQ);
double sellP;
sellP = sellQ * v.getPrice();
IBIO.output("£"+sellP);
String confirm = IBIO.input("This is the price you are selling these items for. Type 'Yes' to complete the order or 'No' to reject it. ");
if(confirm.equalsIgnoreCase("Yes")){
IBIO.output("Order complete!");
try{
int receiptCount = 0;
PrintWriter receipt = new PrintWriter("C:\\Users\\Yemi\\Desktop\\TheStore\\receipt"+ receiptCount +".txt");
receipt.println("Item sold: " + v.getTitle());
receipt.println("Quantity sold: " + sellQ);
receipt.close();
receiptCount = receiptCount + 1;
IBIO.output("Receipt saved to: C:\\Users\\Yemi\\Desktop\\TheStore");
} catch(IOException io){
io.printStackTrace();
}
IBIO.output("Thank you for buying from Gamers Avenue UK!");
} else if(confirm.equalsIgnoreCase("No") && TheStore.privilege){
AccessMenus.adminMenu();
} else {
AccessMenus.userMenu();
}
if(TheStore.privilege){
AccessMenus.adminMenu();
} else {
AccessMenus.userMenu();
}
}
} else {
IBIO.output("The item you are looking for does not exist.");
sellItem();
}
}
}
}
Here are the classes used to navigate the program if anyone needs them:
public class TheStore {
static String password; //Variable created to hold and check the value of password against the correct value.
public static boolean privilege = false; //Variable created to distinguish the difference between a normal user and a user with administrator privileges.
public static void main(String[] args) {
IBIO.output("Welcome to Gamers Avenue UK!");
IBIO.output("Please make sure that you enter the correct password for your given privileges.");
password = IBIO.inputString("Enter password: ");
if(password.equalsIgnoreCase("admin")){ //Checks the entered value against the correct value.
privilege = true; //Sets global boolean value to true, so that admin access is granted.
IBIO.output(" ");
AccessMenus.adminMenu();//If password is correct, loads admin menu.
} else if(password.equalsIgnoreCase("user")){
privilege = false; //Keeps admin access off, so that unauthorised changes cannot be made.
IBIO.output(" ");
AccessMenus.userMenu();//If correct, loads user menu.
} else {
IBIO.output("The password is incorrect. Exiting program.");
System.exit(1); //If an incorrect password is entered, the program will close.
} //close else
}//close main
}//close class TheStore
Access Menus:
public class AccessMenus{
public static int choice;//Variable which will hold the value, which corresponds to an action depending on what value is entered.
public AccessMenus(){ //Null argument constructor, to set values to 0.
AccessMenus.choice = 0;
}
public AccessMenus(int c){ //Single argument constructor.
AccessMenus.choice = c;
}
public static void userMenu(){
IBIO.output("1: Sell a product.");
IBIO.output("2: Register a customer in the Loyalty programme.");
IBIO.output("3: Stock check.");
IBIO.output("4: Log out.");
IBIO.output(" ");
IBIO.output("Please make your choice: ");
choice = IBIO.inputInt();
if(choice == 1){
Sales.sellItem();
} else if(choice == 2){
CustomerRandom.customerMenu();
} else if(choice == 3){
StockCheck.checkStock();
} else if(choice == 4){
IBIO.output("Logging out.");
System.exit(1);
} else {
IBIO.output("Invalid choice. Returning to menu.");
userMenu(); //If the value entered does not correspond to any action, the program will treat it as invalid and return to the menu.
}//close else
}//close userMenu
public static void adminMenu(){
IBIO.output("1: Sell a product.");
IBIO.output("2: Go the Videogame management menu.");
IBIO.output("3: Stock check.");
IBIO.output("4: Register a customer in the Loyalty programme.");
IBIO.output("5: Log out.");
IBIO.output(" ");
IBIO.output("Please make your choice: ");
choice = IBIO.inputInt();
if(choice == 1){
Sales.sellItem();
} else if(choice == 2){
addVideoGame.vgMenu();
}else if(choice == 3){
StockCheck.checkStock();
} else if(choice == 4){
CustomerRandom.customerMenu();
} else if(choice == 5){
IBIO.output("Logging out.");
System.exit(1);
} else {
IBIO.output("Invalid input. Returning to menu.");
adminMenu();
} //end else
}//close AdminMenu
}//close AccessMenus
This class is necessary as it allows you to populate the list:
import java.util.*;
import java.io.*;
public class addVideoGame extends VideoGames implements java.io.Serializable{
public static VideoGames game = new VideoGames();
public static VideoGames eGame = new VideoGames();
public static LinkedList <VideoGames> games = new LinkedList<>();
public static LinkedList <VideoGames> loadList = new LinkedList<>();
private static int vgChoice = 0;
public static int vgCount = 0;
public static int vgAmount = 0;
public static void vgMenu(){
IBIO.output("WARNING: USING OPTION 4 TO LOAD IN A LOCAL FILE WILL ERASE EVERYTHING CONTAINED IN THE CURRENT LIST. \nSave everything in the current list using option 3 before loading in data.");
IBIO.output("1: Add a new videogame to the list.");
IBIO.output("2: View the contents of the list.");
IBIO.output("3: Save the contents of the list to the local area.");
IBIO.output("4: Load in data from a local file.");
IBIO.output("5: Return to the main menu.");
vgChoice = IBIO.inputInt("Make your choice: ");
if(vgChoice == 1){
vgAmount = IBIO.inputInt("How many games would you like to add to the database?: ");
for(int x = 0; x < vgAmount; x = x + 1){
VideoGames vg = new VideoGames();
vg.setTitle(IBIO.inputString("Enter the title of the game: "));
vg.setPublisher(IBIO.inputString("Enter the publisher of the game: "));
vg.setDeveloper(IBIO.inputString("Enter the developer of the game: "));
vg.setAgeRating(IBIO.inputInt("Enter the age rating of the game: "));
vg.setGenre(IBIO.inputString("Enter the genre of the game: "));
vg.setQuantity(IBIO.inputInt("Enter the available quantity of the game: "));
vg.setPrice(IBIO.inputDouble("Enter the recommended retail price: "));
game = vg;
games.add(vg);
IBIO.output(" ");
}
vgMenu();
} else if(vgChoice == 2){
IBIO.output("Current amount of games in the list: " + games.size());
Iterator itr = games.iterator();
while(itr.hasNext()){
Object g = itr.next();
IBIO.output(g + " ");
}
//System.out.println(Arrays.toString(games.toArray()));
vgMenu();
} else if(vgChoice == 3){
try{
ListIterator output = games.listIterator();
while(output.hasNext()){
Object o = output.next();
FileOutputStream fileOut = new FileOutputStream("C:\\Users\\Yemi\\Desktop\\TheStore\\games.ser");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(game);
out.close();
fileOut.close();
IBIO.output("Data saved to C:\\Users\\Yemi\\Desktop\\TheStore\\games.ser");
}
} catch(IOException io){
io.printStackTrace();
}
vgMenu();
} else if(vgChoice == 4){
eGame = null;
try{
ListIterator input = games.listIterator();
while(input.hasNext()){
Object i = input.next();
FileInputStream fileIn = new FileInputStream("C:\\Users\\Yemi\\Desktop\\TheStore\\games.ser");
ObjectInputStream in = new ObjectInputStream(fileIn);
eGame = (VideoGames) in.readObject();
in.close();
fileIn.close();
games.clear();
games.add(eGame);
IBIO.output("Item added to list from local file.");
}
} catch (IOException i){
i.printStackTrace();
return;
} catch(ClassNotFoundException c){
IBIO.output("VideoGames class not found");
c.printStackTrace();;
return;
}
vgMenu();
} else if(vgChoice == 5){
IBIO.output("Returning to main menu: ");
AccessMenus.adminMenu();
}
}
}
Again, any help would be greatly appreciated!
I guess the bug is cause by the else-block inside the loop inside sellItem().
Try this (although still I think you should remove the call to sellItem() inside the final if):
import java.io.*;
import java.util.*;
public class Sales extends addVideoGame implements java.io.Serializable{
private static LinkedList<VideoGames> sellGame = new LinkedList<>();
private static String searchTerm;
private static int searchQ;
public static void sellItem(){
sellGame = games;
int listLength = sellGame.size();
searchTerm = IBIO.inputString("What item would you like to sell: ");
boolean foundItem = false;
for(VideoGames v : sellGame){
if(v.getTitle().contains(searchTerm)){
foundItem = true;
IBIO.output("Item found: " + searchTerm);
searchQ = v.getQuantity();
IBIO.output("Available Quantity: " + searchQ);
int sellQ = IBIO.inputInt("How much of this item would you like to sell: ");
if(sellQ > searchQ){
IBIO.output("The amount you have specified is greater than the \ncurrent stock.");
sellItem();
} else {
searchQ = searchQ - sellQ;
v.setQuantity(searchQ);
double sellP;
sellP = sellQ * v.getPrice();
IBIO.output("£"+sellP);
String confirm = IBIO.input("This is the price you are selling these items for. Type 'Yes' to complete the order or 'No' to reject it. ");
if(confirm.equalsIgnoreCase("Yes")){
IBIO.output("Order complete!");
try{
int receiptCount = 0;
PrintWriter receipt = new PrintWriter("C:\\Users\\Yemi\\Desktop\\TheStore\\receipt"+ receiptCount +".txt");
receipt.println("Item sold: " + v.getTitle());
receipt.println("Quantity sold: " + sellQ);
receipt.close();
receiptCount = receiptCount + 1;
IBIO.output("Receipt saved to: C:\\Users\\Yemi\\Desktop\\TheStore");
} catch(IOException io){
io.printStackTrace();
}
IBIO.output("Thank you for buying from Gamers Avenue UK!");
} else if(confirm.equalsIgnoreCase("No") && TheStore.privilege){
AccessMenus.adminMenu();
} else {
AccessMenus.userMenu();
}
if(TheStore.privilege){
AccessMenus.adminMenu();
} else {
AccessMenus.userMenu();
}
}
break;
}
}
if(!foundItem) {
IBIO.output("The item you are looking for does not exist.");
sellItem();
}
}
}
And while this may work I would generally advise to transform searchTerm into an argument to the function and searchQ to the return value of the function. Doing so increases isolation between concurrent processes and clarifies which parameters are needed for the correct execution of the function.