Integer canno be derefrenced - java

I have some problem with my simple code in Java. I want to do aircraft flight search program, but when I leave the variable under the parameter, I get an error:
Airlines.java:14: error: int cannot be dereferenced
String Parameters = flightNumber_go.getParameters();
Anyone have any idea how I could solve this problem?
PS. Sorry for my bad English
import java.util.Scanner;
class Airlines{
public static void main(String args[]) throws Exception{
Flight 524 = new Flight("Moskwa", "Londyn", 140);
Flight 135 = new Flight("Warszawa", "Wroclaw", 60);
Flight 141 = new Flight("Frankfurt", "Rzym", 95);
Scanner flightNumber = new Scanner(System.in);
System.out.println("Enter code of your flight: ");
int flightNumber_go = Integer.valueOf(flightNumber.nextLine());
String Parameters = flightNumber_go.getParameters();
System.out.println(Parameters);
}
}
class Flight{
String departures;
String arrival;
int price;
public Flight(String departures, String arrival, int price){
this.departures = departures;
this.arrival = arrival;
this.price = price;
}
public String getParameters(String ... args){
return "Lot z "+this.departures+" do "+this.arrival+" kosztuje "+this.price;
}
}

To begin with you are misunderstanding how to correctly use an Object as getParameters will only work for the current object, it will not search all the objects you made. You must use a Collection to keep track on all of your objects if you want to find a specific one.
Additionally you should not use variable names to store information, instead store that information inside of the object as an integer.
Here is the modified Flight class:
class Flight {
private String departures;
private String arrival;
private int price;
private int flightNum;
public Flight(String departures, String arrival, int price, int flightNum){
this.departures = departures;
this.arrival = arrival;
this.price = price;
this.flightNum = flightNum;
}
public String getParameters(){
return "Lot z "+this.departures+" do "+this.arrival+" kosztuje "+this.price;
}
public String getDepartures() {
return departures;
}
public String getArrival() {
return arrival;
}
public int getPrice() {
return price;
}
public int getFlightNum() {
return flightNum;
}
public void setDepartures(String departures) {
this.departures = departures;
}
public void setArrival(String arrival) {
this.arrival = arrival;
}
public void setPrice(int price) {
this.price = price;
}
public void setFlightNum(int flightNum) {
this.flightNum = flightNum;
}
}
Note that I added the new parameter, flightNum and made all of your class variables private, with standard getters and setters for access.
Now here is the modified Airlines class that uses an ArrayList to store the Flights:
class Airlines {
public static void main(String args[]) throws Exception{
ArrayList<Flight> flights = new ArrayList<>();
flights.add(new Flight("Moskwa", "Londyn", 140, 524));
flights.add(new Flight("Warszawa", "Wroclaw", 60, 135));
flights.add(new Flight("Frankfurt", "Rzym", 95, 141));
Scanner flightNumber = new Scanner(System.in);
System.out.println("Enter code of your flight: ");
int flightNumber_go = Integer.valueOf(flightNumber.nextLine());
Flight currentFlight = findFlight(flights, flightNumber_go);
System.out.println(currentFlight.getParameters());
}
public static Flight findFlight(ArrayList<Flight> flights, int flightNum) {
for (Flight f : flights) {
if (f.getFlightNum() == flightNum) {
return f;
}
}
//If no flights are found
return null;
}
}
I added a static method called findFlight which takes in the ArrayList and flightNumber you want to find as a parameter, and returns the corresponding Flight. This is done using a simple enhanced for loop. The method will return null if no flight is found, which can modified to return whatever you want for a default case.
Example Run:
Enter code of your flight:
135
Lot z Warszawa do Wroclaw kosztuje 60
Note: It may make sense in your case to use a Map to store the key as the flight number with the Flight as the value which ensures the key is unique and then you do not need flightNumber in the Object itself. This ArrayList is just one way to do it.

Related

To make the object variable private in another class

I have written the code this expected output:
Sample input :
Enter the passenger name:
Priya
Enter the gender(M or F / m or f):
F
Enter the age:
61
Enter the ticket no:
140
Enter the ticket price:
500.0
Sample Output 1 :
Ticket no:143
Passenger Name:Priya
Price of a ticket : 500.0
Total Amount : 375.0
I have to change the total amount value based on the age and gender for which I have written function.
My code:
Person.java
public class Person {
private String name;
private char gender;
private int age;
public void setName(String name ){
this.name = name;
}
public void setGender(char gender){
this.gender = gender ;
}
public void setAge(int age ){
this.age = age;
}
public String getName(){
return this.name;
}
public char getGender(){
return this.gender;
}
public int getAge(){
return this.age;
}
}
BusTicket.java
public class BusTicket {
private int ticketNo;
private float ticketPrice;
private float totalAmount;
Person person = new Person();
int age = person.getAge();
char g = person.getGender();
public void setTicketNo(int ticketNo){
this.ticketNo = ticketNo;
}
public void setTicketPrice(float ticketPrice){
this.ticketPrice = ticketPrice;
}
public void setTotalAmount(float totalAmount){
this.totalAmount = totalAmount;
}
public void calculateTotal()
{
if(age<16)
{
totalAmount = ticketPrice/2;
setTotalAmount(totalAmount);
}
else if(age>=60)
{
totalAmount = 3*(ticketPrice/4);
setTotalAmount(totalAmount);
}
else if(g == 'f'|| g== 'F')
{
totalAmount = 9*(ticketPrice/10);
setTotalAmount(totalAmount);
}
else{
setTotalAmount(ticketPrice);
}
}
public int getTicketNo(){
return this.ticketNo;
}
public float getTicketPrice(){
return this.ticketPrice;
}
public float getTotalAmount(){
return this.totalAmount;
}
}
TestMain.java
import java.util.Scanner;
public class TestMain {
public static BusTicket getTicketDetails()
{
Scanner sc = new Scanner(System.in);
BusTicket bt = new BusTicket();
System.out.println("Enter the ticket no:");
bt.setTicketNo(sc.nextInt());
System.out.println("Enter the ticket price:");
bt.setTicketPrice(sc.nextFloat());
return bt;
}
public static void main (String[] args) {
Scanner sc = new Scanner(System.in);
Person p = new Person();
BusTicket bt;
System.out.println("Enter the passenger name:");
p.setName(sc.nextLine());
System.out.println("Enter the gender(M or F/ m or f):");
p.setGender(sc.next().charAt(0));
System.out.println("Enter the age:");
p.setAge(sc.nextInt());
bt = getTicketDetails();
System.out.println("Ticket no:"+bt.getTicketNo());
System.out.println("Passenger Name:"+p.getName());
System.out.println("Price of a ticket : "+bt.getTicketPrice());
System.out.println("Total Amount : "+bt.getTotalAmount());
}
}
But my TotalAmount value is always coming 0.0, it is not getting updated.
And some test cases are failed please help to resolve them:
Fail 1 -
Incorrect access specifier/modifier for person -Should be a [private]
Fail 2 -
Check whether the signature(Returntype/Argument/AccessSpecifier/MethodName) of the method setPerson is correct
Fail 3-
Check whether the signature(Returntype/Argument/AccessSpecifier/MethodName) of the method getPerson is correct
Please Help
Thanks
You need to call calculateTotal to update totalAmount. Otherwise, it will be always 0.0.
...
System.out.println("Price of a ticket : "+bt.getTicketPrice());
bt.calculateTotal(); // Add this line
System.out.println("Total Amount : "+bt.getTotalAmount());
In your BusTicket class a new Person object is assigned to Person attribute and then you are trying to get age and gender details from that newly created Person object, but at this moment Person's age and gender are not populated yet.
Person person = new Person();
int age = person.getAge();
That's why you are getting 0. What should ideally happen is, you should pass the person object created using the input details to the BusTicket class and populate the BusTicket's person attribute with that person.For now I ll tell just that. :)
Give a try :)
In your BusTicket class, create a getter and setter for the Person object, and set the value from the main method.

Having trouble with constructors and user-input

I'm working on a little project, but I'm having trouble. It has to do with creating classes, constructors, etc. For the class, all data fields have to be private. I must also have two constructors, one default and one parameterized. Here's the class:
public class PetInfo {
private String petName = "na";
private boolean petType = true;
private String petBreed = "na";
private double petAge = 0;
private double petWeight = 0;
private String ownerName = "na";
public PetInfo(){}
public PetInfo(String name, boolean type, String breed, double age, double weight, String owner){
this.petName = name;
this.petType = type;
this.petBreed = breed;
this.petAge = age;
this.petWeight = weight;
this.ownerName = owner;
}
public String getName (){
return petName;
}
public void setName(String name){
petName = name;
}
public boolean getType(){
return petType;
}
public void setType(boolean type){
petType = type;
}
public String getBreed(){
return petBreed;
}
public void setBreed(String breed){
petBreed = breed;
}
public double getAge(){
return petAge;
}
public void setAge(double age){
petAge = age;
}
public double getWeight(){
return petWeight;
}
public void setWeight(double weight){
petWeight = weight;
}
public String getOwner(){
return ownerName;
}
public void setOwner(String owner){
ownerName = owner;
}
}
Here is what I have in my main function:
import java.util.Scanner;
public class Pp1_C00019540 {
public static void main(String[] args) {
PetInfo[] info = new PetInfo[5];
collectInfo(info);
}
public static void collectInfo(PetInfo[] info){
Scanner input = new Scanner(System.in);
for(int i = 0; i < info.length;i++){
System.out.print("Enter pet name: ");
}
}
}
So it prints "Enter pet name: ", but it won't let me input a name. I tried to do:
info[i] = new PetInfo(input.nextLine());
But it tells me "constructor PetInfo.PetInfo(String, boolean, String, double,double, String) is not applicable. Actual and formal arguments differ in length." Is there something wrong with my class that I'm not catching? I tested it and it seemed to work correctly.
And I'm not looking for a definite answer, I could more than likely figure it out myself. I'm just not sure what's going on, especially when it seemed to me like this would work when I passed the constructor the correct parameters.
Basically, your code is trying to call the PetInfo constructor that takes a single string as input. But based on the code you have, no such constructor exists. You just have the large multi-parameter constructor for PetInfo. You need to call the scanner for input several times before you call the constructor. See the code below:
private static void collectInfo(PetInfo[] info) {
Scanner input = new Scanner(System.in);
try {
for (int i = 0; i < info.length; i++) {
System.out.print("Enter pet name: ");
String petName = input.nextLine();
System.out.print("Enter pet type: ");
boolean petType = input.nextBoolean();
input.nextLine();
System.out.print("Enter pet breed: ");
String petBreed = input.nextLine();
System.out.print("Enter pet age: ");
double petAge = input.nextDouble();
input.nextLine();
System.out.print("Enter pet weight: ");
double petWeight = input.nextDouble();
input.nextLine();
System.out.print("Enter pet owner: ");
String petOwner = input.nextLine();
info[i] = new PetInfo(petName, petType, petBreed, petAge, petWeight, petOwner);
}
}
finally {
input.close();
}
}
Hopefully the code above gives you a good illustration of what I'm talking about. Also, don't forget to call input.nextLine() after calls to nextBoolean() and nextDouble(). Lastly, don't forget to close your input scanner to avoid a resource leak.
Hope that helps.
Well it's simple, when you input using scanner. It takes input in a string, since there is no such constructor which takes string as a parameter it is giving you an error.
You need to take the input from scanner in respective datatypes, store them in variables and then call the constructor. I think what you are trying to do is to call the constructor while taking comma separated input from the scanner, that's not possible.

Inputting data into an object

I'm doing a homework assignment, where we were asked to create a banking system. The first option is to create a customer and to store their information in a customer object. The start of my create_customer() method asks for their name and stores it into a newly create Customer object, but when i call the getName() method, nothing comes back. Here's the initial class Atm which holds all the actions for each option.
import java.util.ArrayList;
public class Atm
{
private ArrayList<Customer> cust;
private int starting_account_number;
private int starting_customer_number;
private String admin_pin;
private int interest_rate;
private int transaction_counter;
ConsoleReader console = new ConsoleReader(System.in);
public Atm() // constructor
{
cust = new ArrayList<>(100);
starting_account_number = 1001;
starting_customer_number = 101;
admin_pin = "abcd";
interest_rate = 5;
transaction_counter = 0;
}
void create_customer()
{
Customer customer = new Customer();
System.out.println("Please input your name: ");
customer.setName(console.readLine());
customer.getName();
while (customer.istrue)
{
System.out.println("Please input a 4 digit alphanumeric PIN: ");
customer.setPin(console.readLine());
if (customer.istrue == false) break;
}
System.out.println("A system generated ID was created for you, it is: ");
String customer_id = String.valueOf(starting_customer_number);
customer.setId(customer_id); // set customer ID
starting_customer_number++; //incrememnt customer ID
System.out.print(customer.getId());
cust.add(customer); //puts the customer object into atm class arraylist
}
Here's the customer class
import java.util.ArrayList;
public class Customer
{
public boolean istrue;
private String name;
private String id; // 3 digits string
private String pin; // 4 digits string
private ArrayList<Account> acct;
private double total_bal; // for all accounts
public Customer() //constructor
{
acct = new ArrayList<>(100);
istrue = true;
name = "NoName";
id = "000";
pin = "0000";
total_bal = 0;
}
// public cal_total_bal() { }
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getPin() {
return pin;
}
public void setPin(String pin) {
this.pin = pin;
if (pin.length() != 4)
{
System.out.println("That was not 4 digits, please input a 4 digit alphanumeric PIN: ");
}
else istrue = false;
}
You are calling a method
customer.getName();
But you are not actually doing anything with it.. you might want to print it:
System.out.println(customer.getName());

Java Keyboard.readInput() error

I'm learning java and my programming skills are are good. I have been asked to find out the problem with codes below. when I paste them on netbeans, the error that had been detected was in the public class CheckoutProgram (String wordIn = Keyboard.readInput(); and wordIn = Keyboard.readInput();) and I noticed that the public static void method was empty but I'm not sure it has anything to do with the error. I have tried to find a solution myself but I can't sort it out. Can you help me with this issue? please
import java.io.*;
import java.text.DecimalFormat;
public class CheckoutProgram {
public static void main (String[] args) {
}
public void start() {
SalesItem[] items = getStock();
System.out.print("Type item code (press enter to finish):");
String wordIn = Keyboard.readInput();
SalesItem[] goods = new SalesItem[1000];
int count = 0;
while (wordIn.length()>=4 && wordIn.length()<=4){
for (int i=0;i<items.length;i++) {
if (items[i] != null && wordIn.equals(items[i].getItemCode())){
System.out.println(items[i]);
goods[count] = items[i];
}
}
System.out.print("Type item code (press enter to finish):");
wordIn = Keyboard.readInput();
count++;
}
System.out.println();
System.out.println("==========Bill==========");
double amountDue = 0.0;
for (int i=0; i<count; i++){
System.out.println(goods[i]);
amountDue = amountDue + goods[i].getUnitPrice();
}
System.out.println();
System.out.println("Amount due: $" + new DecimalFormat().format(amountDue));
System.out.println("Thanks for shopping with us!");
}
// method to read in "stock.txt" and store the items for sale in an array of type SalesItem
private SalesItem[] getStock(){
SalesItem[] items = new SalesItem[1000];
try {
BufferedReader br = new BufferedReader(new FileReader("stock.txt"));
String theLine;
int count = 0;
while ((theLine = br.readLine()) != null) {
String[] parts = theLine.split(",");
items[count] = new SalesItem(parts[0],parts[1],Double.parseDouble(parts[2]));
if (parts.length==4){
String discount = parts[3];
String numPurchases = discount.substring(0, discount.indexOf("#"));
String price = discount.substring(discount.indexOf("#")+1);
items[count].setNumPurchases(Integer.parseInt(numPurchases));
items[count].setDiscountedPrice(Double.parseDouble(price));
}
count++;
}
}
catch (IOException e) {
System.err.println("Error: " + e);
}
return items;
}
}
import java.text.DecimalFormat;
public class SalesItem {
private String itemCode; //the item code
private String description; // the item description
private double unitPrice; // the item unit price
// An item may offer a discount for multiple purchases
private int numPurchases; //the number of purchases required for receiving the discount
private double discountedPrice; // the discounted price of multiple purchases
// the constructor of the SalesItem class
public SalesItem (String itemCode, String description, double unitPrice){
this.itemCode = itemCode;
this.description = description;
this.unitPrice = unitPrice;
}
// accessor and mutator methods
public String getItemCode(){
return itemCode;
}
public void setItemCode(String itemCode){
this.itemCode = itemCode;
}
public String getDescription(){
return description;
}
public void setDescription(String description){
this.description = description;
}
public double getUnitPrice(){
return unitPrice;
}
public void setUnitPrice(double unitPrice){
this.unitPrice = unitPrice;
}
public int getNumPurchases(){
return numPurchases;
}
public void setNumPurchases(int numPurchases){
this.numPurchases = numPurchases;
}
public double getDiscountedPrice(){
return discountedPrice;
}
public void setDiscountedPrice(double discountedPrice){
this.discountedPrice = discountedPrice;
}
// the string representation of a SalesItem object
public String toString(){
return description + "/$" + new DecimalFormat().format(unitPrice);
}
}
Keyboard most likely doesn't exist. It isn't a part of the standard Java library. You would have to import a class that uses Keyboard if you are trying to use some custom class to read user input.
I assume you are getting the error because you do not have the class Keyboard. Check for a file called Keyboard.java.. This is more of a comment than an answer.
Firstly you are using public for a class CheckoutProgram so the file name should be same as the class name when you used public access specifier for a class.
Secondly the Keyboard class is missing in your program so please check with these issues.

JAVA Null pointer Exception getTitle method, I can't find it

There's no error while coding it, but when i ran it, it said
Exception in thread "main" java.lang.NullPointerException
at homework.Book.getTitle(Book.java:36)
at homework.BookMain.main(BookMain.java:61)
Java Result: 1
***********************************
package homework;
public class BookMain {
public static void main(String[] args){
int i;
int option;
Book[] bookSet = new Book[20];
bookSet[0] = new Book("I dare you","Joyce Meyer",2007);
bookSet[1] = new Book("Straight from the Heart","Rev. Fr. Mario Jose C. Ladra",2012);
bookSet[2] = new Book("Deliverance From Fear","Bob Buess",1993);
bookSet[3] = new Book("Extraordinary Book of Facts","Bathroom Readers' Institute",2006);
bookSet[4] = new Book("Fat Kid Rules the World","K.L. Going",2003);
Book.numberOfBooks = 5;
Book getter = new Book();
for (i=0; i<Book.numberOfBooks; i++)
{
System.out.println(getter.getTitle(bookSet[i])+" "+getter.getAuthor(bookSet[i])+" "+getter.getYear(bookSet[i]));
}
System.out.println();
for (i=0; i<Book.numberOfBooks; i++)
{
if(getter.getYear(bookSet[i])>2000)
System.out.println(getter.getTitle(bookSet[i])+" "+getter.getAuthor(bookSet[i])+" "+getter.getYear(bookSet[i]));
}
bookSet[5] = new Book("The Lake of Dead Languages","Carol Goodman",2002);
Shelf shelf1 = new Shelf("Shelf1","Bedroom");
Shelf shelf2 = new Shelf("Shelf2","Living room");
Shelf shelf3 = new Shelf("Shelf3","Basement");
Shelf placer = new Shelf();
placer.insertBook(shelf1,bookSet[1]);
placer.insertBook(shelf1,bookSet[2]);
placer.insertBook(shelf2,bookSet[3]);
placer.insertBook(shelf2,bookSet[4]);
placer.insertBook(shelf1,bookSet[5]);
placer.insertBook(shelf1,bookSet[0]);
System.out.println(placer.getShelfName(shelf1)+" "+placer.getLocation(shelf1));
Book aBookInShelf = new Book();
for(i=0; i<shelf1.booksInShelf; i++)
{
aBookInShelf = placer.pickBook(shelf1, i);
System.out.println(getter.getTitle(aBookInShelf)+" "+getter.getAuthor(aBookInShelf)
+" "+getter.getYear(aBookInShelf));
}
}
}
===========================================
Books class:
package homework;
public class Book {
private String title;
private String author;
private int year;
public static int numberOfBooks = 0;
public Book(String title, String author, int year){
this.title=title;
this.author=author;
this.year=year;
}
public Book(){
}
public String getAuthor(Book target){
return target.author;
}
public int getYear(Book target){
return target.year;
}
public String getTitle(Book target){
return target.title;
}
public static void main(String[] args){
}
}
=====================================
Shelves class:
package homework;
public class Shelf {
private String name;
private String location;
public static int booksInShelf=0;
private Book[] shelfBooks = new Book[20];
public Shelf(String name, String location){
this.name = name;
this.location = location;
}
public Shelf(){
}
public String getShelfName(Shelf target){
return target.name;
}
public String getLocation(Shelf target){
return target.location;
}
public void insertBook(Shelf target, Book aBook){
target.shelfBooks[target.booksInShelf] = aBook;
target.booksInShelf++;
}
public Book pickBook(Shelf target, int nthBook){
return target.shelfBooks[nthBook];
}
}
Beside getter/setter design madness it seems that NullPointerException is caused by fact that booksInShelf is static, which means that it belongs to entire Shelf class (instances of this class share value of this field) so when you add book to one Shelf and increment this field, it will be incremented for all instances of Shelf.
Because of that in loop
for(i=0; i<shelf1.booksInShelf; i++)
you are iterating even over positions that were not set yet and are still nulls. Now in
aBookInShelf = placer.pickBook(shelf1, i);
System.out.println(getter.getTitle(aBookInShelf)+" "+getter.getAuthor(aBookInShelf)
+" "+getter.getYear(aBookInShelf));
you are picking this null and using it inside getter.getTitle(null) which will try to invoke return null.title which will case NPE because null doesn't have title.
To fix this problem remove static modifier from booksInShelf field.

Categories