Creating a library with book objects and member objects - java

I've just started programming recently and have ran into a few minor errors. I'm creating a library object which holds references to book objects and member objects, however I'm having trouble accessing methods from the member class and using them in the library class without errors popping up in the LibraryTester class. This is what I've coded
Library class
package assignment;
import java.nio.channels.MembershipKey;
import java.util.ArrayList;
import java.util.Scanner;
import org.omg.Messaging.SyncScopeHelper;
public class Library {
// Declared an array list of type book
private ArrayList<Book> Books;
private MemberList members;;
public Library(ArrayList<Book> Books, Member member) {
this.Books = Books;
this.members=members;
};
public void displayBooks() {
System.out.println("\t\t\t-----The Current Books in the library are-----");
for (int i = 0; i < Books.size(); i++) {
System.out.println("\n" + "\t\t" + Books.get(i).getTitle() + "\t\t\t" + "\n\t\tAuthor: "
+ Books.get(i).getAuthor() + "\n\t\tThis Books ID is: " + Books.get(i).getBookID() + "\t\t\t\t\t\t"
+ "\n\t\tIs this book on loan? " + Books.get(i).getOnLoan() + "\t\t\t\t\t"
+ "\n\t\tThe number of times which this book has been loaned: " + Books.get(i).getNumOfLoans()
+ "\t\t");
}
}
// method to remove permanently a book object
public void removeBook() // the parameter that is passed through
// is the book id of the book that is to
// be removed
{
Scanner input = new Scanner(System.in);
int bookID = 0;
boolean successful = false;
try {
do {
System.out.println("Please enter the book ID of the book you wish to delete");
bookID = input.nextInt();
for (int i = 0; i < Books.size(); i++) {
if (bookID == Books.get(i).getBookID())
{
System.out.println("The Book " + Books.get(i).getTitle() + " was removed");
Books.remove(i);
successful = true;
break;
}
}
if (!successful) {
System.out.println("Book ID " + bookID + " does not exist");
}
} while (successful == false);
} catch (Exception e) {
System.out.println("ERROR: Invalid input" + "\nYou have been returned to the main menu");
}
}
public void editBook() {
boolean successful = false;
try {
do {
Scanner sc = new Scanner(System.in);
System.out.println("Please enter the book ID of the book who's details you wish to change");
int bookID = sc.nextInt();
sc.nextLine();
for (int i = 0; i < Books.size(); i++) {
if (Books.get(i).getBookID() == bookID) {
System.out.println("Please enter the new name of the book:");
String newTitle = sc.nextLine();
Books.get(i).setTitle(newTitle);
System.out.println("Please enter the name of the author of the book:");
String newAuthor = sc.nextLine();
Books.get(i).setAuthor(newAuthor);
System.out.println("Change of book details successful" + "\nNew book title: " + newTitle
+ "\nNew author: " + newAuthor);
successful = true;
}
}
if (!successful) {
System.out.println("This book does not exist ");
}
} while (successful == false);
} catch (Exception e) {
System.out.println("ERROR: Invalid input" + "\nYou have been returned to the main menu");
}
}
public void addBook() {
boolean successful = false;
int bookID = 0;
String title = "";
String author = "";
Scanner input = new Scanner(System.in);
do {
System.out.println("Please assign a 3 digit number for the books ID ");
bookID = input.nextInt();
input.nextLine();
if(bookID > 99 && bookID <1000){
for (int i = 0; i < Books.size(); i++) {
if(Books.get(i).getBookID()!= bookID){
successful = true;
} else {
System.out.println("This book ID already exists ");
}
}
} else { System.out.println("You must enter a number between 99 and 1000 ");
}
} while (successful == false);
do {
System.out.println("Please enter the name of book");
title = input.nextLine();
for (int i = 0; i < Books.size(); i++) {
if (Books.get(i).getTitle().equalsIgnoreCase(title)) {
System.out.println("ERROR: This book already exists");
successful = false;
} else {
successful = true;
}
}
} while (successful == false);
do {
System.out.println("Please enter the author of the book");
author = input.nextLine();
successful = true;
} while (successful == false);
Book Book = new Book(bookID, title, author, false, 0, 0);
Books.add(Book);
System.out.println(
"Book creation succcessful:" + "\nTitle: " + title + "\nAuthor: " + author + "\nBook ID:" + bookID);
}
public void loanBook() {
Scanner input = new Scanner(System.in);
boolean successful = false;
do {
System.out.println(
"\nPlease enter the book ID of the book that you wish to take out (Press 9 to exit to the main menu)");
int bookID = input.nextInt();
if (bookID == 9) {
successful = true;
break;
}
for (int i = 0; i < Books.size(); i++) {
if (Books.get(i).getBookID() == bookID) {
do {
System.out.println("\nHow long would you like to loan the book for (20 Days maximum):");
int durationOnLoan = input.nextInt();
if (durationOnLoan <= 20 && 1 <= durationOnLoan) {
Books.get(i).setDurationOnLoan(durationOnLoan);
successful = true;
} else {
System.out.println("The number of days you have entered is invalid");
}
} while (successful == false);
System.out.println("\nThe book " + Books.get(i).getTitle() + " is now on loan");
Books.get(i).setOnLoan(true);
Books.get(i).setNumOfLoan(Books.get(i).getNumOfLoans() + 1);
successful = true;
}
}
if (successful == false) {
System.out.println("This book does not exist ");
}
} while (successful == false);
}
public void returnBook() {
boolean successful = false;
Scanner input = new Scanner(System.in);
try {
do {
System.out.println(
"Please enter the book ID of the book you wish to return (Press 9 to exit to the main menu");
int bookID = input.nextInt();
input.nextLine();
if (bookID == 9) {
successful = true;
}
for (int i = 0; i < Books.size(); i++) {
if (Books.get(i).getBookID() == bookID) {
if (Books.get(i).getOnLoan() == true) {
System.out.println("How long did you loan the book for?");
int durationOnLoan = input.nextInt();
if (durationOnLoan > Books.get(i).getDurationOnLoan()) {
durationOnLoan -= Books.get(i).getDurationOnLoan();
if (durationOnLoan < 3) {
System.out.println("You are " + durationOnLoan
+ " day(s) late in returning the book" + "\nYou have been fined £3."
+ "\n The book " + Books.get(i).getTitle() + " is now returned");
successful = true;
} else {
System.out.println("You are " + durationOnLoan + " days late in returning the book"
+ "\nYou have been fined £6.");
System.out
.println("The book " + Books.get(i).getTitle() + " has now been returned");
successful = true;
}
} else {
Books.get(i).setOnLoan(false);
System.out.println("The book " + Books.get(i).getTitle() + " has now been returned");
successful = true;
}
} else if (Books.get(i).getOnLoan() == false) {
System.out.println("\nThis book was not on loan");
System.out.println("\nYou have been returned to the main menu");
successful = true;
}
} else if (successful == false) {
System.out.println("This book does not exist");
}
}
} while (successful == false);
} catch (Exception e) {
System.out.println("ERROR: Invalid input" + "\nYou have been returned to the main menu");
}
}
}
MemberList class
package assignment;
import java.util.Scanner;
import java.util.ArrayList;
public class MemberList {
private ArrayList<Member> Members;
public MemberList(ArrayList<Member> Members) {
this.Members = Members;
}
public void addNewMember() {
Scanner input = new Scanner(System.in);
boolean successful = false;
int memberID = 0;
String memberName = "";
int memberAge;
String address;
int contactNumber;
System.out.println("\t\tCreate new member");
do {
System.out.println("Please enter your full name:");
memberName = input.nextLine();
if (!input.hasNextInt()) {
successful =true;
} else {
input.next();
System.out.println("Your name cannot contain a number");
}
} while (successful == false);
do {
try{
input.nextLine();
System.out.println("please create your unique 2 digit member ID");
memberID = input.nextInt();
for (int i = 0; i < Members.size(); i++) {
if (Members.get(i).getMemberID() == memberID) {
System.out.println("This member ID is already in use");
successful =false;
}
if (memberID <= 9 || memberID > 99) {
System.out.println("PLease enter 2 digit ID (between 10 and 100) ");
}
if(Members.get(i).getMemberID() != memberID && memberID > 9 && memberID < 100) {
successful = true;
}
}
} catch(NumberFormatException e)
{
System.out.println("Invalid input");
}
} while (successful == false);
do{
System.out.println("Please enter your age: ");
memberAge = input.nextInt();
if(!input.hasNextInt())
{
System.out.println("Invalid input");
} else{successful =true;}
}while(successful == false);
do{
System.out.println("Please enter your adress");
address = input.nextLine();
successful =true;
}while(successful==false);
do {
System.out.println("please enter your contact number:");
contactNumber = input.nextInt();
if(!input.hasNextInt())
{
System.out.println("Invalid input");
} else{successful = true;}
}while(successful==false);
Member newMember = new Member(memberID,memberName,memberAge,0,0,address,contactNumber);
Members.add(newMember);
}
public void displayMembers()
{
System.out.println("\t\t\t-----The current members in the library are-----");
for (int i = 0; i < Members.size(); i++)
{
System.out.println("\n" + "\t\t" + Members.get(i).getMemberName() + "\t\t\t" + "\n\t\tMember ID: "
+ Members.get(i).getMemberID() + "\n\t\tAge: " + Members.get(i).getMemberAge() + "\t\t\t\t\t\t"
+ "\n\t\tAddress: " + Members.get(i).getAddress() + "\t\t\t\t\t"
+ "\n\t\tContact number: " + Members.get(i).getContactNumber()
+ "\t\t" + "\n\t\tNumber of books loaned: " + Members.get(i).getNumOfBooksLoaned()
+ "\t\t" + "\n\t\tNumber of Late Fees: " + Members.get(i).getPenalties());
}
}
}
LibraryTester Class
package assignment;
import java.util.Scanner;
import java.util.ArrayList;
public class LibraryTester {
public static void main(String[] args) {
String title = "";
String author = "";
int bookID = 0;
ArrayList<Member> List = new ArrayList<Member>();
MemberList memberlist = new MemberList(List){};
Member John = new Member(10,"John McLaughlin", 44, 5, 0,"75 B Loughbeg Road Toomebridge",123456789);
List.add(John);
Member Cathy = new Member(11,"Cathy McLaughlin", 43, 7, 0,"75 B Loughbeg Road Toomebridge",123456789);
List.add(Cathy);
ArrayList<Book> list = new ArrayList<Book>();
Library library = new Library(list, );
Book HarryPotter = new Book(100, "Harry Potter and The Philosopher's Stone", "J.K Rowling", false, 5, 0);
list.add(HarryPotter);
Book theOriginOfSpecies = new Book(101, "The Origin Of Species", "Charles Darwin", false, 3, 0);
list.add(theOriginOfSpecies);
Book LOTR = new Book(102, "The Lord of The Rings: The Fellowship of The Ring", "J.R.R Tolkien", false,7,0);
list.add(LOTR);
Scanner input = new Scanner(System.in);
boolean B = true;
while (B == true) {
System.out.println(" \nMenu ");
System.out.println("Press 1 to add a book");
System.out.println("Press 2 to edit a books details");
System.out.println("Press 3 to delete a book");
System.out.println("Press 4 to take out a book on loan");
System.out.println("Press 5 to return a book");
System.out.println("Press 6 to see all the books in the library");
System.out.println("Press 7 to become a member");
System.out.println("Press 8 to see the members of the library");
System.out.println("Press 9 to exit the program");
switch (input.nextInt()) {
case 1:
library.addBook();
B = true;
break;
case 2:
library.displayBooks();
library.editBook();
B = true;
break;
case 3:
library.displayBooks();
library.removeBook();
B = true;
break;
case 4:
library.displayBooks();
library.loanBook();
B = true;
break;
case 5:
library.displayBooks();
library.returnBook();
break;
case 6:
library.displayBooks();
B = true;
break;
case 7:
memberlist.addNewMember();
break;
case 8:
memberlist.displayMembers();
B = true;
break;
case 9:
System.out.println("Exiting .....");
System.exit(1);
break;
default:
System.out.println("You have not entered a valid option");
break;
}
}
}
}
The error occurs at the code
Library library = new Library(list , ) {
};
I'm not sure what to put after the comma, I've tried everything and nothing seems to work. Any thoughts?
EDIT
Edited Library class
package assignment;
import java.nio.channels.MembershipKey;
import java.util.ArrayList;
import java.util.Scanner;
import org.omg.Messaging.SyncScopeHelper;
public class Library {
// Declared an array list of type book
private ArrayList<Book> Books;
private ArrayList<Member> members;;
public Library(ArrayList<Book> Books, ArrayList<Member> member) {
this.Books = Books;
this.members=member;
};
Edited LibraryTester class
ArrayList<Member> List = new ArrayList<Member>();
MemberList memberList = new MemberList(List){};
ArrayList<Book> list = new ArrayList<Book>();
Library library = new Library(list, memberList ){};
The error says "The constructor Library(ArrayList, MemberList) is undefined" But i've changed the relevant things in the library class?

You need to pass an array of Book and, a Member :
public Library(ArrayList<Book> Books, Member member)

Since Library class is having the constructor
public Library(ArrayList<Book> Books, Member member){};
you can't just create a object as you are doing in LibraryTester class.
you need to pass the second parameter i.e, object of Member class.

Here you miss a member:
Library library = new Library(list, );
Try to add it like this creating an object of Member:
Member memberlist = new Member(10,"Joe Blogs", 44, 5, 0,"Bleaker Street",123456789);
Library library = new Library(list, memberlist);

Related

How to print two different data type arrays?

Can anyone help?
Choice 2 isn't working. It is suppose to display the employee ID when the user inputs the employee Name, but when the user enters the name nothing prints. The code has no errors.
public static void main(String[] args) {
int[] emplID={ 42577, 38611, 32051, 28627, 42061, 79451 };//employee ID
int ID = employeeID(emplID);
String[] emplNames= { "Bruce Wayne", "Barry Allen", "Hal Jordan", "Dinah Lance", "Oliver Queen", "Tineil Charles" };// Employee Names
search(emplNames, emplID);
//methods called from main
}
public static int employeeID(int [] emplID) {
//check ID length
for(int i=0; i< emplID.length; i++) {
if((emplID[i] > 10000)&&(emplID[i] < 99999)) {
System.out.print(emplID[i] + " - Valid ID length\n");
}
else {
System.out.println(emplID[i] + " - Invalid ID! ID must be Five digits!\n");
}//end of check length
//check if ID is prime
boolean isPrime = true;
for (int j = 2; j < emplID[i]; j++) {
if (emplID[i] % j == 0) {
System.out.println(emplID[i] + " - not prime");
isPrime = false;
break;
}
}
if(isPrime) System.out.println(emplID[i] + " - valid prime");//end of check prime
}//end of employeeID method
return 0;
}// end of ID checker
// search employee data
public static void search(String[] emplNames, int[]emplID) {
Scanner scan= new Scanner(System.in);
//Menu Choice
System.out.println("Please choose 1 to enter Employee ID or 2 to enter Employee Name:" );
int num = scan.nextInt();//input choice
// Choice 1 to enter ID to display name
if (num == 1) {
System.out.println("Please enter Employee ID:");
int searchID= scan.nextInt();
for(int ID = 0; ID < emplID.length; ID++) {
if (searchID == (emplID[ID])){
System.out.println("Name: "+ emplNames[ID]);
}
}
}
// Choice 2 to enter name to display ID
else if(num == 2) {
System.out.println("Please enter Employee Name");
String searchName= scan.next();
for(int ID = 0; ID< emplID.length; ID++){
if ((searchName.equals(emplNames[ID]))){
System.out.println("ID: " + emplID[ID]);
}
}
}
else
System.out.println("Employee Not Found");
}
}
I copied and pasted your code and ran it on my machine. Yes, choice 2 was not working for me either.
Before reading your code completely my gut feeling was that the cause of failure was in using the Scanner class to get the name of the employee. I have had similar issues in the past and the best move is to learn to use the InputStreamReader and BufferedStreamReader objects.
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class Main {
1: I didn't do anything to your main()
public static void main(String[] args) {
int[] emplID={ 42577, 38611, 32051, 28627, 42061, 79451 };//employee ID
int ID = employeeID(emplID);
String[] emplNames= { "Bruce Wayne", "Barry Allen", "Hal Jordan", "Dinah Lance", "Oliver Queen", "Tineil Charles" };// Employee Names
search(emplNames, emplID);
}
2: I didn't do anything to your employeeID() function
public static int employeeID(int [] emplID) {
//check ID length
for(int i=0; i< emplID.length; i++) {
if((emplID[i] > 10000)&&(emplID[i] < 99999)) {
System.out.print(emplID[i] + " - Valid ID length\n");
}
else {
System.out.println(emplID[i] + " - Invalid ID! ID must be Five digits!\n");
}//end of check length
//check if ID is prime
boolean isPrime = true;
for (int j = 2; j < emplID[i]; j++) {
if (emplID[i] % j == 0) {
System.out.println(emplID[i] + " - not prime");
isPrime = false;
break;
}
}
if(isPrime) System.out.println(emplID[i] + " - valid prime");//end of check prime
}//end of employeeID method
return 0;
}// end of ID checker
3: It's in your search() method where I first created the InputStreamReader and the BufferedReader:
public static void search(String[] emplNames, int[]emplID) {
InputStreamReader in = new InputStreamReader(System.in);
BufferedReader buff = new BufferedReader(in);
//Menu Choice
System.out.println("Please choose 1 to enter Employee ID or 2 to enter Employee Name:" );
int num = 0;
try {
num = Integer.parseInt(buff.readLine());
} catch (Exception e) {
e.printStackTrace();
}
4: Since choice 1 works fine, all I did was change your for loop to a for-each loop to make it easier to read.
// Choice 1 to enter ID to display name
if (num == 1) {
System.out.println("Please enter Employee ID:");
int searchID = 0;
try {
searchID = buff.read();
} catch (Exception e) {
e.printStackTrace();
}
for (int i : emplID) {
if (searchID == i) {
System.out.println("Name: " + emplNames[i]);
}
}
5: Here is what I did to make your 2nd Option work. Again, get the String from user via BufferedReader object's readLine() method. Then, it was just letting your for-loop searching for a match. That's it. Afterward, I ran the program and tested it for all the names you had above, works fine.
} else if (num == 2) {
System.out.println("Please enter Employee Name");
String searchName = "";
try {
searchName = buff.readLine();
} catch(Exception e) {
e.printStackTrace();
}
for(int ID = 0; ID< emplID.length; ID++){
if ((searchName.equals(emplNames[ID]))){
System.out.println("ID: " + emplID[ID]);
}
}
} else {
System.out.println("Employee Not Found");
}
}
}
6: Yeah, Scanner has an issue where it either doesn't read the entire line or you need to flush the stream before getting the input. It caused a lot of problems for me in a bunch of easy programs. Then I switched to using the InputStreamReader and BufferedStreamReader combo. Just wrap them in try-catch blocks, and you're fine. Look into it, it will the behavior of your code and your life a lot easier.
7: I hope this was helpful.

Error: Could not find or load main class Disneyland

My code compiles and I have two text files that need to be read from the program but when I run the program I get the following error: the menuItems.txt contains:
Churro
Ice Cream
Hamburger
Cheese burger
Turkey Leg
Corn Dog
Pizza
Funnel Cake
Soda
The priceItems contains:
5
4
9
10
13
7
9
6
5
All Files are located on my desktop
Error: Could not find or load main class Disneyland
package com.Kassie$;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Scanner;
public class Disneyland {
//Initialize the items 1D array
public static String[] getItems() {
try {
//Read from file
String[] aItems = new String(Files.readAllBytes
(Paths.get("src/com/Kassie$/desktop/menuItems.txt")))
.split("\n");
return aItems;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
//Initialize the items 1D array
public static String[] getPrices() {
try {
//Read from file
String[] aPrices = new String(Files.readAllBytes
(Paths.get("src/com/Kassie$/desktop/menuPrices.txt")))
.split("\n");
return aPrices;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
// Find the character's location
public static String findLocation(String[][] storedValue, String name) {
for(int i = 0; i < storedValue.length; i++) {
if(storedValue[i][0].equals(name)) {
return (storedValue[i][1]);
}
}
return null;
}
public static void main(String[] args) {
char choice = ' ';
int totPrice = 0;
Scanner s = new Scanner(System.in);
String[][] characterLocation = {{"Mickey Mouse","Main Street USA"},
{"Minnie Mouse", "Toon Town"},
{"Goofy","Frontier Land"},
{"Pluto","Tomorrowland"},
{"Belle","Fantasyland"},
{"Jasmine", "Adventureland"}};
System.out.println("Do you like to know the "
+ "Disney Character's location(Y/N)?");
choice = s.next().charAt(0);
if(choice == 'Y' || choice == 'y') {
System.out.println("Enter the name of the character");
String aName = s.next();
String location = findLocation(characterLocation,aName);
if( location != null) {
System.out.println("The character is located in " + location);
}
else {
System.out.println("Sorry! The character you are looking for "
+ "is not in park today");
}
}
String[] items = getItems();
String[] prices = getPrices();
choice = ' ';
System.out.println("Would you like to view the menu?(Y/N)");
choice = s.next().charAt(0);
if(choice == 'N' || choice == 'n') {
System.exit(0);
}
while(choice == 'Y' || choice == 'y') {
for(int i = 0; i < items.length; i++) {
System.out.println("Enter " + (i+1) + " for " + items[i]);
}
int option = s.nextInt();
System.out.println("Item : " + items[option-1]);
System.out.println("Price : " + prices[option-1]);
totPrice = totPrice + Integer.parseInt(prices[option-1]);
System.out.println("Do you want to order more(Y/N)?");
choice = s.next().charAt(0);
}
System.out.println("Are you an Annual Pass Holder?(Y/N)?");
choice = s.next().charAt(0);
if(choice == 'Y' || choice == 'y') {
System.out.println("Your bill amount due : $" + ((double)totPrice -
((double)(totPrice*15))/100));
System.exit(1);
}
System.out.println("Your bill amount due : $" + totPrice);
}
}
You need to escape the dollar sign in your path.
To match a dollar sign, use "\$"
public static String[] getPrices() {
try {
//Read from file
String[] aPrices = new String(Files.readAllBytes
(Paths.get("src/com/Kassie\\$/desktop/menuPrices.txt")))
.split("\n");
return aPrices;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}

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]);
}
}

Student Info System

**this is what I have done so far. This program need me to display student info. There is no error when I run the program but the grade just isn't displayed. **
import java.io.*;
import java.math.MathContext;
class StudInfo {
public static DataInputStream d = new DataInputStream(System.in);
public static String matricNo[] = new String[100];
public static String name[] = new String[100];
public static int courseWorkMark []= new int[100];
public static int finalExamMark[] = new int [100];
public static String grade[] = new String[100];
public static double mark1;
public static double mark2;
public static int x = 1;
public static String sgrade;
public static int scourseWorkMark;
public static int sfinalExamMark;
//MENU
public static void main(String[] args)throws IOException {
menu();
}
public static void menu()throws IOException {
System.out.println("<<<-- MAIN MENU -->>>");
System.out.println("");
System.out.println("[1] Add\n[2] Edit\n[3] Delete\n[4] Search\n[5] View\n[6] Exit");
System.out.println("");
System.out.print("Select a menu: ");
int m = Integer.parseInt(d.readLine());
switch(m) {
case 1: //ADD DATA
addData();
break;
case 2: //EDIT DATA
editData();
break;
case 3: //DELETE DATA
DeleteData();
break;
case 4: //SEARCH DATA
SearchData();
break;
case 5: //VIEW DATA
viewData();
break;
case 6: //EXIT SYSTEM
break;
default:
break;
}
}
//DELETE
public static void DeleteData()throws IOException {
boolean result = false;
int index = 0;
spacing();
System.out.print("<<<-- DELETE RECORDS -->>>\n\n");
System.out.print("Search Student Matric Number: ");
String smatricNo = d.readLine();
for(int i=1;i<matricNo.length;i++) {
if(matricNo[i] !=null) {
if(smatricNo.equalsIgnoreCase(matricNo[i])) {
result = true;
index = i;
}
}
}
if(result == true) {
System.out.print("Matric: "+matricNo[index].toUpperCase()+ " ");
System.out.print("Name: "+name[index].toUpperCase()+ " ");
System.out.print("Course Work: "+courseWorkMark[index]+ " ");
System.out.print("Final Exam: "+finalExamMark[index]+ " ");
System.out.print("Grade: "+grade[index].toUpperCase()+ " ");
System.out.println("");
System.out.print("Are you sure to save this record?[y]-y/[n]-no: ");
String Ques = d.readLine();
if(Ques.equalsIgnoreCase("y")) {
matricNo[index] = null;
name[index] = null;
courseWorkMark[index] = 0;
finalExamMark[index] = 0;
grade[index] = null;
for(int j=index+1;j<matricNo.length;j++)
{
matricNo[j-1] = matricNo[j];
name[j-1] = name[j];
courseWorkMark[j-1] = courseWorkMark[j];
finalExamMark[j-1] = finalExamMark[j];
grade[j-1] = grade[j];
}
System.out.println("Record succesfully deleted!");
System.out.println("\n\n<Press Enter>");
String Ques1 = d.readLine();
spacing();
menu();
} else{
spacing();
menu();
}
} else{
System.out.print("Matric Number not found!");
System.out.println("\n\n<Press Enter>");
String Ques = d.readLine();
spacing();
menu();
}
}
//SEARCH
public static void SearchData()throws IOException {
boolean result = false;
int index=0;
spacing();
System.out.print("<<<-- SEARCH DATA -->>>\n\n");
System.out.print("Search Student Matric Number: ");
String smatricNo = d.readLine();
for(int i=1;i<matricNo.length;i++) {
if(matricNo[i] !=null) {
if(smatricNo.equalsIgnoreCase(matricNo[i])) {
result = true;
index = i;
}
}
}
if(result==true) {
System.out.print("Matric: " + matricNo[index].toUpperCase() + " ");
System.out.print("Name: " + name[index].toUpperCase() + " ");
System.out.print("Course Work: " + courseWorkMark[index] + " ");
System.out.print("Final Exam: " + finalExamMark[index] + " ");
System.out.print("Grade: " + grade[index].toUpperCase() + " ");
System.out.println("");
System.out.println("\n\n<Press Enter>");
String Ques = d.readLine();
spacing();
menu();
}else {
System.out.print("Matric Number not found!");
System.out.println("\n\n<Press Enter>");
String Ques = d.readLine();
spacing();
menu();
}
}
//ADD
public static void addData()throws IOException {
spacing();
System.out.print("<<<-- ADD DATA -->>>\n\n");
System.out.print("Student Matric Number: ");
String smatricNo = d.readLine();
System.out.print("Student Name: ");
String sname = d.readLine();
System.out.print("Course Work: ");
scourseWorkMark = Integer.parseInt(d.readLine());
System.out.print("Final Exam: ");
sfinalExamMark = Integer.parseInt(d.readLine());
Calculate();
System.out.print("Grade: " + sgrade);
String sgrade = d.readLine();
System.out.print("Are you sure to save this record?[y]-y/[n]-no: ");
String Ques = d.readLine();
if(Ques.equalsIgnoreCase("y")) {
matricNo[x] = smatricNo;
name[x] = sname;
courseWorkMark[x] = scourseWorkMark;
finalExamMark[x] = sfinalExamMark;
grade[x] = sgrade;
x++;
spacing();
menu();
}else if(Ques.equalsIgnoreCase("n")) {
spacing();
menu();
}
}
public static void spacing() {
System.out.print("\n\n\n");
}
//VIEW
public static void viewData()throws IOException {
boolean center = false;
spacing();
System.out.print("<<<-- VIEW DATA -->>>\n\n");
for(int i=1;i<matricNo.length;i++) {
if(matricNo[i] != null) {
System.out.print("Matric Number: " + matricNo[i].toUpperCase()+ " ");
System.out.print("Name: " + name[i].toUpperCase()+ " ");
System.out.print("Course Work: " + courseWorkMark[i]+ " ");
System.out.print("Final Exam: " + finalExamMark[i]+ " ");
System.out.print("Grade: " + grade[i].toUpperCase()+ " ");
System.out.println("");
center=true;
}
}
if(center == false) {
System.out.print("\nEMPTY DATABASE. NO RECORDS FOUND!");
}
System.out.println("\n\n<Press Enter>");
String Ques = d.readLine();
spacing();
menu();
}
//EDIT
public static void editData()throws IOException {
boolean result = false;
int index=0;
spacing();
System.out.print("<<<-- EDIT DATA -->>>\n\n");
System.out.print("Search Matric Number: ");
String smatricNo = d.readLine();
for(int i=1;i<matricNo.length;i++) {
if(matricNo[i] !=null) {
if(smatricNo.equalsIgnoreCase(matricNo[i])) {
result = true;
index = i;
}
}
}
if(result == true) {
System.out.print(matricNo[index] + " " +name[index]+ " " +courseWorkMark[index]+ " " +finalExamMark[index]+ " " +grade[index]+ " \n\n");
System.out.print("Student Matric Number: ");
String smatricNoedit = d.readLine();
System.out.print("Student Name: ");
String snameedit = d.readLine();
System.out.print("Course Work: ");
scourseWorkMark = Integer.parseInt(d.readLine());
System.out.print("Final Exam: ");
sfinalExamMark = Integer.parseInt(d.readLine());
Calculate();
System.out.print("Grade: " + sgrade);
String sgrade = d.readLine();
System.out.print("Are you sure to update this record?[y]-y/[n]-no: ");
String Ques = d.readLine();
if(Ques.equalsIgnoreCase("y")) {
matricNo[index] = smatricNoedit;
name[index] = snameedit;
courseWorkMark[index] = scourseWorkMark;
finalExamMark[index] = sfinalExamMark;
grade[index] = sgrade;
spacing();
menu();
}
else if(Ques.equalsIgnoreCase("n"))
{
spacing();
menu();
}
}else {
System.out.print("Matric Number not found!");
System.out.println("\n\n<Press Enter>");
String Ques = d.readLine();
spacing();
menu();
}
}
//CALCULATION PART
public static String Calculate()
{
double mark1 = scourseWorkMark * 60 / 100;
double mark2 = sfinalExamMark * 40 / 100;
double totalMark = mark1 + mark2;
if (totalMark >= 90)
{
sgrade = "A+";
}
else if (totalMark >= 80)
{
sgrade = "A";
}
else if (totalMark >= 70)
{
sgrade = "A-";
}
else if (totalMark >= 65)
{
sgrade = "B+";
}
else if (totalMark >= 60)
{
sgrade = "B";
}
else if (totalMark >= 55)
{
sgrade = "C+";
}
else if (totalMark >= 50)
{
sgrade = "C";
}
else if (totalMark >= 45)
{
sgrade = "D";
}
else if (totalMark >= 40)
{
sgrade = "E";
}
else
{
sgrade = "F";
}
return;
}
}
Why can't the grade be displayed?
In the public static String Calculate() function, you need to return return sgrade; and currently, you are not returning any object, but the method calls for the return of a string.
Also, remove String sgrade = d.readLine(); from line 199 (in the addData function). This is causing problems, because you are defining a new variable with the same name as a class variable, and not specifying which one to use on the next few lines.
When I fix this, here is the output:
<<<-- MAIN MENU -->>>
[1] Add [2] Edit [3] Delete [4] Search [5] View [6] Exit
Select a menu: 1
<<<-- ADD DATA -->>>
Student Matric Number: 1
Student Name: Jake Chasan
Course Work: 100
Final Exam: 100 Grade: A+
<<<-- VIEW DATA -->>>
Matric Number: 1 Name: JAKE Course Work: 100
Final Exam: 100 Grade: A+

how to recognise capital letters and not just lower case

Hi i have done this program it works fine except if the user tries to write in capital letters i tried .toUpperCase but it still closes the program if you try to use capital letter to search can anyone help please thank you
import java.io.*;
import java.util.Scanner;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class database
{
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
//my arrays
static String country [] = new String[1000];
static String capital [] = new String[1000];
static double population [] = new double[1000];
static List<String> countriesList = Arrays.asList (country); //a new array for user to add data to
public static void main (String args [])throws IOException
{
// now i am adding data to the arrays
country[0] = "Barbados";
capital[0] = "Bridgetown";
population[0] = 65.3;
country[1] = "france";
capital[1] = "paris";
population[1] = 315.8;
country[2] = "nigeria";
capital[2] = "abuja";
population[2] = 170.1;
country[3] = "USA";
capital[3] = "washington";
population[3] = 2840;
country[4] = "japan";
capital[4] = "tokoyo";
population[4] = 126.7;
int option = 0;
System.out.println("WELCOME TO MY COUNTRY DATABASE\n");
while(option!= 5){ //Only five options
options();
option = Integer.parseInt(br.readLine());
if(option > 5 || option < 1)
{
System.out.println("Wrong input! Try Again");
System.out.println("CHOOSE FROM 1 - 5 \n ");
}
if(option == 1) {
addCountry();
}
else if(option == 2){
searchCountry(); //Search from an array
}
else if(option == 3){
ListCountry();
}
else if(option == 4){
getFare(); //show fare to travel
}
else if(option == 5) {
System.out.print("\n Thank you and Goodbye ");
}
}
}
public static void options()
{
System.out.println("Main menu");
System.out.println("=========");
System.out.println("1. Add a new country");
System.out.println("2. Search for a country");
System.out.println("3. Show list of countries available");
System.out.println("4. Get fare from London to countries listed");
System.out.println("5. Exit");
System.out.print("\n Choose an option from 1 - 5: ");
}
public static void addCountry()throws IOException
{
System.out.println("\n Adding a country");
System.out.println("===================");
System.out.print("Enter name of country: ");
String countryInput = br.readLine();
System.out.print("Enter Capital: ");
String capitalInput = br.readLine();
System.out.print("Enter population: ");
String populationInput = br.readLine();
int spareSlot = -1;
for (int i = 0; i < country.length; i++) // loop so data can be added to arraylist
{
if(country[i] == null)
{
spareSlot = i;
break;
}
}
country[spareSlot] = countryInput;
capital[spareSlot] = capitalInput;
population[spareSlot] = Double.parseDouble(populationInput);
System.out.println("\n You added the country " + countryInput + ", the capital is " + capitalInput + ", with a population of " + populationInput + "\n" );
//System.out.println("================================================================================================================");
}
public static void searchCountry() throws IOException
{
Scanner in = new Scanner (System.in);//Scanner to obtain input from command window
String output;
int size, i;
System.out.println("\n Searching countries");
System.out.println("========================= \n");
System.out.print("Search a Country: ");
output = br.readLine();
boolean found = false;
//A loop to search from the array
for(i = 0; i < country.length; i++)
if(output.equals(country[i]))
{
found = true;
break;
}
if (found)
System.out.println(output + " is found at index " + i +"\n");
else
System.out.println(output + ": This country is not found, choose option 1 to Add country \n");
if (output == country[0])
{
System.out.println("The capital of "+ output + "is " + capital[1] + " with a population of " + population[3]);
}
if(output == country[1]) {
System.out.println("The capital is" + capital[4]);
}
if(output == country[2]) {
System.out.println("The capital is" + capital[1]);
}
if(output == country[3]) {
System.out.println("The capital is " + capital[2]);
}
if(output == country[4]) {
System.out.println("The capital is " + capital[3]);
}
}
public static void ListCountry()throws IOException
{
for (String c : countriesList)
{
if(c!=null)
System.out.println("\n" + c +"\n"); // to list all countries so far in the array
}
}
public static void getFare()
{
Scanner input = new Scanner (System.in);
String destination;
int fare;
System.out.println("\n Get a fare:");
System.out.println("============== \n");
System.out.print("Select destination by entering number from 1 -5: \n");
System.out.println("1 Caribbean");
System.out.println("2 Europe");
System.out.println("3 Africa");
System.out.println("4 America");
System.out.println("5 Japan");
destination = input.nextLine(); //get destination from user
fare = Integer.parseInt(destination);
switch(fare)
{
case 1: System.out.println("To travel to the Carribbean the fare is from £600 \n");
break;
case 2: System.out.println("To travel to Europe the fare is from £199 \n");
break;
case 3: System.out.println("To travel to Africa the fareis from £500 \n");
break;
case 4: System.out.println("To travel to America the fare is from £290 \n");
break;
case 5: System.out.println("To travel to Japan the fare is from £550 \n");
break;
default: System.out.println("INVALID ACTION START AGAIN \n");
System.out.println("======================================");
}
}
}
You have one comparison reading
if(output.equals(country[i]))
If you want this to be case-insensitive, you want to change that to
if(output.equalsIgnoreCase(country[i]))
Later in your code, you have lines similar to
if (output == country[0])
which compares object identity rather than string equality. You want to change all these to at least properly compare strings, and possibly to be case-insensitive as above.

Categories

Resources