How to remove an element previously added into an array? - java

Could you please help me figure out how will I make it possible to create a delete command?
in selection 5. I must use array not ArrayList neither Vector?
//Package ask1 main class Library
package ask1;
import java.lang.Object.*;
import java.util.Scanner;
import java.util.Arrays;
import java.io.*;
public class library {
public static void main(String[] args) throws InstantiationException, IllegalAccessException {
Management manager = new Management();
Scanner input = new Scanner( System.in );
Book vivlio = new Book();
System.out.println("\n\t\t^*^*^*^*^*^*^* LIBRARY MANAGEMENT ^*^*^*^*^*^*^");
while(true){
System.out.println("------------------MENU-------------------------------");
System.out.print("\nENTER UR CHOICE\n\t1:Add a new Book\n\t2:Edit Book Infos\n\t3:Search a Book (with ISBN)\n\t4:Show all the Books\n\t5:Delete a Book (with ISBN)\n\t6:Exit \n :");
int selection;
selection=input.nextInt();
if (selection == 1)
{
System.out.println("Adding a new book ");
String empty = input.nextLine();
System.out.println("name of book:");
vivlio.name = input.nextLine();
System.out.println("Author:");
vivlio.author = input.nextLine();
System.out.println("ISBN:");
vivlio.isbn = input.nextLine();
System.out.println("Number of copies:");
vivlio.number = input.nextInt();
System.out.println("");
manager.AddBook(vivlio);
}
else
if (selection == 2) {
System.out.println("Editing a Book ");
System.out.println("Please enter title of book to edit:");
String title = input.next();
Book editingBook = findBookByTitle(title);
if(editingBook == null) {
System.out.println("Sorry no book found with title name = " + title);
} else {
//ask user for new price etc what ever you want to edit.
System.out.println("Please enter new values:");
String newValue = input.nextLine();
editingBook.setPrice(newValue);
// etc. other editing to book.
}
}
else
if (selection == 3)
{
System.out.println("Searching a Book ");
}
else
if (selection == 4)
{
System.out.println("You Choose to view all the Books ");
manager.PrintAllBooks();
}
else
if (selection == 5)
{
System.out.println("You Choose to Delete a Book ");
String empty = input.nextLine();
}
else
if(selection == 6)
{
System.out.println("Library System Terminated!!! ");
String empty = input.nextLine();
System.exit(0);
}
else
{
System.out.println("Wrong Choice");
}
}
}
private static Book findBookByTitle(String title) {
// TODO Auto-generated method stub
return null;
}
here is the second class called Book
package ask1;
import java.util.Scanner;
public class Book {
Scanner input = new Scanner( System.in );
public String isbn;
public String name;
public String author;
public int number;
public String getIsbn() {
return isbn;
}
public void setIsbn(String isbn) {
this.isbn = isbn;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public int getNumber() {
return number;
}
public void setNumber(int number) {
this.number = number;
}
String bookinfo = name + " ," + author + " ," + isbn;
public void setPrice(String newPrice) {
// TODO Auto-generated method stub
}
}
And the third class called Management
package ask1;
import java.lang.reflect.Array;
import java.util.Scanner;
import java.util.Arrays;
public class Management {
public Book[] books =new Book [60];
String Sisbn;
int current = 0;
Library lib = new Library ();
Scanner input = new Scanner( System.in );
//Number 1
public void AddBook(Book vivlio)
{
books[current]=vivlio;
current++;
}
//Number 2
public Book findBookByTitle(String title)
{
Book searchBook = null;
for (Book vivlio : books)
{
if(vivlio.getName().equalsIgnoreCase(title))
{
searchBook = vivlio;
System.out.println("New name of book:");
vivlio.setName(input.nextLine());
System.out.println("New Author of book:");
vivlio.setAuthor(input.nextLine());
System.out.println("New isbn of book:");
vivlio.setIsbn(input.nextLine());
System.out.println("New number of copies of book:");
vivlio.setNumber(input.nextInt());
break; }
}
return searchBook;
}
public String getSisbn() {
return Sisbn;
}
public void setSisbn(String sisbn) {
Sisbn = sisbn;
}
public Book[] getBooks() {
return books;
}
public void setBooks(Book[] books) {
this.books = books;
}
public int getCurrent() {
return current;
}
public void setCurrent(int current) {
this.current = current;
}
//Number3
public Book findBookByISBN(String isbn)
{
Book searchBook = null;
for (Book vivlio : books)
{
if(vivlio.getIsbn().equalsIgnoreCase(isbn))
{
searchBook = vivlio;
String book = vivlio.getName();
lib.once=vivlio.getName();
System.out.println(lib.once);
break;
}
}
return searchBook;
}
//Number 4
public void PrintAllBooks()
{
for (int i=0;i<current;i++)
{
Book b = books[i];
System.out.println(b.name);
}
}
//number 5
public Book DeleteWithIsbn(String isbn)
{
Book searchBook = null;
for (Book vivlio : books)
{
if(vivlio.getIsbn().equalsIgnoreCase(isbn))
{
searchBook = vivlio;
books[current]=null;
for (int i=0;i<current;current--)
{
Book b = books[i];
System.out.println(b.name);
break;
}
}
}
return searchBook;
}
}

Your code doesn't attempt to 'delete' it still finds. Try the following instead:
(Untested but gives you the idea)
public boolean DeleteWithIsbn(String isbn) {
int index = 0;
for (Book vivlio : books) {
if(vivlio.getIsbn().equalsIgnoreCase(isbn)) { //find the right book
for (int i = index; i < books.length - 1; i++) {
books[i] = books[i+1]; //move all the other books up
}
books[books.length -1] = null; //reset the last one in the array
return true;
}
count++;
}
return false;
}
This method will return false if it cannot find the book. It returns true otherwise.
Of course this all assumes that the book only ever exists once in the array.

First, fix your indentation on your if/else statements, and consider using a case statement instead.
Second, your Selection 5 isn't actually deleting anything -- it's just setting String empty to the next line. Get the user-inputted ISBN with Scanner, and make sure to call Book.DeleteBookWithISBN(isbn) with that isbn. Then it'll do what you want :)

Related

how to output the book's title, author, and show the bookID seperately?

I'm a new java learner. Now I need to set the bookID from 1000, and according to the total number of input IDs, book author, and book title, respectively show the book's information.
For example, when users enter 2, The Lord of the Rings; J. R. R. Tolkien; The Hunger Games; Suzanne Collins;
The output is Book ID: 1000 Title: The Lord of the Rings Author: J. R. R. Tolkien Status: Available Book ID: 1001 Title: The Hunger Games Author: Suzanne Collins Status: Available.
I have completed part of the programming, but now I do not how to write the code in the BOOK[] array.
code:
import java.util.Scanner;
class Book{
private Integer bookID = 1000;
static Integer nextID;
private String title;
private String author;
private boolean isBorrowed;
public Book(String title, String author){
this.title = title;
this.author = author;
this.isBorrowed = false;
this.nextID = bookID++;
}
public void borrowBook(){
isBorrowed = true;
}
public void returnBook(){
isBorrowed = false;
}
public boolean isBookBorrowed(){
return isBorrowed;
}
public void show() {
System.out.println("Book ID: " + bookID);
System.out.println("Title: " + title);
System.out.println("Author: " + author);
System.out.print("Status: ");
if (isBorrowed)
System.out.println("Not Available");
else
System.out.println("Available");
System.out.println();
}
}
public class MyClass {
public static void main(String args[]) {
Scanner input=new Scanner(System.in);
int num=input.nextInt();
input.nextLine();
Book[] books = new Book[num];
String title;
String author;
for (int i=0; i<num; i++) {
books[i] =input.nextBook();
title = input.nextLine();
author = input.nextLine();
}
}
}
The following is my programming code, please help me see how to write the code of the array part, thank you very much!
This is how it should be done:
nextId must be static because it's the one and only variable that has your last book id.
bookID should not be static because it's different for each book.
Book class:
class Book{
private static Integer nextID = 1000;
private Integer bookID;
private String title;
private String author;
private boolean isBorrowed;
public Book(String title, String author){
this.title = title;
this.author = author;
this.isBorrowed = false;
this.bookID = nextID++;
}
public void borrowBook(){
isBorrowed = true;
}
public void returnBook(){
isBorrowed = false;
}
public boolean isBookBorrowed(){
return isBorrowed;
}
public void show() {
System.out.println("Book ID: " + bookID);
System.out.println("Title: " + title);
System.out.println("Author: " + author);
System.out.print("Status: ");
if (isBorrowed)
System.out.println("Not Available");
else
System.out.println("Available");
System.out.println();
}
}
Main class:
import java.util.Scanner;
public class MyClass{
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int num = input.nextInt();
input.nextLine();
Book[] books = new Book[num];
String title;
String author;
for (int i = 0; i < num; i++) {
title = input.nextLine();
author = input.nextLine();
books[i] = new Book(title,author);
}
for (int i = 0; i < num; i++) {
books[i].show();
}
}
}
The following code has a "database" of 2 books. The user is prompted to enter the book id as you stated, it starts with 1000. If the book is found they see your information via the show() method. If this isn't what you want let me know. OR if you want to add a feature that allows the user to input books we can do that too..
Please always give user prompts like "enter a number" when you use scanner.
I went ahead and added so that the user can enter a book and immediately see that the book was stored with the correct id. its alternate main below
import java.util.Scanner;
public class Book {
private static Integer nextID = 1000;
private Integer bookID;
private String title;
private String author;
private boolean isBorrowed;
public Book(String title, String author){
this.title = title;
this.author = author;
isBorrowed = false;
bookID = nextID++;
}
public void borrowBook(){
isBorrowed = true;
}
public void returnBook(){
isBorrowed = false;
}
public boolean isBookBorrowed(){
return isBorrowed;
}
public void show() {
System.out.println("Book ID: " + bookID);
System.out.println("Title: " + title);
System.out.println("Author: " + author);
System.out.print("Status: ");
if (isBorrowed)
System.out.println("Not Available");
else
System.out.println("Available\n");
}
public static void main(String[] args) {
// here we will create an array of 2 books as your data
Book books[] = new Book[2];
books[0] = new Book("blah", "blah bhal hald");
books[1] = new Book("java", "girl power");
Scanner input = new Scanner(System.in);
System.out.println("Enter the book id:");
int num = input.nextInt();
for (int i = 0; i < books.length; i++){
if (books[i].bookID == num){
books[i].show();
}
}
}
}
alternate main:
```public static void main(String[] args) {
// here we will allow the user to input book data and see the data
// returned with the new id.
Scanner input = new Scanner(System.in);
System.out.println("Enter the number of books you wish to add:");
int num = input.nextInt();
input.nextLine();
Book[] books = new Book[num];
String title;
String author;
for (int i = 0; i < num; i++) {
System.out.println("enter the title:");
title = input.nextLine();
System.out.println("enter the author");
author = input.nextLine();
books[i] = new Book(title,author);
System.out.println("The book you entered is:");
books[i].show();
}
}

(Array of objects) The method is undefined for the type

I am using eclipse ide.
I am creating a program to make an array of objects and get input from the user using scanner class.
When I'm trying to set input to the method variable I'm getting error which is:
The method set_no(Int) is undefined for the type BookDetails, where set_no is a method of class Book and BookDetails is the main class. And I'm getting it for all 4 methods.
Here is the code:
This is the Book class:
import java.util.Scanner;
class Book {
private int bookno;
private String title;
private String author;
private float price;
public Book(){
bookno=0;
title="Anonymous";
author="Anonymous";
price=0;
}
public void set_no(int no) {
this.bookno=no;
}
public void set_title(String t) {
if(t.length()<4) {
System.out.println("Error, the title of the book can't be less than 4 characters\n");
}
else {
this.title=t;
}
}
public void set_author(String a) {
this.author=a;
}
public void set_price(int p) {
if(p<1 || p>5000) {
System.out.println("Error, the price is out of range\n");
}
else {
this.price=p;
}
}
#Override
public String toString() {
String s = "Book number: "+Integer.toString(bookno)+",\n"+"Title: "+title+",\n"+"Author: "+author+",\n"+"Price: Rs. "+Float.toString(price)+".\n";
return s;
}
}
This is the main class:
public class BookDetails{
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
Book[] b=new Book[3];
for(int i=0; i<b.length; i++) {
b[i]=new Book();
}
for(int i=0; i<b.length; i++) {
System.out.println("Enter the book number: ");
b[i]=set_no(sc.nextInt()); //The method set_no(int) is undefined for the type BookDetails
System.out.println("Enter the book title: ");
b[i]=set_title(sc.nextLine()); //The method set_title(String) is undefined for the type BookDetails
System.out.println("Enter the name of the author: ");
b[i]=set_author(sc.nextLine()); //The method set_author(String) is undefined for the type BookDetails
System.out.println("Enter the price of the book: ");
b[i]=set_price(sc.nextFloat()); //The method set_price(String) is undefined for the type BookDetails
}
for(int i=0; i<b.length; i++) {
System.out.println(b[i].toString());
}
}
}
set_no is a method of Book, so you need to call it on an instance of Book, in this case b[i].
So, write b[i].set_no(sc.nextInt()) (and likewise for other methods).
Getters and setters in Java not like TypeScript/JavaScript , you dont need the under line in java (_)
I changed your code to getters and setters like Java functions :
import java.util.Scanner;
class Book {
private int bookNo;
private String title;
private String author;
private float price;
public Book(){
bookNo=0;
title="Anonymous";
author="Anonymous";
price=0;
}
public void setBookNo(int newBookNo) {
this.bookno=newBookNo;
}
public void setTitle(String newTitle) {
if(newTitle.length()<4) {
System.out.println("Error, the title of the book can't be less than 4 characters\n");
}
else {
this.title=newTitle;
}
}
public void setAuthor(String newAuthor) {
this.author=newAuthor;
}
public void setPrice(int newPrice) {
if(newPrice<1 || newPrice>5000) {
System.out.println("Error, the price is out of range\n");
}
else {
this.price=newPrice;
}
}
#Override
public String toString() {
String s = "Book number: "+Integer.toString(bookNo)+",\n"+"Title: "+title+",\n"+"Author: "+author+",\n"+"Price: Rs. "+Float.toString(price)+".\n";
return s;
}
}

Method wont increment an int variable inside an object ArrayList?

I've been having this issue with a 'Loanbook' method, the function of it is to increment the 'numOnLoan' variable stored in an object ArrayList by 1, however when i run the method it doesn't seem to change the value.
//Allows loaning of books
public static void Loanbook(Scanner sc, ArrayList<Book> books){
System.out.println("Please enter a book title");
if(sc.hasNext()){
String criteria = sc.nextLine();
for (int i = 0; i < books.size(); i++){
if(criteria.equals(books.get(i).getBookTitle())){
System.out.println("The book " + books.get(i).getBookTitle() + " there are " + books.get(i).getNumInStock() + " in stock");
books.get(i).setNumOnLoan(books.get(i).GetNumOnLoan()+1);
System.out.println("number on loan: " + books.get(i).GetNumOnLoan()); break;
}
} System.out.println("Book Loaned");
LibraryTester.MenuReturn(sc, books);
}
LibraryTester.MenuReturn(sc, books);
}
i suspect this is an issue with the logic of the code by however i edit it, the code doesn't seem to do what i want.
Edit:
book.java
public class Book {
private int id;
private String bookTitle;
private String authorName;
private int bookReleaseYear;
private int numOnLoan;
private int numInStock;
//constructor
public Book(int id, String bookTitle, String authorName, int bookReleaseYear, int numOnLoan, int numInStock) {
this.id = id;
this.bookTitle = bookTitle;
this.authorName = authorName;
this.bookReleaseYear = bookReleaseYear;
this.numOnLoan = numOnLoan;
this.numInStock = numInStock;
}
//Getters/Setters
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getBookTitle() {
return bookTitle;
}
public void setBookTitle(String bookTitle) {
this.bookTitle= bookTitle;
}
public String getAuthorName() {
return authorName;
}
public void setAuthorName(String authorName) {
this.authorName = authorName;
}
public int GetNumOnLoan() {
return numOnLoan;
}
public void setNumOnLoan(int numOnLoan) {
this.numOnLoan = numOnLoan;
}
public int getNumInStock() {
return numInStock;
}
public void setNumInStock(int numInStock) {
this.numInStock = numInStock;
}
public int getBookReleaseYear() {
return bookReleaseYear;
}
public void setBookReleaseYear(int bookReleaseYear) {
this.bookReleaseYear = bookReleaseYear;
}
Library.java
import java.util.ArrayList;
import java.util.Scanner;
public class Library {
public ArrayList<Book> books = new ArrayList<Book>();
public Library(){
super();
}
//Getters/Setters
public Library(ArrayList<Book> books) {
this.books = books;
}
public ArrayList<Book> getBooks() {
return books;
}
public void setBooks(ArrayList<Book> books) {
this.books = books;
}
//Methods
//Allows loaning of books
public static void Loanbook(Scanner sc, ArrayList<Book> books){
System.out.println("Please enter a book title");
if(sc.hasNext()){
String criteria = sc.nextLine();
for (int i = 0; i < books.size(); i++){
if(criteria.equals(books.get(i).getBookTitle())){
System.out.println("The book " + books.get(i).getBookTitle() + " there are " + books.get(i).getNumInStock() + " in stock");
books.get(i).setNumOnLoan(+1);
System.out.println("number on loan: " + books.get(i).GetNumOnLoan()); break;
}
} System.out.println("Book Loaned");
LibraryTester.MenuReturn(sc, books);
}
LibraryTester.MenuReturn(sc, books);
}
}
public static void Returnbook(Scanner sc, ArrayList<Book> books){
System.out.println("Please enter a book title");
if(sc.hasNext()){
String criteria = sc.nextLine();
for (int i = 0; i < books.size(); i++){
if(criteria.equals(books.get(i).getBookTitle())){
System.out.println("The book " + books.get(i).getBookTitle() +
" is in stock," + " there are " + books.get(i).getNumInStock() + " in stock and " + books.get(i).GetNumOnLoan() + " out on loan");
books.get(i).setNumOnLoan(-1);; break;
}
} System.out.println("Book returned");
LibraryTester.MenuReturn(sc, books);
}
}
LibraryTester.java
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Scanner;
public class LibraryTester {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Library lib = new Library();
ArrayList<Book> books = lib.getBooks();
books = Library.CreateBooksArrayList();
MenuInput(sc, books);
sc.close();
lib.setBooks(books);
}
//prints menu
public static void PrintMenu(){
System.out.println("Public Library Menu System");
System.out.println("---------------------------");
System.out.println("1: Add Book");
System.out.println("2: Search for book");
System.out.println("3: Loan Book");
System.out.println("4: Return Book");
System.out.println("5: Amend Book Details");
System.out.println("6: Display all Books");
System.out.println("7: Delete a Book");
System.out.println("8: Other Options");
System.out.println("9: Exit system");
System.out.println("----------------------------");
}
// Allows menu input
public static void MenuInput(Scanner sc, ArrayList<Book> books){
int input = 0;
PrintMenu();
if(sc.hasNextInt()){
input = sc.nextInt();
switch(input){
case 1:Library.AddBook(sc, books);
case 2:Library.SearchBooks(sc, books);;
case 3:Library.Loanbook(sc,books);
case 4:Library.Returnbook(sc, books);
case 5:Library.AmendDetails(sc,books);
case 6:Library.DisplayAllBooks(sc,books);
case 7:Library.Removebook(sc, books);;
case 8:OtherMenu(sc,books);
case 9:System.exit(0);
}
} else {
System.out.println("Please enter a number");
}
}
//Returns user to main menu
public static void MenuReturn(Scanner sc, ArrayList<Book> books){
System.out.println("Press any key to return to the main menu");
if(sc.hasNextLine()){
sc.nextLine();
MenuInput(sc, books);
}
}
}
EDIT: I seem to get the output:
Please enter a book title
Input: book1
Please enter a book title
The book book1 is in stock, there are 5 in stock and 1 out on loan
Book returned
Press any key to return to the main menu
Final Edit: Fixed the issue, the code was not running due to an issue with the if statement, when i removed it there was a problem with all the text appearing at once, which was fixed with am extra 'sc.nextLine'. The issue with the ReturnBook running without call was due to lack of a 'break;' in the menu system.
Thanks everybody for your help, especially Shreyans Sheth
I just dug deep into your code. It seems you had a nasty bug (If it is one). I'll be addressing this specific line in your question: "the function of it is to increment the 'numOnLoan' variable stored in an object ArrayList by 1, however when i run the method it doesn't seem to change the value."
Original method:
public void setNumOnLoan(int numOnLoan)
{
this.numOnLoan= numOnLoan;
}
Method call in Loanbook:
books.get(i).setNumOnLoan(1);
In the LoanBook method, you are simply passing '+1' as a parameter and everytime, only 1 is being assigned. Here's what you need to do.
public void setNumOnLoan(int numOnLoan)
{
//When numOnLoan is 1, as you have passed everytime
//the current value gets incremented by one. I think that is what you wanted.
this.numOnLoan += numOnLoan; //You add it to the existing variable
}
You really should have named that function something else. I'm pretty sure there are more bugs out there but does THIS accomplish what you wanted?
Output:
(First call to Loanbook)
Please enter a book title
input :bbbbb
The book bbbbb there are 5 in stock
number on loan: 2
Book Loaned
(Second call to Loanbook)
Please enter a book title
input: bbbbb
The book bbbbb there are 5 in stock
number on loan: 3
Book Loaned

I am making a program to display error message whenever an empty space or blank space is entered

I am making a program to display error message whenever the input was blank or empty space and continues until desired input was entered.
Here's my current code:
public static Person getInput ()
{
Scanner data = new Scanner(System.in);
Person p = new Person();
boolean isEmpty = false;
int personAge = 0;
String personName;
char personGender;
while (isEmpty) {
try {
System.out.println("Name: ");
personName = data.nextLine();
personName.toUpperCase();
if (personName.isEmpty()) {
System.out.println("Please enter your name. ");
} else {
p.setName(personName);
}
System.out.println("AGE: ");
personAge = Integer.parseInt(data.nextLine());
if (personAge >= 1 && personAge <= 50)
{
System.out.println(" ");
} else {
System.err.println("Please enter a number from 1 - 50. ");
}
} catch (Exception e) {
System.err.println("Please enter your age.");
data.next();
} finally {
}
System.out.println("GENDER: ");
personGender = data.next().charAt(0);
p.setGender(personGender);
}
return p;
}
I am still a bit lost if I got it right or I need to correct some other things still. Thanks.
You should try something like with looping:
do {
System.out.println("Name: ");
personName = data.nextLine();
if (personName.isEmpty()) {
System.out.println("Please enter your name. ");
}else {
personName = personName.toUpperCase();//String is immutable
p.setName(personName);
}
} while (personName.isEmpty())
I changed your program a little bit so that it runs. If you ask a question it is more convenient to help you when you post a runnable example.
Here is what i did:
package person;
import java.util.Scanner;
public class Person {
private String name = "";
private char gender = ' ';
private int age = 0;
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public void getInput() {
Scanner data = new Scanner(System.in);
while (getName().trim().isEmpty()) {
System.out.print("Name (not empty): ");
setName(data.nextLine());
setName(getName().toUpperCase());
}
while (getAge() < 1 | getAge() > 50) {
System.out.print("AGE (1 - 50): ");
setAge(Integer.parseInt(data.nextLine()));
}
System.out.print("GENDER (m/f): ");
setGender(data.next().charAt(0));
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public char getGender() {
return gender;
}
public void setGender(char gender) {
this.gender = gender;
}
#Override
public String toString() {
return String.format("%s (%s) is %d year(s) old", getName(), getGender(), getAge());
}
public static void main(String[] args) {
Person p = new Person();
p.getInput();
System.out.println(p.toString());
}
}
I created getter and setter methods which is common to encapsulate classes from each other and improve the possibility for re-use.
As SMA has already recommended it is handy to use while loops to ask the user again if the input was not what you expected.
I would also recommend to not just ask 'AGE:' but 'AGE (1-50):' which guides the user through the inputs.
Sorry for also answering questions you didn't ask (;
Here's my updated codes. I would like to know if I'm doing it right this time.
public class PersonApp {
public static void main(String [] args) {
System.out.println("Enter 'exit' in name to quit app");
while(true) {
try {
Person p = Person.getInput();
if(p.getName().equalsIgnoreCase("exit")) break;
}
catch(Exception e) {
System.out.println("Error on input: " + e.getMessage());
}
}
}
}
import java.util.Scanner;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class Person {
private static String name;
private static int age;
private static char gender;
public String getName ()
{
return name;
}
public void setName (String name)
{
this.name = name;
}
public int getAge ()
{
return age;
}
public void setAge (int age)
{
this.age = age;
}
public char getGender ()
{
return gender;
}
public void setGender (char gender)
{
this.gender = gender;
}
public static Person getInput ()
{
Scanner data = new Scanner(System.in);
Person p = new Person();
boolean isEmpty = false;
while (p.getName().trim().isEmpty()) {
try {
System.out.println ("Please enter your name.");
p.setName(data.next());
p.setName(p.getName().toUpperCase());
break;
}
catch (Exception e) {
System.err.println(" Input invalid. ");
p.setName(data.next());
}
}
while (p.getAge() >= 1 && p.getAge() <=50) {
try {
System.out.println("AGE (1-50): ");
p.setAge(Integer.parseInt(data.nextLine()));
if (p.getAge() >= 1 && p.getAge() <=50)
{
p.setAge(p.getAge());
break;
}else {
System.err.println("Please enter a number from 1 - 50. ");
}
}
catch (Exception e) {
System.err.println(" Input invalid. ");
p.setAge(Integer.parseInt(data.nextLine()));
}
}
while (p.getGender() == 'F' || p.getGender() == 'f' || p.getGender() == 'M' || p.getGender() == 'm') {
try {
System.out.println("GENDER (M/F): ");
p.setGender(data.next().charAt(0));
if (p.getGender() == 'F' || p.getGender() == 'f' ||
p.getGender() == 'M' || p.getGender() == 'm') {
p.setGender(p.getGender());
break;
} else {
System.out.println ("Please enter M for male and F for female. ");
}
}
catch (Exception e) {
System.err.println(" Input invalid. ");
p.setGender(data.next().charAt(0));
}
}
return p;
}
}

JAVA Linked List Confused on why I can't check a variable against an node in the Linked List?

public static void check(){
String name;
System.out.println("Enter Customer Name to CHECK RESERVATION ticket for this Flight: ");
Scanner input = new Scanner(System.in);
name = input.nextLine();
if (list.contains(name)) { //WHY IS THIS ASKING FOR SEPARATE METHOD?
System.out.println(name +" has a Reservation on this FLight!");
menu();
}
I am trying to take an input and check to see if that input is in the Linked List. I am having problems though getting this to work right.
If I add the new method in my LinkedList.Java class it says it needs to define a variable for link. Below is what I have in entirety if it helps:
import java.util.Scanner;
class airline {
public static LinkedList list = new LinkedList();
public static void main(String[] args) {
list.addAirplane("Allen",501);
list.addAirplane("James",501);
list.addAirplane("Andrea",501);
list.addAirplane("Velvett",501);
list.addAirplane("Paul",501);
//Method sort the list after year the car was made
list.sortList();
menu();
//Method to print all objects in List
System.out.println(list.viewAll());
}
public static void menu(){
int menuOpt;
System.out.println("Airline Menu:");
System.out.println("1. Reserve a Ticket");
System.out.println("2. Cancel Reservations");
System.out.println("3. Check Reservations");
System.out.println("4. Display Airplanes on Flights");
Scanner input = new Scanner(System.in);
menuOpt=input.nextInt();
System.out.println(menuOpt);
switch (menuOpt){
case 1:
System.out.println("Reserve a Ticket");
reserveTick();
break;
case 2:
System.out.println("Cancel Reservations");
cancel();
break;
case 3:
System.out.println("Check Reservations");
check();
break;
case 4:
System.out.println("Passengers listed by Flights");
break;
default:
System.out.println("INVALID RESPONSE!");
menu();
break;
}
}
public static void reserveTick(){
String name;
System.out.println("Enter Customer Name to RESERVE ticket for this Flight: ");
Scanner input = new Scanner(System.in);
name = input.nextLine();
list.addAirplane(name,501);
System.out.println(name + " has been added to Flight Number 501");
menu();
}
public static void cancel(){
String name;
System.out.println("Enter Customer Name to CANCEL ticket for this Flight: ");
Scanner input = new Scanner(System.in);
name = input.nextLine();
list.remove(name, 501);
System.out.println(name + " has been REMOVED from Flight Number 501");
menu();
}
public static void check(){
String name;
System.out.println("Enter Customer Name to CHECK RESERVATION ticket for this Flight: ");
Scanner input = new Scanner(System.in);
name = input.nextLine();
if (list.contains(name)) {
System.out.println(name +" has a Reservation on this FLight!");
menu();
}
else {
System.out.println(name + " is not on this Flight!");
menu();
}
}
public static void listpassengers(){
list.sortList();
}
}
------------------------------------------------------------------
import java.util.*;
public class LinkedList
{
private AirplaneNode head = null;
public void addAirplane(String name , int hk)
{
//If head = null then create the first node
if(head == null)
{
head = new AirplaneNode(name,hk,null);
}
else
{
//If there are more than 1 node
head = new AirplaneNode(name,hk,head);
}
}
public void sortList()
{
boolean sorted = false;
while(!sorted)
{
sorted = true;
for(AirplaneNode cursor = head ; cursor.getNext() != null ; cursor = cursor.getNext())
{
if(cursor.getHk() < cursor.getNext().getHk())
{
String n = cursor.getName();
int hk = cursor.getHk();
cursor.setName(cursor.getNext().getName());
cursor.setHk(cursor.getNext().getHk());
cursor.getNext().setName(n);
cursor.getNext().setHk(hk);
sorted = false;
}
}
}
}
public String viewAll()
{
StringBuffer str = new StringBuffer();
for(AirplaneNode cursor = head ; cursor != null ; cursor = cursor.getNext())
{
str.append(cursor+"\n");
}
return new String(str);
}
}
--------------------------------------------------------------
public class AirplaneNode
{
private String name;
private int hk;
private AirplaneNode next;
public AirplaneNode(String name,int hk,AirplaneNode head)
{
this.name = name;
this.hk = hk;
this.next = head;
}
public AirplaneNode getNext()
{
return next;
}
public String getName()
{
return name;
}
public int getHk()
{
return hk;
}
public void setName(String in)
{
name = in;
}
public void setHk(int in)
{
hk = in;
}
public String toString()
{
return name + " " + hk ;
}
}
It seems as if you are creating a own class LinkedList in the top package here:
import java.util.*;
public class LinkedList
{
Since your method check() belongs in the airline class in the same package (and without any import of java.util.LinkedList) it will instead use the class you have created and that class doesn't implement any contains() method.
Declare your linked list this way:
public static LinkedList<String> list = new LinkedList<String>();
EDIT (based on your comment):
It looks like you want a list of flights, where each flight has a list of passenger names.
public class Flight implements Comparable<Flight> {
private List<String> mPassengers;
private final int mFlight;
private static final Collator sCollator = Collator.getInstance();
public Flight(int flight) {
mPassengers = new ArrayList<String>();
mFlight = flight;
}
public void sortPassengers() {
Collections.sort(mPassengers, sCollator);
}
public void addPassenger(String name) {
mPassengers.add(name);
}
public boolean removePassenger(String name) {
return mPassengers.remove(name);
}
public boolean hasPassenger(String name) {
return mPassengers.contains(name);
}
public String getFlight() { return mFlight; }
public int compareTo(Flight other) {
return mFlight - other.mFlight;
}
}
public static List<Flight> list = new LinkedList<Flight>();
public static void main(String[] args) {
Flight flight = new Flight(501);
flight.addPassenger("Allen");
// etc. for all flight 501 passengers
list.add(flight);
// repeat all the above for each flight number
}
You should be able to fill in the rest.

Categories