This is the parent class
public class Holding {
private String holdingId, title;
private int defaultLoanFee, maxLoanPeriod, calculateLateFee;
public Holding(String holdingId, String title){
this.holdingId = holdingId;
this.title = title;
}
public String getId(){
return this.holdingId;
}
public String getTitle(){
return this.title;
}
public int getDefaultLoanFee(){
return this.defaultLoanFee;
}
public int getMaxLoanPeriod(){
return this.maxLoanPeriod;
}
public void print(){
System.out.println("Title: " + getTitle());
System.out.println("ID: " + getId());
System.out.println("Loan Fee: " + getDefaultLoanFee());
System.out.println("Max Loan Period: " + getMaxLoanPeriod());
}
}
This is the child class:
public class Book extends Holding{
private String holdingId, title;
private final int defaultLoanFee = 10;
private final int maxLoanPeriod = 28;
public Book(String holdingId, String title){
super(holdingId, title);
}
public String getHoldingId() {
return holdingId;
}
public String getTitle(){
return title;
}
public int getDefautLoanFee(){
return defaultLoanFee;
}
public int getMaxLoanPeriod(){
return maxLoanPeriod;
}
public void print(){
System.out.println("Title: " + getTitle());
System.out.println("ID: " + getHoldingId());
System.out.println("Loan Fee: " + getDefaultLoanFee());
System.out.println("Max Loan Period: " + getMaxLoanPeriod());
}
}
This is the menu:
public class LibraryMenu {
static Holding[]holding = new Holding[15];
static int hold = 0;
static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int options = keyboard.nextInt();
do{
}
System.out.println();
System.out.println("Library Management System");
System.out.println("1. Add Holding");
System.out.println("2. Remove Holding");
switch(options){
case 1:
addHolding();
break;
default:
System.out.println("Please enter the following options");
}
}while(options == 13);
System.out.println("Thank you");
}
public static void addHolding(){
System.out.println("1. Book");
System.out.println("2. Video");
int input1 = input.nextInt();
switch(input1){
case 1:
addBook();
break;
case 2:
addVideo();
break;
default:
System.out.println("Please select the following options");
break;
}
}
public static void addBook(){
}
}
All i want is when a user wants to add a book, the user will type in the title and id for it and it will save into the array, and when it is done, it will go back to the menu. I cant seem to do it with my knowledge at the moment.
i tried to do this in the addBook() method
holding[hold] = new Book();
holding[hold].setBook();
the setBook method would be in the Book class, to complete the setBook, i have to make set methods for all the get method. But when i do this, the constructor is undefined.
public void setBook(){
System.out.println("Title: " + setTitle());
System.out.println("ID: " + setHoldingId());
System.out.println("Loan fee: " + setDefaultLoanFee());
System.out.println("Max Loan Period: " + setMaxLoanPeriod());
}
If there is anything wrong with my code, please feel free to say it to me :D
Thanks.
edit: After the user adds a book or video, when the user wants to print all the holdings, it will show the title, id, loan fee and max loan period. How do i do that?
edit2: Clean up a few parts that wasn't necessary with my question
I would suggest you to use "List of Object" concept in handling it.
1) You can define a List of Book object for example.
List<Book> bookList = new ArrayList<Book>();
2) Everytime when you hit AddBook() function, you can then do something like this.
//Create a temporary object of Book to get the user input data.
Book tempBook = new Book(holdingIDParam, titleParam);
//Add them to the list
bookList.Add(tempBook);
3) You can then use that list to your likings, whether to store them into a .txt based database or to use them throughout the program. Usage example:
bookList.get(theDesiredIndex).getBook() ...
I am not entirely sure of what you want but after paying focus on your bold text,this is what I can understand for your case. Feel free to correct me on your requirements if it doesn't meet.
Hope it helps :)
Related
I would be required to write an array list of Mobile, do some operations such as add, remove, update and display. However, when it comes to sorting objects in arraylist, I am a little bit confused.
I am talking and referring to https://beginnersbook.com/2017/08/comparator-interface-in-java/
In drive class
//Create an arraylist of Mobile
ArrayList<Mobile> themobile = new ArrayList<>();
Scanner input = new Scanner(System.in);
System.out.println("Welcome to Mobile");
System.out.println("Please select a number in the following: ");
while (true) {
//A list of options
System.out.println("1. Diplay the next mobile.");
System.out.println("2. Display the previous mobile.");
System.out.println("3. Add a new mobile.");
System.out.println("4. Remove a new mobile");
System.out.println("5. Update a mobile.");
System.out.println("0. Exit");
//prompt user input
int choice = input.nextInt();
switch(choice) {
case 1:
//displayNext(themobile);
break;
case 2:
//displayPrevious(themobile);
break;
case 3:
addMobile(themobile);
break;
case 4:
removeMobile(themobile);
break;
case 5:
updateMobile(themobile);
break;
case 0:
System.out.println("Thank you for using a Mobile arraylist");
System.exit(0);
}
}
Collections.sort((themobile, new MobileByBrandName());
System.out.println("Sorted by brand name" + themobile);
Collections.sort(themobile, new MobileByMoNum());
System.out.println("Sorted by brand name" + themobile);
Collections.sort(themobile, new MobileByInS());
System.out.println("Sorted by brand name" + themobile);
}
In mobile class
public class Mobile implements Comparable<Mobile> {
private String brandName;
private int modelNumber;
private int internalMemoryS;
private int noOfAvailCameras;
public Mobile() {
}
public Mobile(String brandName, int modelNumber, int internalMemoryS, int noOfAvailCameras) {
this.brandName = brandName;
this.modelNumber = modelNumber;
this.internalMemoryS = internalMemoryS;
this.noOfAvailCameras = noOfAvailCameras;
}
public String getBrandName() {
return this.brandName;
}
public void setBrandName(String brandName) {
this.brandName = brandName;
}
public int getModelNumber() {
return this.modelNumber;
}
public void setModelNumber(int modelNumber) {
this.modelNumber = modelNumber;
}
public int getInternalMemoryS() {
return internalMemoryS;
}
public void setInternalMemoryS(int internalMemoryS) {
this.internalMemoryS = internalMemoryS;
}
public int getNoOfAvailCameras() {
return noOfAvailCameras;
}
public void setNoOfAvailCameras(int noOfAvailCameras) {
this.noOfAvailCameras = noOfAvailCameras;
}
public int compareTo(Mobile m) {
return this.brandName.compareTo(m.getBrandName());
}
public String toString() {
return "Brand name: " + brandName + "Model number: " + modelNumber + "Internal memory space: " + internalMemoryS + "No of available cameras: " + noOfAvailCameras;
}
}
Each method has its own class & import java.util.*;
public class MobileByMoNum implements Comparator<Mobile> {
public int compare(Mobile m1, Mobile m2) {
return m1.getModelNumber() - m2.getModelNumber();
}
}
public class MobileByBrandName implements Comparator<Mobile> {
public int compare(Mobile m1, Mobile m2) {
return m1.getBrandName().compareTo(m2.getBrandName());
}
}
public class MobileByInS implements Comparator<Mobile> {
public int compare(Mobile m1, Mobile m2) {
return m1.getInternalMemoryS() - m2.getInternalMemoryS();
}
}
Outcome:
TestMobile.java:48: error: unreachable statement
Collections.sort(themobile, new MobileByBrandName());
^
1 error
Any help and clarification is much appreciated. Thank you
As this code
while (true) {
never exits, the code below this loop is unreachable
Maybe System.exit(0); should maybe only be breaking the while loop.
Note break in a switch will not break the while loop
The code after while loop is never reached. You need to write some logic to break out of the while loop. One easy way to fix this is:
int choice = -1;
while (choice != 0) {
choice = input.nextInt();
switch (choice) {
//...other cases
case 0:
System.out.println("Thank you for using a Mobile arraylist");
}
}
Collections.sort(...);
System.out.println(...);
Put these lines inside while loop
Collections.sort((themobile, new MobileByBrandName());
System.out.println("Sorted by brand name" + themobile);
Collections.sort(themobile, new MobileByMoNum());
System.out.println("Sorted by brand name" + themobile);
Collections.sort(themobile, new MobileByInS());
System.out.println("Sorted by brand name" + themobile);
Also you can simplify the operation of comparison by using Comparator.comparing available from java 8 onwards. Like:
Comparator<Mobile> comparator = Comparator.comparing(new Function<Mobile,
#Override
public String apply(Mobile t) {
return t.getBrandName();
}
}).thenComparingInt(new ToIntFunction<Mobile>() {
#Override
public int applyAsInt(Mobile t) {
return t.getModelNumber();
}
}).thenComparingInt(new ToIntFunction<Mobile>() {
#Override
public int applyAsInt(Mobile t) {
return t.getInternalMemoryS();
}
});
Collections.sort(themobile, comparator);
I want to make a list of elements create with user input. Can I directly store an element into a list, or do I have to create a reference? I found how to make a list of premade variables, but I want to create te variables with user input.
The goal of my project is to store dataset and recall them at a later moment.
First I understand the concept of lists. Therefore I don't think its useful to copy my code at this moment.
import java.util.*;
public class Database {
public Database () {
}
public static int numberOfSpawnpoints = 0;
static Scanner userInput = new Scanner(System.in);
public static void main(String[] args) {
System.out.println("Add a new spawnpoint.\n");
System.out.println("State the name of this spawnpoint: ");
Spawnpoints Sp1 = new Spawnpoints(getSpawnName());
System.out.println("Name: " + Sp1.getSpawnName());
System.out.println("Location: " + Sp1.getLocation());
System.out.println("Pokemon: " + Sp1.getPokemon());
System.out.println("Spawntime: " + Sp1.getSpawntime());
System.out.println("The pokemon is currently spawned: " + Sp1.isSpawned());
numberOfSpawnpoints++;
}
public static String spawnName;
public static String getSpawnName() {
spawnName = userInput.next();
return spawnName;
}
public void setSpawnName(String spawnName) {
Database.spawnName = spawnName;
}
}
Hope this helps
import java.util.*;
public class Database {
public Database () {
}
public static int numberOfSpawnpoints = 0;
static Scanner userInput = new Scanner(System.in);
public static void main(String[] args) {
System.out.println("Add a new spawnpoint.\n");
System.out.println("State the name of this spawnpoint: ");
ArrayList<Spawnpoints> SPlist = new ArrayList<Spawnpoints>();
SPlist.add(new Spawnpoints(getSpawnName()));
// the above line will create an object of Spawnpoints and store it in list
System.out.println("Name: " + SPlist.get[0].getSpawnName());
System.out.println("Location: " + SPlist.get[0].getLocation());
System.out.println("Pokemon: " + SPlist.get[0].getPokemon());
System.out.println("Spawntime: " + SPlist.get[0].getSpawntime());
System.out.println("The pokemon is currently spawned: " + SPlist.get[0].isSpawned());
numberOfSpawnpoints++;
}
public static String spawnName;
public static String getSpawnName() {
spawnName = userInput.next();
return spawnName;
}
public void setSpawnName(String spawnName) {
Database.spawnName = spawnName;
}
}
You can try adding this code:
ArrayList<String> items = new ArrayList<String>();
while (!userInput.equals("exit")){
items.add(userInput.next());
}
I am creating 3 things right now; a driver, a class and an exception.
Currently having trouble with my book store class recognizing the exceptions on my book class.
What am I doing wrong?
Driver: edited by the given suggestion by #Satoshi Kouno
import java.io.*;
import java.util.*;
public class BookStore{
public static void main(String arg[ ]) throws Exception{
Scanner sc = new Scanner(System.in);
int isbn=0;
int quantity = 0;
String title = "";
Book oneBook;
boolean exit = false;
List<Book> bookList = new ArrayList<Book>(); //here
while(true){
try{
sc = new Scanner(System.in);
System.out.print("Enter title: ");
title = sc.nextLine( );
System.out.println();
System.out.print("Enter isbn: ");
isbn = sc.nextInt( );
System.out.println();
System.out.print("Enter quantity: ");
quantity = sc.nextInt( );
System.out.println();
// Validation Codes
// Condition
if(isbn !=0 && quantity != 0 && !"".equals(title))
{
oneBook = new Book(title, isbn, quantity);
bookList.add(oneBook); //create a list in main
System.out.println("Book added in the list.");
}
else
{
System.out.println("Book not added");
break;
}
}
catch(InputMismatchException ime){
System.out.println("you did not enter a number");
}
catch (BookException be){
System.out.println(be.getMessage( )); //
}
}
for(int i = bookList.size()-1; i >= 0; i--){
System.out.println(bookList.get(i));
}
} //main method
} //class
Class:
public class Book{
//instance variables
private String title = "";
private int isbn;
private int quantity;
public Book (String title, int isbn, int quantity)throws Exception{
//constructors
setTitle(title);
setIsbn(isbn);
setQuantity(quantity);
}
public String toString( ){ //toString Method
String s = "";
s = s + "Title: " + this.title + "\nISBN: " + this.isbn + "\nQuantity: " + this.quantity + "\n";
return s;
}
public String getTitle( ){
return this.title;
}
public int getisbn( ){
return this.isbn;
}
public int getquantity( ){
return this.quantity;
}
//mutator methods
public void setTitle(String newtitle )throws BookException{
if(newtitle.length()<1){
BookException be = new BookException( );
be.setMessage("Title cannot be blank");
throw be;
}
else{
this.title=newtitle;
}
}
public void setIsbn(int newisbn)throws BookException{
if (isbn <= 1000 || isbn >= 10000) {
this.isbn = newisbn;
}
else{
BookException be = new BookException( );
be.setMessage("ISBN should be between 1000 and 10000.");
throw be;
}
}
public void setQuantity(int newquantity)throws BookException{
if(newquantity>=0){
this.quantity = newquantity;
}
else{
BookException be = new BookException( );
be.setMessage("Quantity can't be a negative number.");
throw be;
}
}
}
And my exception class: edited #2
public class BookException extends Exception {
//instance variable
private String message = "";
public BookException(String message) {
super(message);
}
public void setMessage(String newMessage) {
this.message = newMessage;
}
public String getMessage() {
return this.message;
}
}
Trying to get my class to work with my driver but it's not working.
EDIT!! PSA
i forgot to point out the requirements of my driver class
Read the book title from the user
Read the book ISBN from the user
Read the book in stock quantity from the user
Your program should continue to read the book information from the user until all the entries from the user for all the fields are blank or zero.
Your program will store valid book objects into an ArrayList (only valid objects)
Your program will then print the list all the "valid" Books entered by the user in the reverse order in which the books were entered.
As the user is entering information, the program should give feedback such as reporting that an item has been added to the ArrayList, or reporting any errors found.
my book and exception class are not needed changes already
they just want me to make my own driver to run with both of them and their exceptions
Your class is not working to due this:
// Validation Codes
// Condition
if(isbn !=0 && quantity != 0 && title != null && title != "")
title != ""
This condition will be never and never verified so will not enter in the part of code where you create the Book object:
To compare String values just replace it by:
!"".equals(title);
#See String#equals() JavaDOC
or use apache lang classes (probably you will have to import it):
StringUtils.isNotEmpty(title);
Moreover:
I suggest you to modify your custom exception class adding the construct:
public class BookException extends Exception {
public BookException(String message) {
super(message);
}
}
And in Book#setTitle and the other one setters raise it by:
throw new BookException("Title cannot be blank!");
Hope this help.
Update:
Analysing the code i checked others things like:
if (isbn <= 1000 || isbn >= 10000) {
this.isbn = newisbn;
} else {
BookException be = new BookException( );
be.setMessage("ISBN should be between 1000 and 10000.");
throw be;
}
This check is wrong for me, probably you wanted to do this:
isbn >= 1000 && isbn <= 10000
I have a class Borrower which consists of a name and then it also stores an arraylist full of items that the person has borrowed.
I want to be able to create multiple instances of this class from my main and then be able to access them to view the items they have borrowed.
I am having trouble understanding how to create multiple instances. I just keep running into the issue of overwriting the the Borrowed class.
So in the code below if I create newBorrower("Tim") and then addItem("Wrench"), and then go to create newBorrower("john") then I overwrite newBorrower.
I want to be able to create multiple instances of Borrower based on user input?
I've tried saving the entire Borrower class. I'm not sure if that would work, because it will not sort so I can't add multiple names or I get an error.
Borrower Class
public class Borrower
{
protected String name;
protected String item;
ArrayList<String> itemList = new ArrayList<String>();
public Borrower()
{
}
public Borrower(String name)
{
this.name = name;
}
public String getName()
{
return name;
}
public void addItem(String item)
{
this.item = item;
itemList.add(item);
}
Main Class
public class WhoBorrowedIt
{
public static void main(String[] args)
{
ArraySortedList<String> borrowersList = new ArraySortedList<String>();
Borrower newBorrower = new Borrower();
Borrower otherBorrower = new Borrower();
Scanner inName = new Scanner(System.in);
Scanner inItem = new Scanner(System.in);
String item;
String name;
String menu;
int option;
menu = "Make a selection: " + "\n"
+ "1. Add Borrower" + "\n"
+ "2. Add Item Borrowed" + "\n"
+ "3. Remove Item Returned" + "\n"
+ "4. View Borrowers" + "\n"
+ "5. Exit";
do
{
Scanner in = new Scanner(System.in);
System.out.println(menu);
option = in.nextInt();
switch(option)
{
case 1: //create borrower
{
System.out.println("Enter Name");
name = inName.nextLine();
newBorrower = new Borrower(name);
borrowersList.add(newBorrower.getName());
break;
}
case 2: //add items
{
System.out.println("Enter item");
item = inItem.nextLine();
System.out.println("Who is borrowing");
name = inName.nextLine();
if(borrowersList.contains(name))
{
newBorrower.addItem(item);
}
else
{
newBorrower = new Borrower(name);
borrowersList.add(newBorrower.getName());
newBorrower.addItem(item);
}
}
}while(option != 5)
}
}
Use a Map like this
if (borrowersMap.containsKey(name))
{
borrowersMap.get(name).addItem(item)
}
else
{
newBorrower = new Borrower(name);
borrowersMap.put(newBorrower.getName(), newBorrower);
newBorrower.addItem(item);
}
where borrowersMap is a HashMap
Map<String, Borrower> borrowersMap = new HashMap<String, Borrower>();
You can change your list to this
List<Borrower> borrowerList = new ArraySortedList<Borrower>();
and then add a method to your program that gets a borrower by name
private Borrower getBorrowerByName( String borrowerName ){
for( Borrower borrower : borrowerList ){
if( borrower.getName().equalsIgnoreCase( borrowerName ) ){
return borrower;
}
}
return null;
}
then when you create a new borrower, you add it to the list - when you get an existing borrower, you use the method and check for null before adding an item to it.
I am practicing a programming task given in my course literature. The program will keep asking the user to enter student's grades until they enter end-of-file indicator.
What is happening in my case is typing ctrl+Z (on windows, as it instructs me in book) doesn't work. It happens nothing afetr I doing this. Is it a problem with my console window or program?
GradeBook class:
package gradebook;
import java.util.Scanner;
public class GradeBook {
private String courseName;
private int totalGrade;
private int gradeCounter;
private int aCount;
private int bCount;
private int cCount;
private int dCount;
private int fCount;
//Create a contructor
public GradeBook(String name) {
courseName = name;
}
GradeBook() {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
public void setCourseName(String name) {
courseName = name;
}
public String getCourseName() {
return courseName;
}
public void displayMessage() {
System.out.printf("Welcome to the course\n%s!\n\n", getCourseName());
}
public void inputGrade() {
//int gradeEnteredByuser;
Scanner input = new Scanner(System.in);
int gradeEnteredByuser;
System.out.printf("%s\n%s\n %s\n %s\n", "Enter the integer grade in the range 0-100", "Type the end-of file indicator to terminate input:",
"On Unix/Linux/Mac OS X type <Ctrl> d then press enter", "On windows type <Ctrl> z then press enter:");
while (input.hasNext()) {
//int gradeEnteredByuser;
gradeEnteredByuser = input.nextInt();
totalGrade += gradeEnteredByuser;
gradeCounter++;
incrementLetterGradeCounter(gradeEnteredByuser);
}
}
private void incrementLetterGradeCounter(int gradeEnteredByuser) {
switch (gradeEnteredByuser / 10)
{
case 9:
case 10:
++aCount;
break;
case 8:
++bCount;
break;
case 7:
++cCount;
break;
case 6:
++dCount;
default:
++fCount;
}
}
public void displayGradeReport(){
System.out.println("\nGrade report");
if(gradeCounter!=0){
double average=(double)totalGrade/gradeCounter;
System.out.printf("Total of the %d grades entered is %d\n", gradeCounter,totalGrade);
System.out.printf("Class avereage is %.2f\n", average);
System.out.printf("%s\n%s\n%s\n%s\n%s\n%s\n",
"Number of students who received each grade:",
"A: ", aCount,
"B: ", bCount,
"C: ", cCount,
"D: ", dCount,
"F: ", fCount);
}else{
System.out.println("No grade were entered:re");
}
}
}
GradeBookTest class:
package gradebook;
import java.util.Scanner;
public class GradeBookTest {
public static void main(String[] args) {
GradeBook gb=new GradeBook("Introduction to computer science");
gb.displayMessage();
gb.inputGrade();
gb.displayGradeReport();
// TODO code application logic here
}
}