I'm trying to call some integers into a class from a method within another class
public class Variables
{
public void vary()
{
int DSpr
}
}
public class BattleCalc
{
public static void main(String[] args)
{
Variables v = new Variables();
v.vary();
Scanner spr = new Scanner(System.in);
DSpr = Integer.parseInt(spr.nextLine()); //This line here
}
}
This is my code so far, but on DSpr = Integer.parseInt... eclipse gives me an error "DSpr cannot be resolved". Why is it not calling DSpr from Variables ?
" call some integers into a class from a method within another class" makes no sense to me. Variables in a method are local to that method ONLY
I think what you want to do is something like this
public class Variables
{
...
public int DSpr;
}
...
v.DSpr = Integer.parseInt(spr.nextLine());
i.e Make DSpr a public member variable of the Variables class.
It is recommended that you instead make it a private variable and write setter-getter methods for users outside the class to use it.
Try this: in order to access a variable at another class, it must be declared as class variable.
At your Class Variables:
public class Variables{
int DSpr;
public void vary(){
//do assignment here or operation, if you want to create a method
DSpr = 0;
}
}
Then call it on your main class.
int DSpr is declared locally within vary() method and hence can't be accessed outside of that method. even in it's enclosing class Variables
To access a variable in another class, it should be defined as instance field. (or class variable / static variable)
public class Variables
{
public int DSpr;
// OR
// public static int DSpr;
public void vary()
{
}
}
Now, in BattleCalc class you can access as following:
Variables v = new Variables();
v.DSpr = Integer.parseInt(spr.nextLine());
// OR
// Variables.DSpr = Integer.parseInt(spr.nextLine());
here your DSpr variable scope is limited to this method only:
public void vary()
{
int DSpr
}
so it can not be accessed anywhere else.
if you are using elsewhere you need to re-declare like:
int DSpr = Integer.parseInt(spr.nextLine());
You want to assign a value to DSpr from altogether another class. You should declare DSpr as member variable in Variable class and assign it by calling setter in that class.
Your code will be like this.
public class Variables
{
private int DSpr;
public void setDSPR(int DSpr)
{
this.DSpr=DSpr;
}
}
public class BattleCalc
{
public static void main(String[] args)
{
Variables v = new Variables();
Scanner spr = new Scanner(System.in);
try {
v.setDSPT(Integer.parseInt(spr.nextLine())); //This line here
} catch(NumberFormatException ex) {
System.out.print("Invalid Input.!")
}
}
}
Try this..
import java.io.*;
import java.util.*;
class Variables
{
public void vary()
{
int DSpr;
}
}
public class BattleCalc
{
public static void main(String[] args)
{
Variables v = new Variables();
v.vary();
Scanner spr = new Scanner(System.in);
int DSpr = Integer.parseInt(spr.nextLine()); //This line here
}
}
Yes You should get errors in above code, Here is my solution
I assume you want to change the variable value in vary(). But I am not sure the usage of this since you are not using the changed value in BattleCalc.
So get and set the integer variable you can use getters and sertters but here I will do minimum modifications to your code to make it easy to understand (so I am not using getters and setters here although it is the ideal way of doing)
public class Variables {
public int DSpr;
public void vary() {
// Change the value of DSpr
DSpr = 10;
}
}
public class BattleCalc {
public static void main(String[] args) {
Variables v = new Variables();
v.vary();
Scanner spr = new Scanner(System.in);
v.DSpr = Integer.parseInt(spr.nextLine()); //This line here
}
}
Related
I want to access an object i created in a new class but it returns that the object " cannot be resolved".
thanks for anyone who helps:)
here is my code :
public class lion {
int weight;
int height;
String color;
double roardecibles;
public void lioncolor() {
System.out.println(color);
}
}
public class blacklion {
lion blackLion;{
blackLion = new lion();
blackLion.weight =4;
blackLion.height =3;
blackLion.color = "black";
blackLion.roardecibles = 5.5;
}
}
public class zoo {
public static void main(String[] args) {
blackLion.lioncolor(); //here it dosent work//
}
}
There's a difference between an object and a class. Think of a class as a blueprint, that's what you did when you defined it in public class blacklion. But you didn't actually build something with the blueprint. To create an object you have to instantiate it, using the new keyword.
public static void main(String[] args) {
blacklion lion = new blacklion();
lion.lioncolor(); //here it dosent work//
}
Usually, you want to instantiate an Object of your class that you can then access from where u created it. If you want to access methods or variables of a class directly you want to declare those as public and static.
Hey looks like you should check out this resource:
https://docs.oracle.com/javase/tutorial/
Specifically the section of how classes work:
https://docs.oracle.com/javase/tutorial/java/concepts/class.html
this code
public static void main(String[] args)
{
blackLion.lioncolor(); //here it dosent work//
}
needs an instance of the object in order to call the lioncolor() method
I have just begun learning Java and I am trying to test stuff by myself. Below is the code where I am getting an error. I am trying to call the local variable in class B in class Demo using object of class B.
public class Demo {
public static void main(String args[])
{
B obj=new B();
System.out.println("printing that variable "+obj.a);
}
}
class B{
public void test()
{
int a=10;
}
}
Output:
Exception in thread "main" java.lang.Error: Unresolved compilation
problem: a cannot be resolved or is not a field at
Demo.main(Demo.java:7)
You can always call, but that needs to be in scope and when the current context have access to.
System.out.println("printing that variable "+obj.a);
You cannot do that since the variable a is local to the method test() and scope is restricted to that method only.
To access the way you want now, make it as a instance member.
class B{
int a; // instance member now
public void test()
{
a=10;
}
}
Now note that unless you call the method test() the default value is 0 only. Hence you might want to change your code as
public static void main(String args[])
{
B obj=new B();
obj.test();
System.out.println("printing that variable "+obj.a);
}
and if you don't want to call a method at all want to access a directly, you can do
public class Demo {
public static void main(String args[])
{
B obj=new B();
System.out.println("printing that variable "+obj.a);
}
}
class B{
public int a= 10;
}
Imp note :Always resolve all the compile errors before running your program :)
Because in
class B {
public void test() {
int a = 10;
}
}
a is local variable of test method. If what you are trying to do would be possible, what value should be used in scenario like
class B {
public void test1() {
int a = 10;
}
public void test2() {
int a = 20;
}
}
Should a come from test1 or from test2? For compiler this two methods are equally correct so it can't decide for you, which would cause the problem. Also lets not forget that method can have few variables with same name as long as they are in different scope, that is why we can have few for(int i...) methods (so from which scope you would want to use i).
Generally . operator is used to get access to member of class, not variable from method. So via object.member you may access to object.method() or object.field. If your class would look like
class B{
public int x;
public void test1() {
int a = 10;
}
}
you could use object.b since b is class B field.
Anyway if you want to get access to value of variable created and used only in method test, you could change this method to return this value. In other words you could rewrite it like
public int test1() {
int a = 10;
//... you can do something with a
return a;
}
Now in main method in Demo class you could use int result = obj.test();
Base Class;
import java.util.Random;
public class Animal
{
public void move()
{
int value = 0;
System.out.println("Move");
Random rand = new Random();
value = rand.nextInt(2)+1;
}
}
Inherited Class;
public class Cat extends Animal
{
public void moveCat()
{
super.move();
System.out.println("Move Cat");
}
public static void main(String[] args)
{
Cat test = new Cat();
test.moveCat();
}
}
I Am trying to use a value of the base class animals method move in the override method moveCat. Why cant I use the value "value" in moveCat from Cat.
For Example;
public void moveDoodle()
{
super.move();
System.out.println("Move Doodle");
if(value == 1)
{
System.out.println("Value from base");
}
}
If I am grabbing the content from the base method why can't I also use the values. If its not possible what should I be doing instead in order to get the values I need.
That's because value is in the local scope of the method move() of your base(Animal) class and that is why its not inherited. Only the instance variables will be inherited(provided they are not private). Thus, you need to make value an instance variable for you to be able to inherit it in your base(Animal) class.
int value = 0;
public void move()
{
// int value = 0;
System.out.println("Move");
Random rand = new Random();
value = rand.nextInt(2)+1;
}
Note: I can see that you've inherited the Animal class but have not overriden any method, contrary to what was suggested in the question title.
because value is a local variable to method move(). Local variables are not inherited. Create the variable as instance variable.
By the way, if you are trying to override to move() method, you need to keep the same method signature.
import java.util.Random;
public class Animal {
int value = 0;
public void move() {
System.out.println("Move");
Random rand = new Random();
value = rand.nextInt(2) + 1;
}
}
Your Cat class
public class Cat extends Animal {
public void moveCat() {
super.move();
System.out.println("Move Cat");
}
public static void main(String[] args) {
Cat test = new Cat();
test.moveCat();
System.out.println(test.value);
}
}
With your implementation, the value variable is of local scope. It is accessible only within the move method and the outer world doesn't know about this.
You will need to declare this variable at the instance scope in order to make it accessible at the class level. You will also need to declare the access modifier for this so that the inheriting class know about it.
The following will work.
protected int value = 0;
public void move()
{
System.out.println("Move");
Random rand = new Random();
value = rand.nextInt(2)+1;
}
It is said that non-static variables cannot be used in a static method. But public static void main does. How is that?
No, it doesn't.
public class A {
int a = 2;
public static void main(String[] args) {
System.out.println(a); // won't compile!!
}
}
but
public class A {
static int a = 2;
public static void main(String[] args) {
System.out.println(a); // this works!
}
}
or if you instantiate A
public class A {
int a = 2;
public static void main(String[] args) {
A myA = new A();
System.out.println(myA.a); // this works too!
}
}
Also
public class A {
public static void main(String[] args) {
int a = 2;
System.out.println(a); // this works too!
}
}
will work, since a is a local variable here, and not an instance variable. A method local variable is always reachable during the execution of the method, regardless of if the method is static or not.
Yes, the main method may access non-static variables, but only indirectly through actual instances.
Example:
public class Main {
public static void main(String[] args) {
Example ex = new Example();
ex.variable = 5;
}
}
class Example {
public int variable;
}
What people mean when they say "non-static variables cannot be used in a static method" is that non-static members of the same class can't be directly accessed (as shown in Keppils answer for instance).
Related question:
Accessing non-static members through the main method in Java
Update:
When talking about non-static variables one implicitly means member variables. (Since local variables can't possible have a static modifier anyway.)
In the code
public class A {
public static void main(String[] args) {
int a = 2;
System.out.println(a); // this works!
}
}
you're declaring a local variable (which typically is not referred to as non-static even though it doesn't have a static modifier).
The main method does not have access to non-static members either.
final public class Demo
{
private String instanceVariable;
private static String staticVariable;
public String instanceMethod()
{
return "instance";
}
public static String staticMethod()
{
return "static";
}
public static void main(String[] args)
{
System.out.println(staticVariable); // ok
System.out.println(Demo.staticMethod()); // ok
System.out.println(new Demo().instanceMethod()); // ok
System.out.println(new Demo().instanceVariable); // ok
System.out.println(Demo.instanceMethod()); // wrong
System.out.println(instanceVariable); // wrong
}
}
This is because by default when you call a method or variable it is really accessing the this.method() or this.variable. But in the main() method or any other static method(), no "this" objects has yet been created.
In this sense, the static method is not a part of the object instance of the class that contains it. This is the idea behind utility classes.
To call any non-static method or variable in a static context, you need to first construct the object with a constructor or a factory like your would anywhere outside of the class.
More depth:
Basically it's a flaw in the design of Java IMO which allows static members (methods and fields) to be referenced as if they were instance members. This can be very confusing in code like this:
Thread newThread = new Thread(runnable);
newThread.start();
newThread.sleep(1000);
That looks like it's sending the new thread to sleep, but it actually compiles down into code like this:
Thread newThread = new Thread(runnable);
newThread.start();
Thread.sleep(1000);
because sleep is a static method which only ever makes the current thread sleep.
Indeed, the variable isn't even checked for non-nullity (any more; it used to be, I believe):
Thread t = null;
t.sleep(1000);
Some IDEs can be configured to issue a warning or error for code like this - you shouldn't do it, as it hurts readability. (This is one of the flaws which was corrected by C#...)
**Here you can see table that clear the access of static and non-static data members in static and non-static methods. **
You can create non-static references in static methods like :
static void method() {
A a = new A();
}
Same thing we do in case of public static void main(String[] args) method
public class XYZ
{
int i=0;
public static void increament()
{
i++;
}
}
public class M
{
public static void main(String[] args)
{
XYZ o1=new XYZ();
XYZ o2=new XYZ();
o1.increament();
XYZ.increament(); //system wont be able to know i belongs to which object
//as its increament method(static method)can be called using class name system
//will be confused changes belongs to which object.
}
}
If I make for example one project. Inside with two class. For example: X and Y. I make them what I want, and I want to make a main method in Y. Only system.out.printlf the values in X and Y. But it writes that I need to make them static if I want to run this. I tried to make a new file with only the main class and inside the X Y values but it showed an error. What I missed?
you have missed object creation. Try X x = new X(); in your Y file. I would recommend to read some tutorials on Java, starting from here.
The main method is declared static
public static void main(String[] args) {}
Inside of main, it can only access static variables that exist in the enclosing class. You will see this for example with this bit of code:
public class X {
private int i = 5;
public static void main(String[] args) {
System.out.println(i);
}
}
To make the above work you need to declare i as static:
public class X {
private static int i = 5;
public static void main(String[] args) {
System.out.println(i);
}
}
A better way would be to do this:
public class X {
private int i = 5;
public X() {
System.out.println(i);
}
public static void main(String[] args) {
new X();
}
}
Static methods can only access static methods and other variables declared as static.
This article may also help you to understand what is going on here.
I'm guessing that's because everything happens inside the main method which is indeed static right? e.g.
public class C {
int X;
int Y; //or whatever other type
..
public static void main(String args[]) {
System.out.print( X ); //this won't work!
}
}
instead use this aprroach:
public class C {
int X;
int Y; //or whatever other type
..
public static void main(String args[]) {
C inst = new C();
System.out.print( c.X ); //this will work!
}
}
The main method is static and can only access static fields from the class. non static fields belong to an instance/object which you'd have to create:
public class X {
static int a = 0;
int b = 0;
public static void main(String[] args) {
System.out.println(a); // OK -> accesses static field
System.out.println(b); // compile error -> accesses instance field
X x = new X();
System.out.println(x.b); // OK -> accesses b on instance of X
}
}