How to call a function with array parameters in main application? - java

I've been doing some tutorial on inheritance abstract class, and I pass an array to a function for a calculation of total price. But then, when I tried to call the function in the main, it didn't work and I've got some error according the method call.
Here is my calculation code in subclasses :
public double calcPrice(String[] a, int[] qty, int num){
int i =0;
for(i=0;i<=num;i++) {
if (a[i]=="a")
price=24.90;
}
double tot=price+qty[i];
return tot;
}
This is my method call in the for loop. I don't know how to call the method as the error says "non-static method calcPrice() cannot be referenced from a static context"
for(int i=0;i<=num;i++) {
System.out.println("\t"+a[i]+"\t\t\t"+qty[i]+" "+calcPrice());
}

The main method is static, and can't call non-static code. You have 2 solutions.
Create an instance of the class performing the calculation, and call calcPrice on that instance.
make calcPrice static.
I suggest option one as you've been doing research on classes. This would be good practice for you.
Also do not compare variable a to "a" with ==. Use .equals instead. Check this link for why.
Edit:
I'm not sure how an abstract class plays into this as you have no abstract methods needing implementation.
public class CalcClass{
public double calcPrice(String[] a, int[] qty, int num){
int i =0;
for(i=0;i<=num;i++) {
if ("a".equals(a[i]))
price=24.90;
}
double tot=price+qty[i];
return tot;
}
}
public class MainClass{
public static void main(String[] args){
//create instance of calc class
CalcClass c = new CalcClass();
//call calc price method on calcclass
c.calcPrice(a, new int[]{1}, 1};
}
}

Changed to-
public static double calcPrice(String[] a, int[] qty, int num){
...
}
You should create an object before you do a call from main. Say you have a class-
public class Test {
public void someMethod(){
}
public static void main(String... args){
// Create an object first
Test t = new Test();
// Now you can use that non-static method someMethod
t.someMethod();
}
}
For static method, they exist on load.

You will need to create instance in order to call you method since your method is not static.
making you methos static will enable you to use it without creating instance of the class.
you may want to read about Static Methods here

Related

How do you pass an updated global class variable from one method into another?

I update a variable (which is global in the class) in one method and I cannot seem to be able to then pass that updated variable into another method.
Any help would be appreciated, thank you.
Here's my shortened code:
public class Game{
private int randomIndexX;
protected String spawn(){
randomIndexX = randomGenerator.nextInt(10);
return null;
}
protected String test(){
System.out.println(this.randomIndexX);
return null;
}
}
public class Player extends Game{
protected String getNextAction(String command) {
switch(command){
case "test":
test();
break;
}
}
}
public static void main(String[] args) {
Game game = new Game();
Player player = new Player();
game.spawn();
player.getInputFromConsole();
}
EDIT: so when i call test() from the Player class i want it to print out randomIndexX but it still doesn't seem to be working even with this.randomIndexX in the method test()
EDIT: so when i call test() from the Player class i want it to print out randomIndexX but it still doesn't seem to be working even with this.randomIndexX in the method test().
So test() is instance method, which means you'll have to make an instance of Class Game in order to call that method, your randomIndexX is instance member so you need to think well what you want to do, IF randomIndexX is common for all the objects of Game class, you should declare it static as in:
private static in randomIndexX;
As it's value won't change depending on an object instance.
So in order to access that variable from outside of the class since it's private you declare a public method to retrieve that value (getter or also known as accessor):
public static int getRandomIndex(){
return randomIndexX;
}
So when in main, you don't even have to make an instance of the Game class to access value that's being held in randomIndexX, you just call the getter method like this:
System.out.println(Game.getRandomIndex());
The line above will print 0 to the console as 0 is default value for members of type int, now if you want to be able to change it, you just make a setter or mutator method in Game class as well:
public static void setRandomIndex(int n){
randomIndexX = n;
}
And there you go, you can now set and retrieve "randomIndexX" field from outside of the Game class.
For example, the code below will set value of randomIndexX to 5 and then print it in the console:
Game.setRandomIndex(5);
System.out.println(Game.getRandomIndex());
The first problem I can see is that you don't have a constructor.(Optional)
(If you don't make one the compiler makes what is called a "Default" constructor which is a constructor without any parameters. Its usually good practice to explicitly create a class constructor.
The second problem I can see is that you missing the end bracket.
Fix shown below.
public class Game
{
private int randomIndexX;
protected String spawn()
{
randomIndexX = 0;
return null;
}
protected String test()
{
System.out.println(randomIndexX);
return null;
}
}
You can construct it and trigger any methods you wish:
Game game = new Game();
game.spawn();
game.test()

Return a Reference to a Class with Static Methods and Static Fields Without Instantiation

I want to create a wrapper class that calls static methods and member fields from a class that is provided by a library I am unable to view the code.
This is to avoid boilerplate setting code of the global member fields when I need to use a static method in a specific context.
I want to try to avoid creating wrapper methods for each static method.
My question:
Is it possible to return a class with static methods from a method to access just the static methods without instantiating it?
Code is below with comments in-line.
The code is used to demonstrate a change in a static value when the method getMath() is invoked.
I want to avoid the setting of the value before calling the static method.
StaticMath.setFirstNumber(1);
StaticMath.calc(1);
StaticMath.setFirstNumber(2);
StaticMath.calc(1);
I am using the Eclipse IDE and it comes up with Warnings, which I understand, but want to avoid.
I tried searching for something on this subject, so if anyone can provide a link I can close this.
public class Demo {
// Static Methods in a class library I don't have access to.
static class StaticMath {
private static int firstNum;
private StaticMath() {
}
public static int calc(int secondNum) {
return firstNum + secondNum;
}
public static void setFirstNumber(int firstNum) {
StaticMath.firstNum = firstNum;
}
}
// Concrete Class
static class MathBook {
private int firstNum;
public MathBook(int firstNum) {
this.firstNum = firstNum;
}
// Non-static method that gets the class with the static methods.
public StaticMath getMath() {
StaticMath.setFirstNumber(firstNum);
// I don't want to instantiate the class.
return new StaticMath();
}
}
public static void main(String... args) {
MathBook m1 = new MathBook(1);
MathBook m2 = new MathBook(2);
// I want to avoid the "static-access" warning.
// Answer is 2
System.out.println(String.valueOf(m1.getMath().calc(1)));
// Answer is 3
System.out.println(String.valueOf(m2.getMath().calc(1)));
}
}
I'd just wrap it to make for an atomic operation:
public static class MyMath{
public static synchronized int myCalc( int num1 , int num2 ){
StaticMath.setFirstNum(num1);
return StaticMath.calc(num2);
}
}
Drawback: You'll have to make sure, StaticMath is not used avoiding this "bridging" class.
Usage:
int result1 = MyMath.myCalc( 1, 1 );
int result1 = MyMath.myCalc( 2, 1 );
You shouldnt call a static method through an object reference. You should directly use class reference to call a static method like this:
StaticMath.calc(1)
But if you still need it for some reason, you can return null in getMath method, but you will still get warning in Eclipse:
public StaticMath getMath() {
StaticMath.setFirstNumber(firstNum);
return null;
}
I infer that question is not properly asked if the answer is not
StaticMath.calc(1)
Other issue you may be facing due to package visibility to static inner classes. Which is a design choice by the writer of Demo class. If you can mark your classes MathBook and StaticMath public then you can access them like below:
Demo.StaticMath.calc(1);

Java calling methods non/static and private/public

I just had some method calling scenarios I was unsure of, and was hoping someone could help clear some up for me.
a) If I was in the SalesMethod class and I wanted to call the sales method from the region method how would I do that? (private method calling public method)
b) What about sales calling purchase? (public calling public from within same class)
c)If I was in SalesMethod, what would be a way to call the futureSales method? Would I have to create an instance for it since it's non static?
Thanks in advance.
public class SalesMethod
{
public static double sales ()
{
code
}
private static void region ()
{
code
}
public static double purchase ()
{
code
}
public void futureSales ()
{
code
}
}
a) private method calling public method is ok since public mean "visible from everywhere".
public static double region()
{
sales();
}
b) public method calling public method is ok for the same reason.
b') public method calling private method is ok if the private method is in the same class than the public one.
c) to call a non-static method, you have to create an instance since you call it "on" an object. You can't call it from a static method the way you do in the example above.
static means "relative to a class"
non-static is relative to an object, you can see that as an action performed by the object.
If I was in the SalesMethod class and I wanted to call the sales method from the region method how would I do that? (private method calling public method)
They are both static, so you can call them everytime you need to.
sales();
// Or
SalesMethod.sales();
What about sales calling purchase? (public calling public from within same class)
They are both static, so you can call them everytime you need to.
purchase();
// Or
SalesMethod.purchase();
If I was in SalesMethod, what would be a way to call the futureSales method? Would I have to create an instance for it since it's non static?
Yes.
SalesMethod instance = new SalesMethod();
instance.futureSales();

How to call method from same class?

i am using this code to call the method which is present in same class. when i am trying to call the method, i am getting this error..
How to resolve this error
please help me
error:
: cannot find symbol
symbol : method getRowCount()
code:
int modelvalue =(int) getRowCount();
System.out.println("This is model"+modelvalue);
method:
public int getRowCount()
{
return dataz.size();
}
You're probably calling the method from a static method (main?).
When you have non-static method, you have to access it through an object.
You should do:
MyClass myObj = new MyClass(); //Actually it's your class
int modelvalue = myObj.getRowCount();
Another note, it's redundant to cast the result to int. It's already an int.
If you are calling getRowCount() in static method then you will get this error.You need to create object of the class containg method and call the method on that object.
eg :
public class Abc
{
public int getRowCount()
{
return dataz.size();
}
public static void main(String args[])
{
Abc ob=new Abc();
int modelvalue =ob.getRowCount();
System.out.println("This is model"+modelvalue);
}
}
This is Because you called the method with a missing definition where it is defined ,since you have not shown your class structure on how you define your method and how your going to access it ...but this is similar issue caused when you have'n instantiated the class it belongs like
MyTestClass test = new MyTestClass();
int result = test.getRowCount();
System.out.println("Result is Integer {0},is:",result);

Non-static method cannot be referenced from static content

I cannot compile the following code:
public class Test {
public static void main (String [] args ){
int a = calcArea(7, 12);
System.out.println(a);
}
int calcArea(int height, int width) {
return height * width;
}
}
The following error appears:
Non-static method calcArea(int, int) cannot be referenced from static content
What does it mean? How can I resolve that issue..?
EDIT:
Based from your advice, I made an instance which is new test() as follows:
public class Test {
int num;
public static void main (String [] args ){
Test a = new Test();
a.num = a.calcArea(7, 12);
System.out.println(a.num);
}
int calcArea(int height, int width) {
return height * width;
}
}
Is this correct? What is the difference if I do this...
public class Test {
public static void main (String [] args ){
int a = calcArea(7, 12);
System.out.println(a);
}
static int calcArea(int height, int width) {
return height * width;
}
}
Your main is a static, so you can call it without an instance of class test (new test()). But it calls calcArea which is NOT a static: it needs an instance of the class
You could rewrite it like this I guess:
public class Test {
public static void main (String [] args ){
int a = calcArea(7, 12);
System.out.println(a);
}
static int calcArea(int height, int width) {
return height * width;
}
}
As comments suggests, and other answers also show, you might not want to go this route for evertyhing: you will get only static functions. Figure out what the static actually should be in your code, and maybe make yourself an object and call the function from there :D
What Nanne suggested is definitely a fix for your problem. However, I think it would be prudent if you got in to the habit right now, while you are early in your progression of learning java, of trying to use static methods as little as possible, except where applicable (utility methods, for instance). Here is your code modified to create an instance of Test and call the calcArea method on your Test object:
public class Test {
public static void main (String [] args ){
Test test = new Test();
int a = test.calcArea(7, 12);
System.out.println(a);
}
int calcArea(int height, int width) {
return height * width;
}
}
As you get further in to coding with java and, presumably given the code you've just written start dealing with objects such as polygon objects of some sort, a method like calcArea belongs at the instance context and not the static context so it can operate on the internal state of your objects. This will make your code more Object Oriented and less procedural.
calcArea mustn't be static. For using another methods in main class, you must create an instance of its.
public class Test {
public static void main (String [] args ){
Test obj = new Test();
int a = obj.calcArea(7, 12);
System.out.println(a);
}
int calcArea(int height, int width) {
return height * width;
}
}
Do you know what a static method is?
If not, look it up, but the short answer is that a static method does not (can not) access "this" because it is not assigned to any particular instance of the class. Therefore you can't call an instance method (one that isn't static) from within a static one, because how will the computer know which instance should the method be run on?
If a method is defined as static that means you can call that method over the class name such as:
int a = Test.calcArea(7, 12);
without creating an object,
here; Test is the name of the class, but to do this calcArea() method must be static or you can call a non-static method over an object; you create an object by instantiating a class such as:
Test a = new Test();
here "a" is an object of type Test and
a.calcArea(7,12);
can be called if the method is not defined as static.
your class calcArea should be declared static and if you want to use that class, you have to first create an instance of the class. In the class the parameters of the class should be returned, as someone suggested.

Categories

Resources