I'm getting a NullPointerException at:
If(bookingList.size() == 0)
,
bookingList.add(vehicleBooking)
and
bookingList.add(rvBooking)
And i am not sure what is causing it. Any help is much appreciated.
Stack trace
bookingSystem.FerryBookingSystem at localhost:59034
Thread [main] (Suspended (exception NullPointerException))
FerryBookingSystem.bookingIDExists(String) line: 35
FerryBookingSystem.addVehicleBooking() line: 49
FerryBookingSystem.main(String[]) line: 114
C:\Program Files\Java\jre7\bin\javaw.exe (14/05/2013 10:52:02 PM)
BookingException
package bookingSystem;
import java.util.ArrayList;
import java.util.Scanner;
import java.io.*;
class BookingException extends Exception{
String message;
String IDs;
public BookingException(String message){
this.message = message;
}
public BookingException(String message, String IDs){
this.message = message;
this.IDs = IDs;
}
public String getIDs(){
return IDs;
}
public String getMessage(){
return message;
}
}
FerryBookingSystem
public class FerryBookingSystem {
private static ArrayList<VehicleBooking> bookingList;
private static Scanner userInput = new Scanner (System.in);
public FerryBookingSystem(){
bookingList = new ArrayList<VehicleBooking>();
}
public static int bookingIDExists(String IDs){
if (bookingList.size() == 0)
return -1;
for (int i = 0; i < bookingList.size(); i++){
if(bookingList.get(i).getbookingID().equals(IDs))
return i;
}
return -1;
}
public static boolean addVehicleBooking(){
System.out.print("Please enter the booking ID: ");
String booking_ID = userInput.nextLine();
if(bookingIDExists(booking_ID) != 1)
{
System.out.println("\nError - Sale ID \"" + booking_ID +
"\" already exists in the system!");
return false;
}
System.out.print("Please enter the registration number for the vehicle: ");
String registration_Number = userInput.nextLine();
System.out.print("Please enter the vehicle " +
"description: ");
String vehicle_Description = userInput.nextLine();
System.out.print("Please enter the number of people travelling in the vehicle: ");
int travelling_Number = userInput.nextInt();
userInput.nextLine();
VehicleBooking vehicleBooking = new VehicleBooking(booking_ID, registration_Number, vehicle_Description, travelling_Number);
bookingList.add(vehicleBooking);
System.out.println("New vehicle booking added successfully for " + booking_ID);
return true;
}
public static boolean addRecreationalVehicleBooking(){
System.out.print("Please enter the booking ID: ");
String booking_ID = userInput.nextLine();
System.out.print("Please enter the registration number for the vehicle: ");
String registration_Number = userInput.nextLine();
System.out.print("Please enter the vehicl description: ");
String vehicle_Description = userInput.nextLine();
System.out.print("Please enter the number of people travelling in the vehicle: ");
int travelling_Number = userInput.nextInt();
userInput.nextLine();
RVBooking rvBooking = new RVBooking(booking_ID, registration_Number, vehicle_Description, travelling_Number);
bookingList.add(rvBooking);
System.out.println("New rvbooking added successfully for " + booking_ID);
return true;
}
public static void displayBookingSummary(){
if (bookingList.size() != 0){
System.out.println("\nSummary of all past vehicle booking stored on system.");
for (int i=0 ; i<bookingList.size() ; i++){
bookingList.get(i).printBookingSummary();
System.out.println("");
}
}
}
public static void main (String [] args) throws IOException{
char user;
do{
System.out.println("**** Ferry Ticketing System ****");
System.out.println(" A - Add Vehicle Booking");
System.out.println(" B - Add Recreational Vehicle Booking");
System.out.println(" C - Display Booking Summary");
System.out.println(" D - Update Insurance Status");
System.out.println(" E - Record Recreational Vehicle Weight");
System.out.println(" F - Compile Vehicle Manifest");
System.out.println(" X - Exit");
System.out.print("Enter your selection: ");
String choice = userInput.nextLine().toUpperCase();
user = choice.length() > 0 ? choice.charAt(0) : '\n';
if (choice.trim().toString().length()!=0){
switch (user){
case 'A':
addVehicleBooking();
break;
case 'B':
addRecreationalVehicleBooking();
break;
case 'C':
displayBookingSummary();
break;
case 'D':
break;
case 'E':
break;
case 'F':
break;
case 'X':
break;
default:
break;
}
}
}while(user!='X');
}
}
Your code at:
private static ArrayList<VehicleBooking> bookingList;
have not been initialized. So initialize it.
bookingList is a static attribute of FerryBookingSystem.
You initialize it in the constructor, which is a non-sense for a static attribute.
Then, you never call your constructor because you never instantiate FerryBookingSystem.
Edit:
After looking more deeply into your code, it seems that you first declared bookingList as static then marked all methods static to solve compilations problems...
I don't think that you really need this attribute to be static so just remove the static keywork on your attribute and on all your methods:
public class FerryBookingSystem {
private ArrayList<VehicleBooking> bookingList;
Then, instantiate a FerryBookingSystem at the beginning of your main method:
public static void main (String [] args) throws IOException{
char user;
FerryBookingSystem fbs=new FerryBookingSystem();
and call methods of this instance :
switch (user){
case 'A':
fbs.addVehicleBooking();
break;
case 'B':
fbs.addRecreationalVehicleBooking();
break;
case 'C':
fbs.displayBookingSummary();
Move initialization of the bookingList from a regular constructor to a static initialization block:
static {
bookingList = new ArrayList<VehicleBooking>();
}
or initialize it at the point of declaration:
private static ArrayList<VehicleBooking> bookingList = new ArrayList<VehicleBooking>();
Otherwise, bookingList would remain null until the first call of FerryBookingSystem's constructor is made.
You're initializing the static field bookingList in a constructor and use it in static methods. Now you can call those methods without haveing created an instance of that class.
So there is a good chance, that bookingList is not initialized at the time you call the methods. Either remove all static modifiers or initialize the field directly and drop the constructor.
(I recommend removing all static modifiers and use instances of your class)
Don't initialize the static variables in a constructor. static can be called even before instance created for that class.
In your case bookingList is a static and it can be called without creating any object for this class. My be this is the reason for NullPonterException.
Related
I'm new to java and I was wondering if there was a way to access a variable from one method in another method. While writing a program using methods, I realized that I cannot just take one variable from one method and use it in another method. So I was wondering if there was a way to do this.
Here is my code so far
import java.util.Scanner;
public class program{
public static void mass(){
double a,e,p,v;
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the volume: ");
v=scanner.nextDouble();
p=0.8;
System.out.println("Enter the alcohol volume:(in percents) ");
e=scanner.nextDouble();
e=e/100;
a=v*e*p;
System.out.println("mass is: "+a);
}
public static void Concentration(){
double w,r,m;
String person;
System.out.println("Enter the person: m for male, f for female, j for teenager ");
Scanner sc=new Scanner(System.in);
person=sc.nextLine();
switch(person){
case "m": r=0.7;
break;
case "f": r=0.6;
break;
case "j": r=0.5;
break;
}
System.out.println("Enter person's weight: ");
m=sc.nextDouble();
//w=a/(m*r); //a from the method mass
}
public static void main(String[]args){
mass();
Concentration();
/*If(w>=0.5){ //w from the method concentration
System.out.println("You cannot drive!");
Else{
System.out.println("You can drive");
}
} */
}
}
There are two kinds of variables:
local variables (block-scoped)
member variables (class/instance level scope)
See: https://www.geeksforgeeks.org/variable-scope-in-java/
So, if you want to reuse a variable accross multiple methods, then you will need to convert it from a local variable into a member variable. In your case you only use static methods, so a would be declared outside your methods as
static double a;
and avoid declaring it inside your mass method, so your declaration line would be changed to
double e,p,v;
Note that the a is missing to avoid variable shadowing.
You may want to change your methods to instance-level methods, in which case you can declare a without the static keyword, depending on your plans and needs.
Also, a well-known approach is to implement getters and setters in order to make sure that whenever you get or set a value, if there are common operations, then they are implemented only once instead of code repeating.
Below you see the simplest changes to your code to achieve the goal you have specified:
import java.util.Scanner;
public class program{
static double a;
public static void mass(){
double e,p,v;
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the volume: ");
v=scanner.nextDouble();
p=0.8;
System.out.println("Enter the alcohol volume:(in percents) ");
e=scanner.nextDouble();
e=e/100;
a=v*e*p;
System.out.println("mass is: "+a);
}
public static void Concentration(){
double w,r,m;
String person;
System.out.println("Enter the person: m for male, f for female, j for teenager ");
Scanner sc=new Scanner(System.in);
person=sc.nextLine();
switch(person){
case "m": r=0.7;
break;
case "f": r=0.6;
break;
case "j": r=0.5;
break;
}
System.out.println("Enter person's weight: ");
m=sc.nextDouble();
w=a/(m*r); //a from the method mass
}
public static void main(String[]args){
mass();
Concentration();
/*If(w>=0.5){ //w from the method concentration
System.out.println("You cannot drive!");
Else{
System.out.println("You can drive");
}
} */
}
}
Finally, you could also use a as a return value, like:
import java.util.Scanner;
public class program{
public static double mass(){
double a,e,p,v;
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the volume: ");
v=scanner.nextDouble();
p=0.8;
System.out.println("Enter the alcohol volume:(in percents) ");
e=scanner.nextDouble();
e=e/100;
a=v*e*p;
System.out.println("mass is: "+a);
return a;
}
public static void Concentration(double a){
double w,r,m;
String person;
System.out.println("Enter the person: m for male, f for female, j for teenager ");
Scanner sc=new Scanner(System.in);
person=sc.nextLine();
switch(person){
case "m": r=0.7;
break;
case "f": r=0.6;
break;
case "j": r=0.5;
break;
}
System.out.println("Enter person's weight: ");
m=sc.nextDouble();
//w=a/(m*r); //a from the method mass
}
public static void main(String[]args){
Concentration(mass());
/*If(w>=0.5){ //w from the method concentration
System.out.println("You cannot drive!");
Else{
System.out.println("You can drive");
}
} */
}
}
To make a variable accessible in all functions of the class you can static the variable in question in the current class
package javaapplication6;
import java.util.Scanner;
// #author Vulembere
public class JavaApplication6 {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
mass();
Concentration();
if (w >= 0.5) {
System.out.println("You cannot drive!");
} else {
System.out.println("You can drive");
}
}
static double w;
public static void mass() {
double a, e, p, v;
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the volume: ");
v = scanner.nextDouble();
p = 0.8;
System.out.println("Enter the alcohol volume:(in percents) ");
e = scanner.nextDouble();
e = e / 100;
a = v * e * p;
System.out.println("mass is: " + a);
}
public static void Concentration() {
double r, m;
String person;
System.out.println("Enter the person: m for male, f for female, j for teenager ");
Scanner sc = new Scanner(System.in);
person = sc.nextLine();
switch (person) {
case "m":
r = 0.7;
break;
case "f":
r = 0.6;
break;
case "j":
r = 0.5;
break;
}
System.out.println("Enter person's weight: ");
m = sc.nextDouble();
//w=a/(m*r); //a from the method mass
}
}
So I have this assignment which is meant to simulate passengers waiting at a boarding gate and we need to create a menu with different options. For it we have to have two classes and a main program and the entire thing is supposed to be based on a circular queue.
While attempting to do the circular queue, I stumbled upon the problem mentioned in the title. When I add items to the queue, once I attempt to display them with the option from the menu, the queue pops the first item, which is not meant to do unless the option delete from the menu is called. Furthermore, if I call the delete and view options, the queue deletes two items. To summarize:
I have no idea why my view option acts as a delete option
Any suggestions as to how to resolve this are appreciated because I've been trying for hours on end, I re-wrote the passenger queue class a few times in different ways, yet still the same and currently I have no idea how to resolve it.
The program is as it follows:
Main:
public class Airport {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
PassengerQueue queue1= new PassengerQueue();
Passenger[] ArrayOfPassenger = new Passenger[20];
Scanner input= new Scanner (System.in);
String optionMenu;
for (int i=0; i<20; i++)
ArrayOfPassenger[i]= new Passenger();
char letter;
do {
System.out.println("Enter display option [A-add passenger, V- view passenger queue, D- delete passenger from queue, S- store passengerQueue data into file, L- load passengerQueue data from file] or 'X' to stop: ");
optionMenu = input.next();
letter = optionMenu.charAt(0);
switch (letter) {
case 'A':
queue1.AddPassenger();
break;
case 'V':
queue1.display();
case 'D':
queue1.removePassenger();
break;
case 'S':
break;
case 'L':
break;
}
} while (letter != 'X');
}
}
Passenger class:
public class Passenger {
private String firstName;
private String surname;
private int secondsInQueue;
Scanner input= new Scanner(System.in);
/**
*
* #return
*/
public String getname(){
return firstName= " "+surname;
}
public void setName (String fName, String sName){
firstName=fName;
surname=sName;
}
public Passenger (){
firstName= "";
surname="";
}
public String toString() {
return firstName + " " + surname;
}
And PassengerQueue class, which is having the issue:
public class PassengerQueue {
Scanner input= new Scanner(System.in);
private Passenger[] qArray =new Passenger [20];
private int first = 0;
private int last = 0;
private int maxStayInQueue;
static final int MAX_QUEUE_SIZE = 20;
public PassengerQueue() {
for (int i = 0;i < 20; i++)
qArray[i]= new Passenger();
}
public void AddPassenger() {
System.out.println("Enter passenger's First Name:");
String FirstName = input.next();
System.out.println("Enter passenger's surname:");
String Surname= input.next();
qArray[last].setName(FirstName, Surname);
last++;
if(last == qArray.length+1){
last = 0;
}
}
public boolean isEmpty() {
return first == 0;
}
public boolean isFull() {
return last == 19;
}
public void removePassenger(){
Passenger x;
x= qArray[first];
qArray[first].setName("","");
first=first+1;
if(first==qArray.length+1)
first=0;
}
public void display() {
System.out.println("The queue: ");
for(int i = first; i < last; i++)
System.out.println(qArray[i]);
}
}
You miss the break; statement after
queue1.display(); in class Airport main method.
So the next case'D' executed.
I'm a beginner at Java so sorry for the mess ups.
Im creating a Library program and have 4 classes: Library, Book, BookInterface and Patron.
I'm in the last couple of stages of the program however I have error messages in the Library class as I'm having trouble with instances.
I got the error message "Cannot make a static reference to the non-static method" in ALL of my switch statements. I tried to create an instance of the Library class in case 1 but still an error message. Also I can't change those methods to static. Any help is much appreciated! :)
Library class:
import java.awt.List;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
import java.util.Collections;
public class Library
{
public static void main(String[] args)
{
//create new library
Library newLibrary = new Library();
}
public Library()
{
Library library = new Library();
Scanner input = new Scanner(System.in);
int choice = 0;
System.out.println("********************Welcome to the Public Library!********************");
System.out.println(" Please Select From The Following Options: ");
System.out.println("**********************************************************************");
while(choice != 9)
{
System.out.println("1: Add new patron");
System.out.println("2: Add new book");
System.out.println("3: Edit patron");
System.out.println("4: Edit book");
System.out.println("5: Display all patrons");
System.out.println("6: Display all books");
System.out.println("7: Check out book");
System.out.println("8: Check in book");
System.out.println("9: Search book");
System.out.println("10: Search Patron");
System.out.println("11: Exit");
choice = input.nextInt();
switch(choice)
{
case 1: //Add new patron
//ERROR: Patron cannot be resolved or is not a field
library.Patron.newPatron();
break;
case 2: //Add new book
//ERROR: Cannot make a static reference to the non-static method
Book.addBook();
break;
case 3: //Edit patron name
Patron.editName();
break;
case 4: //edit book
//ERROR: Cannot make a static reference to the non-static method
Book.editBook();
break;
case 5: //display all patrons
System.out.println(Book.UserList);
break;
case 6: //display all books
//System.out.println(Book.OrigBookList);
Book.libraryInventory();
//Book.bookStatus()
break;
case 7: //check out a book
//ERROR: Cannot make a static reference to the non-static method
Patron.CheckOutBook();
break;
case 8: //check in a book
//ERROR: Cannot make a static reference to the non-static method
Patron.CheckInBook();
break;
case 9: //search book
//ERROR: Cannot make a static reference to the non-static method
Patron.bookStatus();
break;
case 10://search Patron
Patron.searchPatron();
break;
case 11: //exit program
}
}
}
}
Book class:
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class Book implements BookInterface
{
Scanner input = new Scanner(System.in);
static ArrayList <String> UserList = new ArrayList<String>();
static ArrayList <String> BookList = new ArrayList <String> (); //display just titles// use when checking out books
static ArrayList <String> OrigBookList = new ArrayList <String> (); //keep track of all titles ever entered
public String title;
public String author;
public String book;
public boolean checkIn;
private String status;
private String borrower;
public Book(String t, String a)
{
title = t;
author = a;
}
//constructor create new book
public Book(String newTitle)
{
title = newTitle;
}
public String toString()
{
return title + " " + author;
}
public String getTitle()
{
return title;
}
public void setTitle(String title)
{
this.title = title;
}
public String getAuthor()
{
return author;
}
public void setAuthor(String author)
{
this.author = author;
}
public void addBook()
{
Scanner input = new Scanner(System.in);
Scanner inputread = new Scanner(System.in);
System.out.print("Enter book title: ");
String title1 = inputread.nextLine();
Scanner input1 = new Scanner(System.in);
System.out.print("Enter book author: ");
String author1 = inputread.next();
Book fullBook = new Book(title1, author1); //create constructor w/ title & author
Book book1 = new Book(title1); //constructor w/ just title to be used to display all books
//BookList.add(title1);
OrigBookList.add(title1);
setStatus("IN"); //false = checked in
System.out.println("-----------------------------------------------");
System.out.println("-----" + title1 + " is now in the library!-----");
System.out.println("-----------------------------------------------");
}
public void editBook()
{
Scanner inputread = new Scanner(System.in);
System.out.println("Enter original book title: ");
String origTitle = inputread.nextLine();
System.out.println("Enter edited book title: ");
String editedTitle = inputread.nextLine();
Collections.replaceAll(Book.UserList, origTitle, editedTitle);
System.out.println("------------------------------------------------------");
System.out.println(origTitle + " has been changed to " + editedTitle + "!");
System.out.println("------------------------------------------------------");
}
public String getStatus(String book)
{
return status;
}
public void setStatus(String status)
{
this.status = status;
}
public void setBorrower(String borrower)
{
this.borrower = borrower;
}
public String getBorrower(String checkPatron)
{
return borrower;
}
public String getBook(String checkPatron)
{
return book;
}
public void setBook(String bookCheckOut)
{
this.book = bookCheckOut;
}
public void libraryInventory()
{
System.out.println("------------------ Library Inventory: ---------------");
for(int i =0; i<= OrigBookList.size()-1; i++)
{
//Book Title: checked in/out
System.out.println(OrigBookList.get(i) + ":" + getStatus(OrigBookList.get(i)));
}
System.out.println("-----------------------------------------------------");
}
}
Patron class:
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Scanner;
public class Patron
{
Scanner input = new Scanner(System.in);
private String fullName;
int bookCount = 0; //amount books user has in pocket
int books = 0;
//constructor to "add new patron" by entering their name.
public Patron(String newName)
{
fullName = newName;
}
public String toString()
{
return fullName;
}
public String getName()
{
return fullName;
}
public void CheckOutBook()
{
//create and format due date (7days)
GregorianCalendar returnDate = new GregorianCalendar();
returnDate.add(GregorianCalendar.DATE, 7);
Date d = returnDate.getTime();
DateFormat df = DateFormat.getDateInstance();
String dueDate = df.format(d);
Scanner inputread = new Scanner(System.in);
Scanner input = new Scanner(System.in);
System.out.println("Enter full patron name: ");
String borrower = inputread.nextLine();
System.out.println("Enter book title to check out: ");
String bookCheckOut = inputread.nextLine();
Book checkOut = new Book(bookCheckOut);
if(Book.BookList.contains(bookCheckOut))
{
Book.BookList.remove(bookCheckOut);
checkOut.setStatus("OUT");
checkOut.setBorrower(borrower);
Book.BookList.remove(bookCheckOut);
System.out.println("----------" + bookCheckOut + " has been checked out!----------");
System.out.println("-------------------BOOK STATUS:---------------------");
System.out.println("Book Title: " + bookCheckOut);
System.out.println("Book Status: Checked out");
System.out.println("Borrower: " + borrower);
System.out.println("Due Date: " + dueDate);
System.out.println("----------------------------------------------------");
}
else if (!(Book.UserList.contains(borrower)))
{
System.out.println("Patron is not a part of library system. Please enter patron in system.");
}
else if (!(Book.BookList.contains(bookCheckOut)))
{
System.out.println(bookCheckOut + " is not in the library. Please enter "
+ "a different book to be checked out");
}
}
public void CheckInBook()
{
Scanner inputread = new Scanner(System.in);
System.out.println("Enter book title to be checked in: ");
String bookCheckIn = inputread.nextLine();
Book checkOut = new Book(bookCheckIn);
if((!Book.BookList.contains(bookCheckIn)) && Book.OrigBookList.contains(bookCheckIn))
{
Book.BookList.add(bookCheckIn);
checkOut.setStatus("IN");
System.out.println("------------------------------------------------------");
System.out.println("-----" + bookCheckIn + " has been checked in!-----");
System.out.println("------------------------------------------------------");
}
else
System.out.println(bookCheckIn + " is not part of the library system. Please enter "
+ "a different book to be checked in");
}
public boolean canBorrow()
{
if(bookCount <= 3)
{
return true;
}
else
{
return false;
}
}
public static void editName()
{
Scanner inputread = new Scanner(System.in);
System.out.println("Enter original patron full name: ");
String origName = inputread.nextLine();
System.out.println("Enter edited patron full name: ");
String editedName = inputread.nextLine();
Collections.replaceAll(Book.UserList, origName, editedName);
System.out.println("------------------------------------------------------");
System.out.println(origName + " has been changed to " + editedName + "!");
System.out.println("------------------------------------------------------");
}
public void newPatron()
{
Scanner inputread = new Scanner(System.in);
System.out.println("Enter patron full name: ");
String name = inputread.nextLine();
Book.UserList.add(name); //add name to userList
Patron patron1 = new Patron(name);
System.out.println("-----------------------------------------------------------------");
System.out.println("-----" + name + " has been added to the library system" + "-----");
System.out.println("-----------------------------------------------------------------");
}
public void bookStatus() //STOPS
{
Scanner input = new Scanner(System.in);
Scanner inputread = new Scanner(System.in);
System.out.println("Enter book title: ");
String checkStatus = inputread.nextLine();
Book status = new Book(checkStatus);
if(Book.OrigBookList.contains(checkStatus) && status.getStatus(checkStatus) == "OUT")
{
System.out.println("Status: checked out");
System.out.println("Borrower: " + status.getBorrower(checkStatus));
}
else if(Book.OrigBookList.contains(checkStatus) && status.getStatus(checkStatus) == "IN")
{
System.out.println("Status: checked in");
System.out.println("Borrower: none");
}
else if(!(Book.OrigBookList.contains(checkStatus)))
System.out.print("Book is not in library system. Please add the book first.");
}
public void searchPatron() //WORKS!!!
{
Scanner inputread = new Scanner(System.in);
System.out.println("Enter patron full name: ");
String checkPatron = inputread.nextLine();
Book search = new Book(checkPatron);
if(Book.UserList.contains(checkPatron))
{
System.out.println("-------------------------------------------------");
System.out.println("Books checked out: " + search.getBook(checkPatron));
System.out.println("-------------------------------------------------");
}
else
System.out.println("Patron is not part of the library system. Please create new patron first.");
}
}
Since you're calling non static methods of Patron and Book you have to make their objects to call these methods. Only static methods can be called directly on the Class. Check links below for details on static members
https://docs.oracle.com/javase/tutorial/java/nutsandbolts/variables.html
https://docs.oracle.com/javase/tutorial/java/javaOO/classvars.html
Couple of things to keep in mind
Constructors should be used to create objects only your Library() constructor is doing too much work, try to put it outside constructor.
Your case 11 was not exiting from the loop, I have added System.exit(0) there.
Close the Scanner object using input.close()
Try some exception handling in the code to be safe.
In Java it's convention to keep first letter small in naming non static fields and methods. Check this link https://docs.oracle.com/javase/tutorial/java/nutsandbolts/variables.html
Here's the corrected code
import java.awt.List;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
import java.util.Collections;
public class Library {
public static void main(String[] args) {
// create new library
Library newLibrary = new Library();
}
public Library() {
Scanner input = new Scanner(System.in);
int choice = 0;
System.out
.println("********************Welcome to the Public Library!********************");
System.out
.println(" Please Select From The Following Options: ");
System.out
.println("**********************************************************************");
while (choice != 9) {
System.out.println("1: Add new patron");
System.out.println("2: Add new book");
System.out.println("3: Edit patron");
System.out.println("4: Edit book");
System.out.println("5: Display all patrons");
System.out.println("6: Display all books");
System.out.println("7: Check out book");
System.out.println("8: Check in book");
System.out.println("9: Search book");
System.out.println("10: Search Patron");
System.out.println("11: Exit");
choice = input.nextInt();
//creating Patron and Book objects
Patron patron = new Patron();
Book book = new Book();
switch (choice) {
case 1: // Add new patron
// ERROR: Patron cannot be resolved or is not a field
patron.newPatron();
break;
case 2: // Add new book
// ERROR: Cannot make a static reference to the non-static
// method
book.addBook();
break;
case 3: // Edit patron name
patron.editName();
break;
case 4: // edit book
// ERROR: Cannot make a static reference to the non-static
// method
book.editBook();
break;
case 5: // display all patrons
System.out.println(Book.UserList);
break;
case 6: // display all books
// System.out.println(Book.OrigBookList);
Book.libraryInventory();
// Book.bookStatus()
break;
case 7: // check out a book
// ERROR: Cannot make a static reference to the non-static
// method
patron.CheckOutBook();
break;
case 8: // check in a book
// ERROR: Cannot make a static reference to the non-static
// method
patron.CheckInBook();
break;
case 9: // search book
// ERROR: Cannot make a static reference to the non-static
// method
patron.bookStatus();
break;
case 10:// search Patron
patron.searchPatron();
break;
case 11: // exit program
//added exit(0)
System.exit(0);
}
}
}
}
I created a method that returns a row of arrays via user input. I managed to display the set of inputted number on the same class using System.out.println by assigning each value in userDigits.
My question is, how can I pass the same value in another class?
public class LottoTicket extends Ticket {
public int NUM_DIGITS = 5;
public int[] userDigits = new int[NUM_DIGITS];
#Override
public void buyTicket() {
Scanner input = new Scanner(System.in);
int number = 0;
double amount = 0;
System.out.println("-------=======LOTTO TICKET SCREEN=======--------");
System.out.println("");
System.out.println("There are three Types (Prima, Ambo and Terro)");
System.out.print("Please select one (P, A, T): ");
String lotteryOption = input.next();
switch (lotteryOption) {
case "P": {
break;
}
case "A": {
break;
}
case "T": {
amount = getAmount(amount);
getUserData(userDigits);
int ticketSold;
ticketSold = +1;
int tik = ticketSold +1;
System.out.println(amount);
System.out.println("Your numbers are: " + userDigits[0] + " "
+ userDigits[1] + " " + userDigits[2] + " " + userDigits[3]
+ " " + userDigits[4] + " ");
System.out.println("Ticket/s Sold: " + tik);
System.out.println("Thank you for playing");
Ticket.pressAnyKeyToContinue();
LotteryApplication.loginScreen();
break;
}
default: {
System.out.println("Invalid Input. Please try again.");
System.out.println("");
buyTicket();
break;
}
}
}
#Override
public double getAmount(double amount) {
Scanner input = new Scanner(System.in);
System.out.print("Please enter amount of money: ");
amount = input.nextDouble();
//input.close();
return amount;
}
#Override
public int getUserData(int[] userInput) {
Scanner input = new Scanner(System.in);
System.out.print("Choose a number from 1 to 90: ");
userDigits[0] = input.nextInt();
System.out.print("Choose a number from 1 to 90: ");
userDigits[1] = input.nextInt();
System.out.print("Choose a number from 1 to 90: ");
userDigits[2] = input.nextInt();
System.out.print("Choose a number from 1 to 90: ");
userDigits[3] = input.nextInt();
System.out.print("Choose a number from 1 to 90: ");
userDigits[4] = input.nextInt();
//key.close();
//Returns last value of array
return userDigits[4];
}
//public int userDigits[];
public static void printTicket(){
// System.out.println(getUserData.userDigits[4]);
// for (int i = 0; i < array.length)
}
}
Well, in this case, since you defined userDigits as public, you can do it easily - it is accessible to any class that has a visibility to your instance of LottoTicket. With the current setup you could do something like this:
// you need to instantiate LottoTicket somewhere in your app
LottoTicket ticket = new LottoTicket();
// get the input from user
ticket.buyTicket();
// at this point you can access the numbers and pass them to some other method like this
checkNumbers(ticket.userDigits);
The example posted above needs you to provide a method checkNumbers that has, for example, the following signature:
public void checkNumbers(int[] numbers) {
// the comparison code goes here...
Also, this is somewhat unrelated to your question, but I'd like to point out two issues with your current code:
defining class fields as public is done rather rarely, more common approach is to define these as private and provide methods for getting/setting the field values; this restricts the operation on these fields to only those you allow - having public field allows anyone who has a visibility to that field to perform basically any operations, which is usually not what you want
you call buyTicket() from default in case user didn't select valid lottery type; in extreme cases this could lead to StackOverflowError - better approach would be to use a loop that keeps asking user for input until a valid one is provided
Hope this helps at least a bit.
You can easily pass input array to method of another class arguments.
class PassValue{
public static void display(int[] elements){
Anotherclass obj= new Anotherclass();
obj.display2(elements);
}
}
class Anotherclass{
public void display2(int[] values){
do whatever you want
}
}
Hello I'm still new to Java and OOP and am having issues trying to get my code to compile. I understand the issue with my code is the instantiation of the same object twice however I'm not sure how I can work around that to compile my code.
package week2;
import java.util.*
public class aBug {
aBug theBug = new aBug();
String Inspecies, Inname;
int Inx, Iny, Inenergy, Inid;
char Insymbol;
Scanner scan = new Scanner(System.in);
aWorld newWorld = new aWorld();
public static void main(String[] args) {
aBug theBug = new aBug();
theBug.mainMenu();
}
public void mainMenu() {
int choice;
do {
System.out.print("1\t Create bug\n");
System.out.print("2\t Enter world\n");
System.out.print("3\t Quit\n");
choice = scan.nextInt();
switch (choice) {
case 1:
bugInit();
break;
case 2:
System.out.println();
newWorld.mapInit(theBug.Inx, theBug.Iny, theBug.Insymbol);
System.out.println();
break;
}
} while (choice != 3);
}
public void bugInit() {
String species, name;
int x, y, energy, id;
char symbol;
System.out.print("Species: ");
species = scan.nextLine();
System.out.print("Name: ");
name = scan.nextLine();
System.out.print("X position: ");
x = scan.nextInt();
System.out.print("Y position: ");
y = scan.nextInt();
System.out.print("Energy: ");
energy = scan.nextInt();
System.out.print("ID: ");
id = scan.nextInt();
theBug.Insymbol = 'b';
theBug.Inspecies = species;
theBug.Inname = name;
theBug.Inx = x;
theBug.Iny = y;
theBug.Inenergy = energy;
theBug.Inid = id;
System.out
.format("\nThe bug is of the species %s, called %s, "
+ "with positions %d & %d, with energy amount: %d, and %d as it's id number\n\n",
theBug.Inspecies, theBug.Inname, theBug.Inx, theBug.Iny,
theBug.Inenergy, theBug.Inid);
}
}
In the constructor you have:
public class aBug {
aBug theBug = new aBug();
...
}
So while creating an instance of aBug (for example in your main) you call new aBug(), which calls the constructor again recurrently with out end overflowing the stack.
I am not sure why do you think you need to create an instance of the object within itself. So it's hard to give any hints. If I guess correctly, you merged the idea of aBug and "main program" in one class. You should split it and put aBug internal stuff in its own class.