I'm totally new to Java and I'm wondering why my static block is not executing.
public class Main {
public static void main(String[] args) {
Account firstAccount = new Account();
firstAccount.balance = 100;
Account.global = 200;
System.out.println("My Balance is : " + firstAccount.balance);
System.out.println("Global data : " + Account.global);
System.out.println("*******************");
Account secondAccount = new Account();
System.out.println("Second account balance :" + secondAccount.balance);
System.out.println("Second account global :" + Account.global);
Account.global=300;
System.out.println("Second account global :" + Account.global);
Account.add(); }
}
public class Account
{
int balance;
static int global;
void display()
{
System.out.println("Balance : " + balance);
System.out.println("Global data : " + global);
}
static // static block
{
System.out.println("Good Morning Michelle");
}
static void add()
{
System.out.println("Result of 2 + 3 " + (2+3));
System.out.println("Result of 2+3/4 " + (2+3/4));
}
public Account() {
super();
System.out.println("Constructor");
}
}
My output is:
Good Morning Michelle
Constructor
My Balance is : 100
Global data : 200
*******************
Constructor
Second account balance :0
Second account global :200
Second account global :300
Result of 2 + 3 5
Result of 2+3/4 2
I want to know why "Good Morning Michelle" was not displayed when I went in with the second account.
From the research I have done, this static block should execute each time the class is called (new Account).
Sorry for the real beginner question.
Michelle
Your static block that prints "Good Morning Michelle" is a static initializer. They are run only once per class, when that class is first referenced. Creating a second instance of the class will not cause it to run again.
Static blocks are executed the first time the Class is loaded. This is why you see the output once. Check out more details here: Understanding static blocks
Related
so currently I m preparing for Oracle certified associate java...and I 've run to this question: what is the output of the following code
the solution says that s the output is: u u ucrcr
I know that static initializers only gets called once so
i don t get why the third u is printed
package com.company;
class Order {
static String result = "";
{
result += "c";
}
static {
result += "u";
}
{
result += "r";
}
}
public class Main {
public static void main(String[] args) {
System.out.print(Order.result + " ");
System.out.print(Order.result + " ");
new Order();
new Order();
System.out.print(Order.result + " ");
}
}
It outputs Order.result 3 times, that's why u is printed 3 times.
After the order class is loaded, result is u. You do System.out.print(Order.result + " "); to output it the first time, the you do System.out.print(Order.result + " "); to output it the second time. Then you create 2 instances of the Order class, thus appending "cr" twice, and how your result is ucrcr, so you output ucrcr, where you have your third you.
You must take into account the fact that System.out.print is being used here.
Hi, I am working on a CodeHS problem and completed it with confidence, but got it very wrong. I am looking for my mistakes and helpful feedback. Thanks!
*The instructions for the problem are as follows:
We have a simple Battery class. Add two static fields to Battery,
totalVoltage and numOfBatteries. In addition, alter the constructor so that
the Battery class keeps track of both of the new static variables.
Every time a new Battery is constructed, the numOfBatteries should increase by one, and the totalVoltage should increase by the new voltage of the current Battery being constructed.
Hint: totalVoltage should be a double*
The Batterytester is:
public class BatteryTester extends ConsoleProgram
{
public void run()
{
Battery aaBattery1 = new Battery(1.5);
System.out.println("Total voltage: " + Battery.totalVoltage);
System.out.println("Total batteries: " + Battery.numOfBatteries);
Battery aaBattery2 = new Battery(1.5);
System.out.println("Total voltage: " + Battery.totalVoltage);
System.out.println("Total batteries: " + Battery.numOfBatteries);
Battery aaBattery3 = new Battery(1.5);
System.out.println("Total voltage: " + Battery.totalVoltage);
System.out.println("Total batteries: " + Battery.numOfBatteries);
Battery aaBattery4 = new Battery(1.5);
System.out.println("Total voltage: " + Battery.totalVoltage);
System.out.println("Total batteries: " + Battery.numOfBatteries);
}
}
My code is as follows:
public class Battery
{
private double voltage;
public static int numOfBatteries;
public static double totalVoltage;
//adds the new fields to constructor
public Battery(double voltage, double totalVoltage, int numOfBatteries)
{
this.voltage = voltage;
this.totalVoltage = totalVoltage;
this.numOfBatteries = numOfBatteries;
numOfBatteries++;
totalVoltage += voltage; //increments total voltage with voltage param
}
public double getVoltage()
{
return this.voltage;
}
public static int numOfBatteries()
{
return this.numOfBatteries;
}
public static double totalVoltage()
{
return this.totalVoltage;
}
//all of these return the values
}
You don't need this for numOfBatteries() and totalVoltage() methods, since static methods cannot access this.
Batteries should only be taking in one parameter, you have three. Just remove totalVoltage and numOfBatteries and your code will be fixed. Also as the other guy said, you don't need this for the two static methods your creating.
Assignment:
Print person1's kids, apply the incNumKids() method, and print again, outputting text as below. End each line with newline.
Sample output for below program:
Kids: 3
New baby, kids now: 4
Code:
// ===== Code from file PersonInfo.java =====
public class PersonInfo {
private int numKids;
public void setNumKids(int personsKids) {
numKids = personsKids;
return;
}
public void incNumKids() {
numKids = numKids + 1;
return;
}
public int getNumKids() {
return numKids;
}
}
// ===== end =====
// ===== Code from file CallPersonInfo.java =====
public class CallPersonInfo {
public static void main (String [] args) {
PersonInfo person1 = new PersonInfo();
person1.setNumKids(3);
/* Your solution goes here */
System.out.println("Kids: " + person1.getNumKids());
System.out.println("New baby, kids now: " + person1.getincNumKids());
return;
Problem:
I'm having trouble incrementing and including the incNumKids() method, and print again
Don't increment the number of kids within the println statement as it doesn't belong there -- it's not a statement that returns a String, but rather a method that changes the state of your PersonInfo object. Do it on its own on its own line, and then print the number of kids same as you did before, by calling getNumKids(). Also, don't call methods that simply don't exist, getincNumKids()??? There is no such method
public class CallPersonInfo {
public static void main (String [] args) {
PersonInfo person1 = new PersonInfo();
person1.setNumKids(3);
/* Your solution goes here */
System.out.println("Kids: " + person1.getNumKids());
person1.incNumKids();
System.out.println("Kids: " + person1.getNumKids());
// return; // no reason for this
Heres what worked for me on the homework for my class
/* Your solution goes here */
System.out.println("Kids: " + person1.getNumKids());
person1.incNumKids();
System.out.println("New baby, kids now: " + person1.getNumKids());
Its the correct solution for the homework I am working on right now. Hope this helps you. Heres for peeps needing help with hmwk. x3
person1.setNumKids(personsKid);
int addOne;
addOne = personsKid + 1;
System.out.println("Kids: " + person1.getNumKids());
person1.setNumKids(addOne);
System.out.println("New baby, kids now: " + person1.getNumKids());
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++;
}
import java.util.Scanner;
public class RentalDemo
{
public static void main (String[] args)
{
Scanner input = new Scanner (System.in);
String cnumber;
String outnumber;
Rental first=new Rental();
System.out.print("Enter the contract number: ");
cnumber = input.next();
first.setContractNumber(cnumber);
outnumber=first.getContractNumber();
System.out.println("The contract number is: "+outnumber);
Rental Hours = new Rental();
double Hourss = Hours.getHours();
Rental Minutes = new Rental();
double Minutess = Minutes.getMinutes();
SammysRentalPriceWithMethods motto = new SammysRentalPriceWithMethods();
motto.companyMotto();
}
****public static void AlmostThere(double Minutess, double Hourss)
{ double Total_Cost = Hourss * 40 + Minutess;
System.out.println("You rented our equipment for " + Hourss + "complete hours and "+ Minutess + " extra minutes!");
System.out.println("The total cost of a " + Hourss + " hour rental, with " + Minutess + "extra minutes is " + Total_Cost + "at a $40 rate/hr with a $1 rate/extramin!");**
}
This last section here is the part that isn't printing out when I run it, any ideas why? I'm sorry if I wasn't thorough,** I was expecting it to take the correct numbers and show it to the reader but it just gets through the Main method and stops.
You're never calling the AlmostThere() method. That's what's going to print out everything for you.
At the end of your main() method do something like:
AlmostThere(Hourss, Minutess);
You need to call the AlmostThere method or it will never be run.
Try adding
AlmostThere(Minutess,Hourss);
at the end of your Main method.
Its because you are not calling the method AlmostThere. Any method after the main method has to be called in order for you to see the output.
For example, to call you method you could write.
AlmostThere(45.0, 7.0));