import and use methods among different classes? - java

I created a method called calRoomCharges(int cusID) in the class public class transactions extends javax.swing.JFrame
Then I import this class to the class called public class AddReservation extends javax.swing.JFrame
I imported the class as follows.
import myhotel.FrontOffice.transactions;
these both classes are in the same project.
But when I'm going to call method calRoomCharges(int cusID) in AddReservation class it says that there is no such method.
I did this in netbeans.
So howshould I import the class and use the method that I created in another class?
here is the method I created
public double calRoomCharges(int cusId)
{
double tot=0.0;
try
{
//Get Rates
String sql="SELECT nights FROM reservation where cus_id ='"+cusId+"'";
pst=conn.prepareStatement(sql);
rs=pst.executeQuery();
int nights = 0;
if(!rs.next())
{
//handle no result
}
else
{
nights = rs.getInt("nights") ;
}
//Get number of rooms
String sql2="SELECT no_of_rooms FROM reservation where cus_id ='"+cusId+"'";
pst=conn.prepareStatement(sql2);
rs=pst.executeQuery();
int rooms =0;
if(!rs.next())
{
//handle no result
}
else
{
rooms = rs.getInt("no_of_rooms") ;
}
//Get rates
String sql3="SELECT rates from room_type a,rooms b ,reservation r where a.type=b.type AND b.room_no=r.room_no AND r.cus_id='"+cusId+"' group by r.cus_id";
pst=conn.prepareStatement(sql3);
rs=pst.executeQuery();
double roomRates =0.0;
if(!rs.next())
{
//handle no result
}
else
{
roomRates = rs.getDouble("rates") ;
}
//Calculate room charges
tot =roomRates * rooms * nights;
}
catch(Exception e){}
return tot;
}
And this is the way I called it
private void EmpnamefieldMouseClicked(java.awt.event.MouseEvent evt) {
int cusNo =Integer.parseInt(cusID.getText());
double roomCharges = calRoomCharges(cusNo);
}

You simply have to either make the method static or call it through an object
public static double calRoomCharges(int cusId)
{
// ...
}
and call it like that:
double roomCharges = transactions.calRoomCharges(cusNo);
or call it through a created object:
transactions t = new transactions();
double roomCharges = t.calRoomCharges(cusNo);
And a good thing is to name classes with a first capital letter so you'd have class Transactions

You have 2 possibilities of calling the calRoomCharges method:
the method is a static method and you can call it via:
transactions.calRoomCharges(123);
the method is an object method, so you have to create an object first like:
transactions obj = new transactions();
obj.calRoomCharges(123);

Related

Store different object type in one array and print each one with their methods

I am trying to create a parent class for cars and subclasses from it. Each one has separate methods and store them in an array then if the class are subclass try to call the method on it.
Parent class
public class car {
public String name ;
public double price ;
public car (String name , int price) {
this.name = name ;
this.price = price;
}
public String toString() {
return "car name : "+this.name
+" Price : " +this.price ;
}
}
Sub class
public class CarMotors extends car {
public float MotorsCapacity ;
public CarMotors( String name, int price , float MotorsCapacity) {
super(name, price);
this.MotorsCapacity = MotorsCapacity ;
}
public float getMotorsCapacity() {
return this.MotorsCapacity;
}
}
Main class
public class Test {
public static void main(String[] args) {
car [] cars = new car[2] ;
cars[0] = new car("M3" , 78000);
cars[1] = new CarMotors("M4" , 98000 , 3.0f);
for(int i=0 ;i<2;i++){
if(cars[i] instanceof CarMotors) {
System.out.println(cars[i].getMotorsCapacity()); // error here
}else {
System.out.println(cars[i].toString());
}
}
}
}
As you can see, I can't print the getMotorsCapacity(). I am new to Java. I think there is a cast that need to happen, but I don't now how.
Being short... a class only can see what its yours behaviors.
In your example CarMotors is a Car, that's fine.
But the behavior getMotorsCapacity() is created in CarMotors and it wasn't in Car.
That error occurs because, it's OK in a variable Car you are able to put an instance of CarMotors because CarMotors is a Car. So, any method that is in Car is also in CarMotors, yes, you can call. Look at cars[i].toString() there's no problem here.
You need explicitly say to compiler:
"- oh, right, originally this variable is a Car, but I know that is a CarMotors inside that. I will make a cast here, OK compiler? Thanks."
System.out.println(((CarMotors) cars[i]).getMotorsCapacity());
Or, to be more clear:
CarMotors carMotors = ((CarMotors) cars[i]);
System.out.println(carMotors.getMotorsCapacity());

Getting Values of 3 to 5 Interger Variables from a difrerent Class in JAVA

I'm currently doing a mini parking system for our JAVA bootcamp.
I'm trying to get the value of the integer variables into a different class.
These variables are results of the sql counts of total parked (countCar,countMotor, and countVan).
This is what I did:
I stored them in a class called SQLCountResult:
public class SQLConnections {
public Connection con = null;
public void parkInSQL() {
con = dbConnect.con();
int countCar;
int countMotor;
int countVan;
int parkCar;
int parkMotor;
int parkVan;
int[] vehicleTotal = new int[3];
String qCar = "SELECT COUNT(*) FROM `vehicle` WHERE `vType` = 1 AND `parkout` IS NULL";
String qMotor = "SELECT COUNT(*) FROM `vehicle` WHERE `vType` = 2 AND `parkout` IS NULL";
String qVan = "SELECT COUNT(*) FROM `vehicle` WHERE `vType` = 3 AND `parkout` IS NULL";
try {
Statement stmtCar = con.createStatement();
Statement stmtMotor = con.createStatement();
Statement stmtVan = con.createStatement();
ResultSet rsCar = stmtCar.executeQuery(qCar);
ResultSet rsMotor = stmtMotor.executeQuery(qMotor);
ResultSet rsVan = stmtVan.executeQuery(qVan);
rsCar.next();
rsMotor.next();
rsVan.next();
countCar = rsCar.getInt(1);
countMotor = rsMotor.getInt(1);
countVan = rsVan.getInt(1);
} catch(SQLException e) {
e.printStackTrace();
}
}
}
Now I want to call countCar, countMotor, and countVan to another class called Park. My code for the Park class is below:
public class Park {
public Connection con = null;
public void parkMethod() {
SQLConnections sqlConnections = new SQLConnections();
sqlConnections.parkInSQL();
}
}
I also tried using extend but this didn't work either. How can I call these variables to the Park class?
I suggest you first do some supplementary reading on class members and using objects. If you are not familiar with objects, read this comprehensive article called What Is an Object?. I cannot stress how important it is to understand this. The very concept of "Object Oriented Programming" is centered around objects. Once you have familiarized yourself with this, then go on and read the rest of my answer.
Now that you are familiar with the articles I cited above, I will begin by setting up some fields, which are explained in the "Declaring Member Variables" article. First we need ask ourselves, "Which variables are we trying to retrieve in our Park class?" As you mentioned in your question, the concerned variables are countCar, countMotor, and countVan.
We have identified the variables we are after. Now what? The next step is to change these variables to fields so that they don't get gobbled up by the garbage collector when your parkInSQL method returns. This is a simple task. Let's start by removing the variables from your parkInSQL method:
public void parkInSQL() {
con = dbConnect.con();
̶ ̶i̶n̶t̶ ̶c̶o̶u̶n̶t̶C̶a̶r̶;̶
̶ ̶i̶n̶t̶ ̶c̶o̶u̶n̶t̶M̶o̶t̶o̶r̶;̶
̶ ̶i̶n̶t̶ ̶c̶o̶u̶n̶t̶V̶a̶n̶;̶
//...
}
Next we need to declare these variables as fields. To do that, simply place the variable declarations at the top of your class, just like you did with your Connection variable:
public class SQLConnections {
public Connection con = null;
public int countCar;
public int countMotor;
public int countVan;
//...
}
Notice that I used the public access modifier. This is to make sure that these fields will be visible to our Park class (We could make them private, but that would get us into getters and setters, which is a lesson for another time).
Once we have our variables declared as fields, we should be all set with the SQLConnections class. The rest is easy as pie.
You already have half of the work done. If you look at your parkMethod, you'll see that you constructed an SQLConnections object:
SQLConnections sqlConnections = new SQLConnections();
Now all we need to do is reference the newly created fields, which is explained in the "using objects" article I cited above. After you call sqlConnections.parkInSQL(), you can reference the fields with sqlConnections.countCar, sqlConnections.countMotor, and sqlConnections.countVan:
public class Park {
public Connection con = null;
public void parkMethod() {
SQLConnections sqlConnections = new SQLConnections();
sqlConnections.parkInSQL();
int countCar = sqlConnections.countCar;
int countMotor = sqlConnections.countMotor;
int countVan = sqlConnections.countVan;
}
}
Now you can operate on these values accordingly.
You could change the scope of the variables.
Move this:
int countCar;
int countMotor;
int countVan;
outside of the parkInSQL method, and add the access modifier, public:
public int countCar;
public int countMotor;
public int countVan;
Then you can access it from the Park class like this:
public class Park {
public Connection con = null;
public void parkMethod() {
SQLConnections sqlConnections = new SQLConnections();
int iAmUsingCountCar = sqlConnections.countCar;
}
}
Variables defined inside a method are local to that method. If you want to share variables between class/methods, then you'll need to specify them as member variables of the class. You should initialise it outside the methods.
public class SQLConnections {
public int countCar;
public int countMotor;
public int countVan;
//...
}
public class VehicleStatistics {
private int countCar;
private int countMotor;
private int countVan;
public VehicleStatistics(int countCar, int countMotor, int countVan) {
this.countCar = countCar;
this.countMotor = countMotor;
this.countVan = countVan;
}
public int getCountCar() {
return countCar;
}
public void setCountCar(int countCar) {
this.countCar = countCar;
}
public int getCountMotor() {
return countMotor;
}
public void setCountMotor(int countMotor) {
this.countMotor = countMotor;
}
public int getCountVan() {
return countVan;
}
public void setCountVan(int countVan) {
this.countVan = countVan;
}
}
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class VehicalesDAOImpl {
private Connection connection;
public VehicalesDAOImpl(Connection connection) {
this.connection = connection;
}
public VehicleStatistics getVehicleStatistics() {
String qCar = "SELECT COUNT(*) FROM `vehicle` WHERE `vType` = 1 AND `parkout` IS NULL";
String qMotor = "SELECT COUNT(*) FROM `vehicle` WHERE `vType` = 2 AND `parkout` IS NULL";
String qVan = "SELECT COUNT(*) FROM `vehicle` WHERE `vType` = 3 AND `parkout` IS NULL";
VehicleStatistics result = null;
try {
Statement stmtCar = connection.createStatement();
Statement stmtMotor = connection.createStatement();
Statement stmtVan = connection.createStatement();
ResultSet rsCar = stmtCar.executeQuery(qCar);
ResultSet rsMotor = stmtMotor.executeQuery(qMotor);
ResultSet rsVan = stmtVan.executeQuery(qVan);
rsCar.next();
rsMotor.next();
rsVan.next();
int countCar =rsCar.getInt(1);
int countMotor =rsMotor.getInt(1);
int countVan =rsVan.getInt(1);
result = new VehicleStatistics(countCar, countMotor, countVan);
} catch(SQLException e) {
//log error
} finally {
//close connections etc...
}
return result;
}
}

Passing Value In Java

I was given a task to create a java program that use this 3 classes. Main class, Menu class and Coffee Class. Now i need to pass value from menu class to coffee class. But the problem is i dont exactly know how to do it since im still new with java.
CoffType pass the value to CoffeeName.
NumBag pass the value to NumberOfBag.
This is menu class(programmer defined class 1)
import java.util.*;
public class Menu {
Scanner scan = new Scanner(System.in);
public String coffType;
public int numBag;
public void setCoffType() {
System.out.println("\t\tChoose Your Coffee");
System.out.println("\n[1] Arabica\tRM12.50 per bag");
System.out.println("\n[2] Robusta\tRM15.00 per bag");
coffType = scan.nextLine();
}
public void setNumBag() {
System.out.println("Enter amount you wish to buy");
numBag = scan.nextInt();
}
}
Coffee Class(programmer defined class 2)
public class Coffee{
private String coffeeName;
private double coffeePrice;
private double amountPay;
private int numberOfBag;
private double discount;
public Coffee() { // constructor
coffeeName = "unknown";
coffeePrice = 0.00;
amountPay = 0.00;
numberOfBag = 0;
discount = 0.00;
}
public double getCoffeePrice() {
if(coffeeName.equalsIgnoreCase("arabica")) {
coffeePrice = 12.50 * numberOfBag;
}
else if(coffeeName.equalsIgnoreCase("robusta")) {
coffeePrice = 15.00 * numberOfBag;
}
System.out.println("Price RM: " +coffeePrice);
return coffeePrice;
}
public double getDiscount() {
if(numberOfBag>0 && numberOfBag<=50) {
discount = coffeePrice*0;
}
if(numberOfBag>50 && numberOfBag<=100) {
discount = coffeePrice*0.10;
}
if(numberOfBag>100 && numberOfBag<=150) {
discount = coffeePrice*0.15;
}
if(numberOfBag>150 && numberOfBag<=200) {
discount = coffeePrice*0.20;
}
if(numberOfBag>200) {
discount = coffeePrice*0.25;
}
System.out.println("Discount RM: " +discount);
return discount;
}
public double getAmountPay() {
amountPay = coffeePrice - discount;
System.out.println("\nTotal Need To Pay RM: " +amountPay);
return amountPay;
}
}
I want to pass coffType to coffeeName and numbag to numberOfBag. How can i change these values?
In CoffeClass create a constructor that receives the parameter that you want to set:
public Coffee(String coffeeName, double amountPay, int numberOfBag) {
this.coffeeName = coffeeName;
this.amountPay = amountPay;
this.numberOfBag = numberOfBag;
}
In MenuClass you will instantiate the object Coffe with the selected values by the user:
Coffe coffeOne = new Coffe(coffeName, amoutPay, numBag);
In the same class use the object to get the discount:
double discountCoffeOne = coffeOne.getDiscount();
You're done.
You use the CoffeClas as a model to an object with the values that you want. That way you can have a lot of different coffe just instantiating another Coffe with another name and using it.
When needed you should use getters and setters to change the attributes of an object, when needed means you should not create them when the values are not supposed to change or the other classes should not have permission to change these attributes.
public setCoffeeName(String coffeeName){
this.coffeeName = coffeName
};
public getCoffeeName(){
return coffeName;
}
;)
Oh, and just like azro said:
"Please follow conventions, and start naming attributs/variables with lowercase"
Here, inorder to pass the value of CoffType to CoffeeName and NumBag to NumberOfBag we can either use a parameterized constructor or setters. Both ways we can pass the value from Menu class to Coffee class.
Using parameterized constructor
create parameterized constructor in the Coffee class and instantiate the Coffee class from the Menu class.
Setter
create 2 setters to set each of NumberOfBag and CoffeName in the Coffee class and set the value by instatiating Coffee class and setting the value to both.

Methods with same name as its class? [duplicate]

This question already has answers here:
Java Constructors
(10 answers)
Closed 5 years ago.
public class Person {
private int age;
public Person(int initialAge) {
if (initialAge<= 0) {
System.out.println("Age is not valid, setting age to 0.");
}
else {
age = initialAge;
}
// Add some more code to run some checks on initialAge
}
public void amIOld() {
if (age < 13) {
System.out.print("You are young.");
}
else if (age >= 13 && age < 18) {
System.out.print("You are a teenager.");
}
else {
System.out.print("You are old.");
}
// Write code determining if this person's age is old and print the correct statement:
System.out.println(/*Insert correct print statement here*/);
}
public void yearPasses() {
age += 1;
}
public static void main(String[] args {
Scanner sc = new Scanner(System.in);
int T = sc.nextInt();
for (int i = 0; i < T; i++) {
int age = sc.nextInt();
Person p = new Person(age);
p.amIOld();
for (int j = 0; j < 3; j++) {
p.yearPasses();
}
p.amIOld();
System.out.println();
}
sc.close();
}
}
In the code above, when an instance of the person class is created with a parameter, does it automatically call the Person method within the class?
is the code
Person p = new Person(age);
a constructor or a method call? is it both?
What is the purpose of having a method with the same name as the class?
How does it function?
I, personally, do not like a method with the same nam as the class it is in, but:
public class Person {
public Person() {} // constructor
public void Person {} // method
public static void main(String... args) {
Person p = new Person();
p.Person();
}
}
Generally, a class's name should be a noun, while a method's name should be a verb.
That's called the constructor. It's axecuted when you create a new instance like this: Person me = new Person(99);
You can have multiple constructors like:
enter code here
public Person(int initialAge) {
if (initialAge<= 0) {
System.out.println("Age is not valid, setting age to 0.");
}
else {
age = initialAge;
}
}
public Person() {
age = 0;
}
in the same class. In that case if you create an instance like this: like this: Person me = new Person(99); only the first constructor is called and if you create an instance like this: Person me = new Person(); only the second one (unless you have one referencing the other of course).
A mehtode named like the class and without void or any returntyp is called a constructor.
class MyClass {
public MyClass () {
//constructor code here
}
}
Every calss has a default constructor (showen above) witch does not have to be expilcitly written out to be used (generated by the compiler) but it can be overritten and overloaded for more functunallity.
A constructor is called everytime when an object of the class is generated.
class Person {
pulbic int age;
public Person (int age) {
this.age = age;
}
}
class Main {
public static void main(String args[]) {
//creating 2 objects of person
Person p1 = new Person(23)
Person p2 = new Person(51)
}
}
This programm now generates 2 objects of person the objct p1 holds in the age variable the value 23 and the objct p2 holds in the age variable the value 51.
The ages are set by the constructor called with the new Person(int age) statment.
If you have not initialized an class vriable (in this case int age) but set its value over a constructor, it is treated by the rest of the class as if it was initialized with a specific value.
You can force the programmer with constructors to set specific attributs of an class at its creation and can therfor be sure that this values are set.
If you overload constructors you can call another constructor with:
this(/*Overloaded parameters*/);
Constructors also can not call any methodes (exept other constructors) of the class, because the class is not fully generated a the time the constructor is running.
When an object of a class is created then
Static block is executed first
Constructor if not defined then default Constructor
After that method called with that object.
Constructor is not a method as it does not have any return type.If constructor not defined in the class then default constructor is called automatically.
Otherwise particular Constructor will be called when creating an object.

How do I create an object from another class (BlueJ)

I am making a program that simulates a Store and a Member. I am trying to write a method, memberRegister2(). This method is the the Store class but calls the constructor from the Member class to make a member object. This method is to be passed the name, id and pinNumber as parameters and then creates the Member object, which is to be stored in a local variable 'member'. I have no idea how to do this. As you will see from the code below I have tried to use the 'Member member = new Member()' But i do not know how to make the parameters user input.
(P.S I am using BlueJ)
Here is my code for both classes hopefully making my question make more sense. I am very new to java so excuse bad coding.
public class Store
{
// instance variables
private String storeName;
private int total;
//Member member;
/**
* Constructor for objects of class Store
*/
public Store(String newStoreName, int newTotal)
{
// initialise instance variables
storeName = newStoreName;
total = newTotal;
}
//Accessor Methods
public String getStoreName()
{
return storeName;
}
public int getTotal()
{
return total;
}
public void memberRegister1(Member newMember)
{
System.out.println("Salford Thrifty " + storeName + ": Welcome " + newMember.getName() + " (id:" + newMember.getId() + ")" );
}
public void memberRegister2()
{
//Member member = new member(memberName, memberId, memberPinNumber);
}
//Mutator Methods
public void newStoreName(String newName)
{
storeName = newName;
}
public void newTotal(int newTotal)
{
total = newTotal;
}
}
and the Member class
public class Member
{
// instance variables
private String name;
private String id;
private String pinNumber;
/**
* Constructor for objects of class Member
*/
public Member(String memberName, String memberId, String memberPinNumber)
{
// initialise instance variables
name = memberName;
id = memberId;
pinNumber = memberPinNumber;
}
public Member()
{
// initialise instance variables
name = "Bob";
id = "ASD123";
pinNumber = "5678";
}
//Accessor Methods
public String getName()
{
return name;
}
public String getId()
{
return id;
}
public String getPinNumber()
{
return pinNumber;
}
//Mutator Methods
public void newName(String newMemberName)
{
name = newMemberName;
}
public void newId(String newMemberId)
{
name = newMemberId;
}
public void newPinNumber(String newMemberPinNumber)
{
name = newMemberPinNumber;
}
}
I have been told to keep the variable at the top private and use pointers? Not sure what this means but it has not been explained to me very well.
You can a Scanner to read the user's input like so.
Scanner s = new Scanner(System.in);
String userInput = s.nextLine();
Then just initialize your member instance using the strings entered by the user.
String memberName, memberId, memberPin;
Scanner s = new Scanner(System.in);
System.out.println("Enter a name");
memberName = s.nextLine();
System.out.println("Enter an id");
memberId = s.nextLine();
System.out.println("Enter a pin");
memberPin = s.nextLine();
Member m = new Member(memberName, memberId, memberPin);
Also, you probably want to make pin, and maybe the id ints instead of strings.
Here's something I have from an old class that should show you how:
SavingsAccount myAccount = new SavingsAccount(200, 5);
So when you want to create an object from another class you have to use that second class to initialize it as shown above the SavingsAccount is like int it instantiates the object and then the two integers SavingsAccount(200, 5); is used because the method within the second class is instantiated with two integers of its own so the object you are creating must have two integers of its own. And what I mean by the method has two integer instantiated is as shown in the code below:
public SavingsAccount(double amount, double rate)
{
super(amount);
interestRate = rate;
}
if you do not instantiate a method with two objects within the parentheses then you do not need them within:
SavingsAccount myAccount = new SavingsAccount(200, 5);
I hope this helps any with your question i'm fairly new myself and am trying to help with as much as I can My course uses BlueJ as well and I know a good bit about BlueJ so I hope this helps.

Categories