Cannot understand enums in java - java

I was looking at an example code provided in my book
enum Coin
{
PENNY(1),
NICKEL(5),
DIME(10),
QUARTER(25);
private final int denomValue;
Coin(int denomValue)
{
this.denomValue = denomValue;
}
int denomValue()
{
return denomValue;
}
int toDenomination(int numPennies)
{
return numPennies / denomValue;
}
}
public class Coins
{
public static void main(String[] args)
{
if (args.length == 1)
{
int numPennies = Integer.parseInt(args[0]);
System.out.println(numPennies + " pennies is equivalent to:");
int numQuarters = Coin.QUARTER.toDenomination(numPennies);
System.out.println(numQuarters + " " + Coin.QUARTER.toString() +
(numQuarters != 1 ? "s," : ","));
numPennies -= numQuarters * Coin.QUARTER.denomValue();
int numDimes = Coin.DIME.toDenomination(numPennies);
System.out.println(numDimes + " " + Coin.DIME.toString() +
(numDimes != 1 ? "s, " : ","));
numPennies -= numDimes * Coin.DIME.denomValue();
int numNickels = Coin.NICKEL.toDenomination(numPennies);
System.out.println(numNickels + " " + Coin.NICKEL.toString() +
(numNickels != 1 ? "s, " : ", and"));
numPennies -= numNickels*Coin.NICKEL.denomValue();
System.out.println(numPennies + " " + Coin.PENNY.toString() +
(numPennies != 1 ? "s" : ""));
}
System.out.println();
System.out.println("Denomination values:");
for (int i = 0; i < Coin.values().length; i++)
System.out.println(Coin.values()[i].denomValue());
}
}
If enum is like a class, is it possible to have the same name for a method and field inside a class, as it has been done here with denomValue?
Why is it calling int numQuarters = Coin.QUARTER.toDenomination(numPennies); in this manner? Is toDenomination() static by default?
In the above case, what is the value of denomValue field? The output for this program hints that it should be equal to QUARTER. But how does that work? Is Coin.QUARTER equivalent to creating a coin object and passing QUARTER as it's constructor argument?

Each of PENNY, NICKEL are instances of Coin class and are static, so they can be accessed as Coin.PENNY.
So when you do :
Coin.QUARTER.toDenomination(numPennies)
you are accessing the QUARTER instance of coin class and calling its toDenomination() method which is an instance method being called on QUARTER instance.
When you do:
PENNY(1) //this actually calls the constructor with one integer argument of Coin class
To check that PENNY is instance of Coin class:
System.out.println(Coin.PENNY.getClass()); //Will show you Coin

Enums are special classes as:
They are constant classes.
The enum values can only be accessed statically.
Hence why Enums have a private constructor.
Once you have gotten the value, the declared methods and attributes can be accessed like an ordinary class.
the values of denomValue depends on the Enum value declared in Coin enum. For example: PENNY enum denomValue is 1 and will always be 1.

Related

Java program not returning any values

I am currently working on a class assignment and cannot figure out why I am getting the output that I am getting. The programming question is:
You operate several hotdog stands. Define a class named HotDogStand
that has an instance variable for the hot dog stand's ID number and an
instance variable for how many hot dogs the stand has sold that day.
Create a constructor that allows a user of the class to initialize
both variables. Also create a method named justSold that increments by
one the number of hot dogs the stand has sold. The idea is that this
method will be invoked each time the stand sells a hot dog so the
total can be tracked. Add another method that returns the number of
hot dogs sold.
Add a static variable that tracks the total number of hot dogs sold by
all the stands and a static method that returns the value in this
variable.
So my code is:
public class HotDogStand {
// instance variable declaration
private int IDNumber;
private int hotDogsSold = 0;
private static int totalSold = 0;
public HotDogStand(int ID, int sold) {
IDNumber = ID;
hotDogsSold = sold;
}
public int getID() {
return IDNumber;
}
public void setID(int ID) {
IDNumber = ID;
}
public void justSold() {
if (hotDogsSold > 0) {
hotDogsSold++;
}
}
public int sold() {
return hotDogsSold;
}
public static int getTotal() {
return totalSold;
}
}
And my testing class is:
public class HotDogTest {
public static void main(String[] args) {
HotDogStand stand1 = new HotDogStand(1, 11);
HotDogStand stand2 = new HotDogStand(2, 17);
HotDogStand stand3 = new HotDogStand(3, 6);
stand1.getID();
stand2.getID();
stand3.getID();
stand1.setID(1);
stand2.setID(2);
stand3.setID(3);
stand1.justSold();
stand2.justSold();
stand3.justSold();
stand1.justSold();
stand1.justSold();
stand1.justSold();
stand3.justSold();
stand1.getTotal();
stand2.getTotal();
stand3.getTotal();
int grandTotal = stand1.getTotal() + stand2.getTotal() + stand3.getTotal();
System.out.println("Stand " + stand1.getID() + " sold a total of " + stand1.getTotal() + " hotdogs.");
System.out.println("Stand " + stand2.getID() + " sold a total of " + stand2.getTotal() + " hotdogs.");
System.out.println("Stand " + stand3.getID() + " sold a total of " + stand3.getTotal() + " hotdogs.");
System.out.println("The total amount of hotdogs sold by all the stands was " + grandTotal);
}
}
My output is:
Stand 1 sold a total of 0 hotdogs.
Stand 2 sold a total of 0 hotdogs.
Stand 3 sold a total of 0 hotdogs.
The total amount of hotdogs sold by all the stands was 0
you are never updating totalSold field. Increment that as well inside justSold() method's if condition.
There is no point at which you change the totalSold variable. justsold increments the instance variable hotDogsSold but getTotal return totalSold.
You need a method getSold which returns the instance variable hotDogsSold.
The other problem is that totalSold is a static variable (it's a class variable; it's not tied to any individual instance of the class like hot dog seller 1 or 2 but rather to the entire model of hot dog sellers). As a result, your grand total would, if totalSold were incremented correctly, give 3 times the number of sold hot dogs for everyone.
Try this:
public void justSold() {
if (hotDogsSold > 0) {
totalSold = hotDogsSold++;
}

Is it possible to use return value of a method in another method?

Hello I'm trying to do this homework and I should write a method that gets some information from other methods that I wrote. (e.g. car type,dates,extras etc.) .So my question is, can i use return values of these methods in my final method without calling them again? This is my main method:
public class Homework3 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
char customer = 'O';
int numberOfCustomers = 0;
int totalEarning= 0;
while(customer != 'N'){
System.out.println("Car Type is " + promptForCarType());
System.out.println("Car rented for " + calculateDays() + " days.");
promptForExtras();
System.out.printf("\nTotal : %d TL",calculateTotal() );
totalEarning += calculateTotal();
numberOfCustomers ++;
System.out.println("Number of customers : " + numberOfCustomers);
System.out.println("Total amount earned : " + totalEarning);
while(customer != 'N' || customer != 'Y'){
System.out.println("A new customer? (Y/N)");
customer = input.next().charAt(0);
customer = Character.toUpperCase(customer);
}
}
}
And I should use car type, days, extras in my calculateTotal() method. I also tried to assign other methods' return values as variables and using them in my final method as parameters but didn't work.For example i tried to write something like this :
public static int calculateTotal(){
int total=0;
int time = calculateDays();
int rate = (time / 7)*5 + (time % 7);
if(promptForCarType().equals("Economy"))
total += 50*rate;
else if(promptForCarType().equals("Midsize"))
total += 70*rate;
else if(promptForCarType().equals("Fullsize"))
total += 100*rate;
total += promptForExtras() * time;
return total;
}
but when i call calculateTotal() in my main method, it automatically calls calculateDays() again
Bascially, what could do, is pass in the value from calculateDays to calculateTotal so you don't need to calculate it again...
System.out.println("Car Type is " + promptForCarType());
in days = calculateDays();
System.out.println("Car rented for " + days + " days.");
promptForExtras();
System.out.printf("\nTotal : %d TL",calculateTotal(days) );
Then you would need to change calculateTotal to allow it to accept the value you want to pass it...
public static int calculateTotal(int time){
int total=0;
int rate = (time / 7)*5 + (time % 7);
//...
For example...

call a method from another class

I'm in an intro programming class, in the lab that I'm currently working on we have to have two classes and pull the methods from one class, "Energy" and have them run in "Energy Driver."
I'm having trouble calling the methods (testOne, testTwo, testThree) over into "EnergyDriver"
public class EnergyDriver
{
public static void main(String [] args)
{
System.out.println(mass1 + " kiolograms, " + velocity1 +
"meters per second: Expected 61250," + " Actual " + kineticE1);
System.out.println(mass2 + " kiolograms, " + velocity2 +
"meters per second: Expected 61250," + " Actual " + kineticE2);
System.out.println(mass3 + " kiolograms, " + velocity3 +
"meters per second: Expected 61250," + " Actual " + kineticE3);
}
}
public class Energy
{
public static void main(String [] args)
{
public double testOne;
{
double mass1;
double velocity1;
double holderValue1;
double kineticE1;
mass1 = 25;
velocity1 = 70;
holderValue1 = Math.pow(velocity1, 2.0);
kineticE1 = .5 *holderValue1 * mass1;
}
public double testTwo;
{
double mass2;
double velocity2;
double holderValue2;
double kineticE2;
mass2 = 76.7;
velocity2 = 43;
holderValue2 = Math.pow(velocity2, 2.0);
kineticE2 = .5 *holderValue2 * mass2;
}
public double testThree;
{
double mass3;
double velocity3;
double holderValue3;
double kineticE3;
mass3 = 5;
velocity3 = 21;
holderValue3 = Math.pow(velocity3, 2.0);
kineticE3 = .5 *holderValue3 * mass3;
}
}
You must have only one main method in any one of class. To call a method from another class you can create an object of that class a call their respective method. Another way is by keeping the calling method to be static so you can access that method via Classname.Methodname.
public class EnergyDriver
{
public static void main(String [] args)
{
Energy energy=new Energy();
System.out.println(mass1 + " kiolograms, " + velocity1 +
"meters per second: Expected 61250," + " Actual " + energy.testOne());
System.out.println(mass2 + " kiolograms, " + velocity2 +
"meters per second: Expected 61250," + " Actual " + energy.testTwo());
System.out.println(mass3 + " kiolograms, " + velocity3 +
"meters per second: Expected 61250," + " Actual " + energy.testThree());
}
}
class Energy
{
public double testOne()
{
double mass1;
double velocity1;
double holderValue1;
double kineticE1;
mass1 = 25;
velocity1 = 70;
holderValue1 = Math.pow(velocity1, 2.0);
kineticE1 = .5 *holderValue1 * mass1;
return kineticE1;
}
public double testTwo()
{
double mass2;
double velocity2;
double holderValue2;
double kineticE2;
mass2 = 76.7;
velocity2 = 43;
holderValue2 = Math.pow(velocity2, 2.0);
kineticE2 = .5 *holderValue2 * mass2;
return kineticE2;
}
public double testThree()
{
double mass3;
double velocity3;
double holderValue3;
double kineticE3;
mass3 = 5;
velocity3 = 21;
holderValue3 = Math.pow(velocity3, 2.0);
kineticE3 = .5 *holderValue3 * mass3;
return kineticE3;
}
}
You can get the value of Kinetic Engergy 1,2,3 by using this code.
You can also use the below code which will use only one method to calculate different values by giving different arguments.
public class EngergyDriver
{
public static void main(String [] args)
{
Energy energy=new Energy();
double mass=25;
double velocity=70;
System.out.println(mass+ " kiolograms, "+velocity+"meters per second: Expected 61250," + " Actual " + energy.testOne(mass,velocity));
}
}
class Energy
{
public double testOne(double mass, double velocity)
{
double mass1;
double velocity1;
double holderValue1;
double kineticE1;
mass1 = 25;
velocity1 = 70;
holderValue1 = Math.pow(velocity1, 2.0);
kineticE1 = .5 *holderValue1 * mass1;
return kineticE1;
}
}
Java programs have SINGLE point of entry and that is through the main method.
Therefore in a single project only one class should have the main method and when compiler will look for that when you run it.
Remember that static methods cannot access non static methods hence main is static therefore it can not access testone two nor three UNLESS you create and object of that type. Meaning in the main method you can have Energy e = new Energy() then access those methods that were not declared with keyword static like e.testone() .
However take note that non static methods can access static methods through Classname.Method name because keyword static entails that only a single copy of that method/variable exists therefore we do not need an object to access it since only one copy exists.
I recommend watching the Java videos from Lynda.com or reading the books Java Head First and Java How To Program (Deitel,Deitel) to give you a boost on your Java knowledge they come with alot of exercises to enhance your knowledge.
Also there are plenty of other questions like this on SO search for them

Beginner Java - Cannot Find Symbol Errors?

I've been trying to figure out why this basic java program wont run. I get about 7 cannot find symbol errors. Any help would be much appreciated. I'd love to know what I'm doing wrong.
The program is just some basic calculations that prompt for some input and output data that show what a speeder's fine would be.
import java.io.*;
import java.util.*;
public class Lab1 {
public static void main (String args[]) {
// Create a scanner to read from keyboard
Scanner kbd = new Scanner(System.in);
System.out.print("\nEnter Driver's FIRST Name.");
String firstName = kbd.next();
System.out.print("\nEnter Driver's LAST Name.");
String lastName = kbd.next();
System.out.print("\nEnter Driver's Age.");
int age = Integer.parseInt(kbd.next());
System.out.print("\nEnter the Speed Limit.");
int speedLimit = Integer.parseInt(kbd.next());
System.out.print("\nEnter Driver's Actual Speed");
int actualSpeed = Integer.parseInt(kbd.next());
System.out.print("\nDid violation occur in construction zone? (yes/no)");
String constructionZone = kbd.next();
int speedDifference = (actualSpeed - speedLimit);
if (speedDifference <= 5) {
int baseFine = 0;
}
else if(speedDifference >= 20) {
int baseFine = (speedDifference / 5) * 50;
}
else {
int baseFine = (speedDifference / 5) * 30;
}
if(constructionZone.equals("yes")) {
int constructionFine = 10;
}
else {
int constructionFine = 0;
}
if(age <= 21 && speedDifference >= 20) {
int underageFine = 300;
}
else {
int underageFine = 0;
}
int totalFine = baseFine + constructionFine + underageFine;
System.out.println("Last Name: " + lastName);
System.out.println("First Name: " + firstName);
System.out.println("Driver Age: " + age);
System.out.println("Speed Limit: " + speedLimit);
System.out.println("Actual Speed: " + actualSpeed);
System.out.println("MPH Over Limit: " + speedDifference);
System.out.println("Base Fine: $" + baseFine);
System.out.println("Construction Zone Fine: $" + constructionFine);
System.out.println("Underage Fine: $" + underageFine);
System.out.println("Total Fine: $" + totalFine);
}
}
Your variables baseFine, constructionFine and underageFine are defined within the scope of if statements. Declare them outside of that scope so that they are visible in the scope of the main method. For example
int baseFine = 0;
if (speedDifference <= 5) {
baseFine = 0;
}
baseFine ,constructionFine ,underageFine These 3 variables are not declared properly. You have declared these three within a local scope. But outside of the scope it can not be recognized.
So declare them as class members.
WHAT IS VARIABLE SCOPE
as you are beginner of java so I think you better know about what variable scope is.
The scope of a variable is the part of the program over which the variable name can be referenced.
You can declare variables in several different places:
In a class body as class fields.
As parameters of a method or constructor.
In a method's body or a constructor's body.
Within a statement block, such as inside a while or for block.
Variable scope refers to the accessibility of a variable. You neither can refer to a variable before its declaration nor you can use them outside the scope
You got variable scoping issues
underageFine , constructionFine and baseFine need to be defined outside of the if/elso to be accessible by the rest of the method.

Method returns zero

It is suppose to return a value of 19 full seats and 68 students remaining!
please help, with my understanding I am returning the right values and assigning them to the correct variables!
public class JetCalculator
{
public static void main(String[] args)
{
int totalStudents = 3013;
int jetCapacity = 155;
int jets;
int students;
jets = calculateJets(jetCapacity, totalStudents);
students = calculateStudents(jetCapacity, totalStudents, jets);
System.out.println("A total of "+ totalStudents + " student require "+ jets + " full seated jets.");
System.out.println("There will be " + students + " students remaining");
System.out.println("_____________________________________________");
System.out.println(jets);
System.out.println(jetCapacity);
System.out.println(students);
}
public static int calculateJets(int totalStudents, int jetCapacity)
{
int fullJets;
fullJets = totalStudents / jetCapacity;
return fullJets;
}
public static int calculateStudents( int jetCapacity, int totalStudents, int jets)
{
int remainingStudents;
remainingStudents = jetCapacity * jets;
return remainingStudents;
}
}
You call calculateJets this way
jets = calculateJets(jetCapacity, totalStudents);
But the argument names for this method imply that you've switched their order in the call
public static int calculateJets(int totalStudents, int jetCapacity)
This means you're actually doing 155 / 3013 which is 0 using integer arithmetic.
You're passing in your parameters back to front.
You call calculateJets by passing capacity then students: calculateJets(jetCapacity, totalStudents); but the method asks for students then capacity: calculateJets(int totalStudents, int jetCapacity).
This is a good argument for consistency in parameter order throughout a class interface.
To help debug this in future, try throwing in a println at the start of methods to see what is happening:
System.out.println("Called calculateJets with totalStudents of " + totalStudents + " and jetCapacity of " + jetCapacity);
Based purely on method names: did you mean to say remainingStudents = totalStudents - (jetCapacity * jets); ?

Categories

Resources