Java calling method in another class - java

I am trying to create a Java class with certain number of pizzas that decreases in number
if someone steals it.
I have two classes.
class House where pizza is,
public class House {
private static int totalPizzas;
public House() {
totalPizzas = totalPizzas;
}
public int getTotalPizzas() {
return totalPizzas;
}
public static void setTotalPizzas(int totalPizzas) {
totalPizzas = totalPizzas - Thief.stealPizza(House stolenPizza);
}
}
and class Thief that steals the pizza.
public class Thief {
private String name;
private int age;
public Thief() {
name = "abc";
age = 11;
}
public static void stealPizza(House stolenPizza) {
???????
}
}
My main concern is the ??????? part where I feel like I should set stolenPizza to certain
integers but
stolenPizza = 1;
certainly does not work.
Could someone give me a bit of advice on how I should approach this?
Thank you very much for reading.

One way to do it would be to do something like:
public class Thief {
private String name;
private int age;
public Thief() {
name = "abc";
age = 11;
}
public static void stealPizza() {
House.setTotalPizzas(House.totalPizzas - 1);
}
}
public class House {
private static int totalPizzas;
public House() {
totalPizzas = totalPizzas;
}
public int getTotalPizzas() {
return totalPizzas;
}
public static void setTotalPizzas(int totalPizzas) {
House.totalPizzas = totalPizzas;
}
}

Your constructor is missing something if I understand your code right:
Your code
public House() {
totalPizzas = totalPizzas;
}
will set the amount of totalPizzas on itself without assigning any "real" integer value to it. Try
public House(int totalPizzas) {
totalPizzas = totalPizzas;
}
so that you actually can assign a number of Pizzas to the house when calling the constructor, for example:
House house = new House (12);
if you want to have 12 Pizzas in the house.

Related

How to change the value of private variable in java

I started to programm in Java since Yesterday, and I have the biggest question of my entire programmer life(since Yesterday).
For example, let's say I have a code like this:
public class itsAClass {
static private String A;
public static void main() {
A = "This should be changed";
}
public String something() {
return A;
}
}
I wanted to use the method something() in another Class to get the String Sentence of A, but I got only null.
How can I change the value of A, so that the another Class can get the Value "This should be changed"?
If you just want to bring this code to work you just can make something() static as well.
But this will be not the right way to approach this problem.
If you want to hold code in the main class you could do something like this:
public class AClass {
private String a;
public static void main() {
AClass myC = new AClass();
myC.setA("This should be changed");
// than use myC for your further access
}
public String something() {
return a;
}
public String getA() {
return a;
}
public void setA(String a) {
this.a = a;
}
}
If you want to access it by a external class without direct reference you can checkout the singleton pattern.
public class AClass {
private final static AClass INSTANCE = new AClass();
private String a;
public static void main() {
getSingleton().setA("This should be changed");
}
public String something() {
return a;
}
public String getA() {
return a;
}
public void setA(String a) {
this.a = a;
}
public static AClass getSingleton() {
return INSTANCE;
}
}
This way you can access it via AClass.getSingleton() from any location of your code.
You have to call your main() function.
In another class:
itsAClass aClassObj = new itsAClass();
aClassObj.main();
// or rather itsAClass.main() as it is a static function
// now A's value changed
System.out.println(aClassObj.something());
the way to set the value of private variable is by setter and getter methods in class.
example below
public class Test {
private String name;
private String idNum;
private int age;
public int getAge() {
return age;
}
public String getName() {
return name;
}
public String getIdNum() {
return idNum;
}
public void setAge( int newAge) {
age = newAge;
}
public void setName(String newName) {
name = newName;
}
public void setIdNum( String newId) {
idNum = newId;
}
}
you can call method main() in method something().
public class itsAClass{
static private String A;
public static void main() {
A = "This should be changed";
}
public String something() {
main();
return A;
}
public static void main(String[] args){
itsAClass a1 = new itsAClass();
System.out.println(a1.something());// prints This should be changed
}
}

How to handle the Duplicated blocks

I ran sonarqube, but it informed me the error
"Duplicated blocks" in class Gold & Silver.
I modified many things, but it didn't solve the problem
Here is my source
Gold and Silver is extends Plan
Here is a Plan.Source
public abstract class Plan {
public abstract double getBasicRate();
public abstract int getBasicMinute();
public abstract double getAdditionalLineRate();
public abstract double getRatePerExcessMinute();
public abstract String getPlanName();}
Here is Gold.Source
public class Gold extends Plan {
private static final double BASIC_RATE = 49.95;
private static final int BASIC_MINUTE = 1000;
private static final double ADDITIONAL_LINE_RATE = 14.50;
private static final double RATE_PER_EXCESS_MINUTE = 0.45;
private static final String PLAN_NAME = "Gold";
public double getBasicRate() {
return BASIC_RATE;
}
public int getBasicMinute() {
return BASIC_MINUTE;
}
public double getAdditionalLineRate() {
return ADDITIONAL_LINE_RATE;
}
public double getRatePerExcessMinute() {
return RATE_PER_EXCESS_MINUTE;
}
public String getPlanName() {
return PLAN_NAME;
}
}
Here is a Silver.Source
public class Silver extends Plan {
private static final double BASIC_RATE = 29.95;
private static final int BASIC_MINUTE = 500;
private static final double ADDITIONAL_LINE_RATE = 21.50;
private static final double RATE_PER_EXCESS_MINUTE = 0.54;
private static final String PLAN_NAME = "Silver";
public double getBasicRate() {
return BASIC_RATE;
}
public int getBasicMinute() {
return BASIC_MINUTE;
}
public double getAdditionalLineRate() {
return ADDITIONAL_LINE_RATE;
}
public double getRatePerExcessMinute() {
return RATE_PER_EXCESS_MINUTE;
}
public String getPlanName() {
return PLAN_NAME;
}
}
please help me
The code in Gold and Silver is identical, except from the data being assigned to the variables. You could refactor to something like this to remove duplication:
public class Plan {
private final double BASIC_RATE;
private final int BASIC_MINUTE;
private final double ADDITIONAL_LINE_RATE;
private final double RATE_PER_EXCESS_MINUTE;
private final String PLAN_NAME;
public Plan(double BASIC_RATE, int BASIC_MINUTE,
double ADDITIONAL_LINE_RATE, double RATE_PER_EXCESS_MINUTE,
String PLAN_NAME) {
this.BASIC_RATE = BASIC_RATE;
this.BASIC_MINUTE = BASIC_MINUTE;
this.ADDITIONAL_LINE_RATE = ADDITIONAL_LINE_RATE;
this.RATE_PER_EXCESS_MINUTE = RATE_PER_EXCESS_MINUTE;
this.PLAN_NAME = PLAN_NAME;
}
public double getBasicRate() {
return BASIC_RATE;
}
public int getBasicMinute() {
return BASIC_MINUTE;
}
public double getAdditionalLineRate() {
return ADDITIONAL_LINE_RATE;
}
public double getRatePerExcessMinute() {
return RATE_PER_EXCESS_MINUTE;
}
public String getPlanName() {
return PLAN_NAME;
}
}
Then Gold would look something like this:
public class Gold extends Plan {
public Gold() {
super(49.95, 1000, 14.50, 0.45, "Gold");
}
}
What we have done here is take code that is shared by 2 classes and moved it up into its parent class. By calling the super constructor in Gold we assign the variables to the values required by this implementation of the super class Plan.
We've also removed the static from the class variables. This means that the variables will be related to an instance of the class rather than the class itself.
We do this so that the variables in Plan will be related to each instance of Plan. This means we can use them in both the extending classes without data being mixed between.
In a lot of cases you wouldn't usually use static unless you actively wanted a variable to be accessible without a class instance. You can read more about static here.
I had this issue recently. Although you already have an accepted solution (and it's been 4 years), I would like to share another way.
I prefer to keep these constants as I find it more readable. A (soooo) simple solution was to rename the constant names ;) (i.e - prefixing them with SILVER_ or GOLD_).
KISS principle and it worked perfectly.
public class Gold extends Plan {
private static final double GOLD_BASIC_RATE = 49.95;
private static final int GOLD_BASIC_MINUTE = 1000;
private static final double GOLD_ADDITIONAL_LINE_RATE = 14.50;
private static final double GOLD_RATE_PER_EXCESS_MINUTE = 0.45;
private static final String GOLD_PLAN_NAME = "Gold";
public double getBasicRate() {
return GOLD_BASIC_RATE;
}
public int getBasicMinute() {
return GOLD_BASIC_MINUTE;
}
public double getAdditionalLineRate() {
return GOLD_ADDITIONAL_LINE_RATE;
}
public double getRatePerExcessMinute() {
return GOLD_RATE_PER_EXCESS_MINUTE;
}
public String getPlanName() {
return GOLD_PLAN_NAME;
}
If you really want to have a separate Gold and Silver class like this you can't avoid the duplicate code blocks. You could suppress the Sonar violations, either by adding the following line above the line causing the violation (see Sonar FAQ):
// NOSONAR
Alternatively you could use an enum to represent these values:
public enum Plan {
GOLD(49.95, 1000, 14.50, 0.45, "Gold"),
SILVER(29.95, 500, 21.50, 0.54, "Silver");
private double basicRate;
private int basicMinute;
private double additionalLineRate;
private double ratePerExcessMinute;
private String planName;
private Plan(double basicRate, int basicMinute, double additionalLineRate, double ratePerExcessMinute, String planName) {
this.basicRate = basicRate;
this.basicMinute = basicMinute;
this.additionalLineRate = additionalLineRate;
this.ratePerExcessMinute = ratePerExcessMinute;
this.planName = planName;
}
public double getBasicRate() {
return basicRate;
}
public int getBasicMinute() {
return basicMinute;
}
public double getAdditionalLineRate() {
return additionalLineRate;
}
public double getRatePerExcessMinute() {
return ratePerExcessMinute;
}
public String getPlanName() {
return planName;
}
}
This also avoids duplicated blocks but might not suit your needs.

Trying to get default value from the data definition class

Please consider two classes :
Data Definition Class :
public class A {
private int amount = 1000;
public A(int amount){
this.amount = amount
}
public int getAmount(){
return amount ;
}
}
Main Class :
public class B {
public static void main (String arg[]){
A a = new A(2000);
System.out.println("Amount:"+a.getAmount());
}
}
Since I am passing 2000 to the constructor, I am getting 2000 in the output. But I would like to keep a option of if the user doesn't specifiy any amount, it should print
the default value which is 1000 as mentioned in the private variable in data definition class.
Is there a way I can accomplish my task using the constructor?
public class A {
private int amount;
public A() {
amount = 1000;
}
public A(int amount) {
this.amount = amount;
}
public int getAmount() {
return amount;
}
}
You just need to create an empty constructor
public A(){
}
And in your main you will be able to do this:
A a = new A();
You can provide default constructor along with the one argument constructor you mentioned. This way user don't have to pass the amount if he don't want to while creating the object.
Create an empty constructor
public class A {
private int amount = 1000;
public A(){
}
public A(int amount){
this.amount = amount;
}
public int getAmount(){
return this.amount;
}
}

Extending abstract classes

MyMath's constructor is supposed to call Homework's constructor, but super(); returns an error 'cannot find symbol'. It should not have any arguments.
Also, I am confused about how to call the method createAssignment using an arraylist, but I have to use it. Any advice?
Homework
public abstract class Homework {
private int pagesToRead;
private String typeHomework;
public Homework(int pages, String hw) {
// initialise instance variables
pagesToRead = 0;
typeHomework = "none";
}
public abstract void createAssignment(int p);
public int getPages() {
return pagesToRead;
}
public void setPagesToRead(int p) {
pagesToRead = p;
}
public String getTypeHomework() {
return typeHomework;
}
public void setTypeHomework(String hw) {
typeHomework = hw;
}
}
MyMath
public class MyMath extends Homework {
private int pagesRead;
private String typeHomework;
public MyMath() {
super();
}
public void createAssignment(int p) {
setTypeHomework("Math");
setPagesToRead(p);
}
public String toString() {
return typeHomework + " - " + pagesRead;
}
}
public class testHomework {
public static void main(String[] args) {
ArrayList<Homework> list = new ArrayList<Homework>();
list.add(new MyMath(1));
list.add(new MyJava(1));
for (Homework s : list) {
s.createAssignment();
}
}
}
Compiler error:
Regarding the compiler error, you have to change the MyMath constractor to somthing like:
public MyMath() {
super(someInt, someString);
}
Or, you can add a non-arg constructor to the Homework class:
public Homework() {
this(someInt,someString);
}
You can learn about the super() keyword in the Javadocs tutoriel:
If a constructor does not explicitly invoke a superclass constructor,
the Java compiler automatically inserts a call to the no-argument
constructor of the superclass. If the super class does not have a
no-argument constructor, you will get a compile-time error. Object
does have such a constructor, so if Object is the only superclass,
there is no problem.
Code Suggestion:
As there is many other issues in your question, i modified all your classes like below:
Homework.java:
public abstract class Homework {
private int pagesToRead;
private String typeHomework;
{
// initialise instance variables
pagesToRead = 0;
typeHomework = "none";
}
public Homework(int pages, String hw) {
this.pagesToRead = pages;
this.typeHomework = hw;
}
public abstract void createAssignment(int p);
public int getPages() {
return pagesToRead;
}
public void setPagesToRead(int p) {
pagesToRead = p;
}
public String getTypeHomework() {
return typeHomework;
}
public void setTypeHomework(String hw) {
typeHomework = hw;
}
}
MyMath.java
public class MyMath extends Homework {
private int pagesRead;
private String typeHomework;
public MyMath(int pages, String hw) {
super(pages,hw);
}
public void createAssignment(int p) {
setTypeHomework("Math");
setPagesToRead(p);
}
public String toString() {
return typeHomework + " - " + pagesRead;
}
}
TestHomework.java:
class TestHomework {
public static void main(String[] args) {
ArrayList<Homework> list = new ArrayList<Homework>();
// will create a homework with type Math and one page to read
list.add(new MyMath(1,"Math"));
// Assuming MyJava is similar to MyMath
list.add(new MyJava(1,"Java"));
for (Homework s : list) {
if (s instanceof MyMath) {
// modify the number of pages to read for the Math homework
s.createAssignment(3);
} else if (s instanceof MyJava) {
// modify the number of pages to read for the Java homework
s.createAssignment(5);
} else {
s.createAssignment(7);
}
}
}
}

Conflict between passing an Array from Main Class to Function, but also wanting to use return vales from my "getter" method

In my main class, I have a static method which I pass the array into. It is a static method because if I want to pass something from the main class body to this method, it must be static. In a separate class I have a series of getters and setters (which must be non static ).
How can I pass my static array in and use the non-static getters and setters?
EDIT- In the arraySearch method...I cannot pass in the Person Array and access the getters in the Person Class
public class Main {
public static void main(String[] args) {
Person One = new Person("Alice","Foo", 22, false);
Person Two = new Person("Alice", "Foo",22, false);
Person Three = new Person("Bob","Bar",99, false);
Person Four = new Person("Joe","Blogs",64, false);
Person Five = new Person("Jane", "Joe",42, false);
Person [] People = {One,Two,Three,Four,Five};
printArray(People);
}
public static void printArray(Person [] People)
{
for(int i=0;i<People.length;i++)
{
System.out.println(People[i]);
}
}
public void arraySearch(Person [] People)
{
for(int i=0;i<People.length;i++) //Searches the Array of Objects
{
String firstName = Person.getFirstName();
String secondName=Person.getSecondName();
if((firstName.equals("Joe")&&secondName.equals("B" + //Searches for Joe Blogs and Jane Joe
"logs"))|| ((firstName.equals("Ja" +
"ne")&&secondName.equals("Joe"))))
{
int age=Person.getAge();
Person.setAge(age+1); //Increments Age by 1
}
}
}
}
public class Person {
private String mfirstName;
private String msecondName;
private int mage;
private boolean misRetired;
public Person(String firstName,String secondName,int age, boolean isRetired)
{
mfirstName=firstName;
msecondName=secondName;
mage=age;
misRetired=isRetired;
}
//GETTERS
public String getFirstName()
{
return mfirstName;
}
public String getSecondName()
{
return msecondName;
}
public int getAge()
{
return mage;
}
public boolean getRetired()
{
return misRetired;
}
//SETTERS
public void setFirstName(String firstName)
{
mfirstName=firstName;
}
public void setSecondName(String secondName)
{
msecondName=secondName;
}
public void setAge(int age)
{
mage=age;
}
public void setRetired(boolean isRetired)
{
misRetired=isRetired;
}
//STRING
public String toString()
{
return (mfirstName+"-"+msecondName+"-"+mage+"-"+misRetired);
}
}
This is very basic Java question. You need to create instance of object containing setter/getters from your static method. You can also pass static array in setter of this object. Then you should be able to call those getter/setter methods.
public class Main
{
public static void main(String[] args)
{
MyClass myclass = new MyClass();
myclass.setArgs(args);
System.out.println(myclass.getArgs());
}
}
public class MyClass
{
private String[] args;
public String[] getArgs()
{
return args;
}
public void setArgs(String[] args)
{
this.args= args;
}
}
You have to create an object instance from the class with the getters.
The Amit answer is correct; this just has some more info and more closely matches the situation you describe in your question.
Your basic premise "It is a static method because if I want to pass something from the main class body to this method, it must be static." is wrong. The method to which you pass the array does not need to be static. Here is some code:
public final class Main
{
private static final String[] staticOTron =
{
"one",
"two",
"three"
};
public static void main(final String[] args)
{
String[] hootBerrySause;
Tool tool = new Tool();
tool.setStaticOTron(staticOTron);
hootBerrySause = tool.getStaticOTron();
for (String value : hootBerrySause)
{
System.out.println("Value: " + value);
}
}
}
// this can be in a different file.
public final class Tool
{
private static String[] staticOTron;
public void setStaticOTron(final String[] newValue)
{
staticOTron = newValue;
}
public String[] getStaticOTron()
{
return staticOTron;
}
}
Sunil kumar from vmoksha
Your asking deeper navigation
Just create the instance of particular or create the getter &and setter in the main
class

Categories

Resources