Method and Variable Scope Issue in Java - java

I need help I cannot figure out how to fix the scope of my variables. I want this to be an example for my notes but have been on it for almost 2 hours.
public class methodPractice{
String streetName;
int streetNum;
public static void streetName()
{
String streetName = "Pope Ave.";
}
public static void streetNum()
{
int streetNum = 11825;
}
public static void main(String[] args)
{
streetName();
streetNum();
System.out.println("This is your home adress: " + streetNum +
streetName);
}
}
Thank you for your help.

You are shadowing the fields. Use this to make sure you get the fields, or a compile error.
public static void streetName()
{
this.streetName = "Pope Ave.";
}
public static void streetNum()
{
this.streetNum = 11825;
}

Here is your main method, with line numbers added:
1. public static void main(String[] args) {
2. streetName();
3. streetNum();
4. System.out.println("This is your home adress: " + streetNum + streetName);
5. }
A few points...
When line 2 runs, "streetName()" calls the static method below. The static keyword says you are free to call the method by itself – that is, you don't need an object; you don't need to call new methodPractice() first.
public static void streetName() {
String streetName = "Pope Ave.";
}
When line 3 runs, it's the same thing: "streetNum()" calls a different static method – again, totally fine to call this by itself.
public static void streetNum() {
int streetNum = 11825;
}
Line 4 is different, there are a few things going on. Your expectation is that "streetNum" finds the int that you declared on the class, but it doesn't work. Why? Because you defined that member with "int streetNum" – without "static". So what? Without being declared static, it means "streetNum" belongs to an object instance. What does that look like? Here's an example showing object creation, followed by setting the object member "streetNum" to 1.
methodPractice object = new methodPractice();
object.streetNum = 1;
You could work around this by declaring both of the non-static members to be static (static String streetName, and static int streetNum). Or you could leave them as is, and interact with them through an object instance (after doing new ..).

Related

How to print a variable from another .java file?

how can I call a variable from another java file? Every time I try to System.out.Println I receive a null. But it works in the original code. I want to print the name variavle in the MartianApp Class/file.
Here is the original code:
import java.util.Random;
public class Martian
{
static String name;
static int count;
static Random rand = new Random();
public static void main(String[] args) {
Martian getRandomName = new Martian(); {
count = count++;
char c = (char)(rand.nextInt(26) + 'a');
int min = 10;
int max = 99;
int num = rand.nextInt(max - min) + min;
name = c + String.valueOf(num) + " /" + count;
};
System.out.println (name);
}
};
Here is the second code:
public class MartianApp
{
public static void main (String[] args)
{
System.out.println(Martian.name);
}
};
You first have to assign a value to name. Run the main method of the Martian class first.
Martian.main(null);
System.out.println(Martian.name); // unnecessary as there is a println in Martian.main()
The problem you are getting null as the value for name variable is you are executing only the main method of MartianApp class.Because of that Martian class main method won't be run so the updation of value for name variable after running the main method of Martian class won't be happen.That's why you are getting the output as null.
Solution:
public class MartianApp
{
public static void main (String[] args)
{
Martian.main(null);//Now the main method of Martian class will be executed and name variable will be updated
System.out.println(Martian.name);
}
};
Please replace static String name; in class Martian with static String name="John";
Then first run class Martian
Later on run class MartianApp.
It will show the output as John
The problem is that you're trying to access a variable which is not public. The variables have certain access scopes that define from where you can access them. In your case
static String name;
is a default access scope, meaning you can't use it outside of its package. You can fix this by changing it to a public variable like this
public static String name;
This however is NOT the way to go in Java. It would work, but it's a very bad practice. If you want to access the variables of a class, by default, you should create a getter method for them.
public class Martian {
private String name;
public String getName(){
return this.name;
}
}
Then you can instantiate your Martian.class and call the getter for it
Martian martian = new Martian();
System.out.println(martian.getName());
Read up on how getters and setters work. You shouldn't make everything static if there isn't a very good reason to do so.

assign a value to a println statement so it can be used anywhere in the file

I need to assign a value to a println statement so that i can declare it as a variable and then use it anywhere in the code. i want to be able to assign a value to the "result" in the println, however i do not know how to do this. Does anyone know how to assign a value to this so that it can be used anywhere?
I have tried the following, however i get an error saying that void cannot be converted to string...
You can define a method:
private void print(String value) {
System.out.println(value);
}
This can be called from anywhere in your class.
If you would like to re-use this functionality in different classes you could create a separate class for it:
public class Printer {
public void print(String value) {
System.out.println(value);
}
}
You can then add it as a dependency in the class that wants to print:
public class MyApp {
private Printer printer;
public MyApp(Printer printer) {
this.printer = printer;
}
public void doSomething() {
printer.print("Hello world");
}
}
You can probably write it as a JAVA lambda expression, such as:
Consumer<String> print = it-> System.out.println(it);
Whenever you want to run, you can run it like this:
print.accept("hello");
Br,
Tim
Make a Consumer and pass a object whenever you want to print taht object.
Consumer consumer= System.out::println;
consumer.accept(5);
Updated
In your case define consumer as :
public static int myHouseValue;
public static final Consumer CONSUMER= System.out::println;
and any where and in any class you can use this consumer. just include this static member. and pass the object you want to print.
CONSUMER.accept(5);
CONSUMER.accept("String");
CONSUMER.accept(new Object());
CONSUMER.accept(myHouseValue);
Your Code (Updated):
public class Weka {
public static int Lotsize;
public static int Bedrooms;
public static int LocalSchools;
public static int Age;
public static int Garages;
public static int Bathrooms;
public static double myHouseValue = 0d;// here is the default value zero
public static final Consumer CONSUMER = System.out::println;
public static void main(String[] args) throws Exception {
System.out.println("Server up and running");
. . .
your code
. . .
// donot declare myHouseValue again , its already defined wher we set it to default value. only use here
myHouseValue = (coef[0] * Lotsize) +
(coef[1] * Bedrooms) +
(coef[2] * LocalSchools) +
(coef[3] * Age) +
(coef[4] * Garages) +
(coef[5] * Bathrooms) +
coef[7];
CONSUMER.accept(myHouseValue);

passing static variable value to another function

I have a static variable totalcontainer and I am assigning value to it in main method.
Now when I call it in another method it gives default value i.e. 0
The value of variable is not updating in second method.
import java.util.ArrayList;
public class abc {
static int totalContainer;
static ArrayList<Integer> count = new ArrayList<Integer>();
public static void main(String args[]) {
count.add(2);
count.add(10);
count.add(15);
count.add(6);
count.add(8);
totalContainer = count.size();
System.out.println(totalContainer);
}
public static float getCpu() {
int getcontainer = totalContainer;
System.out.println("in get cpu " + getcontainer);
return getcontainer;
}
}
I am calling method getCpu from another class and always getting value 0.
How can I use this variable value in another class?
This is a simple program to demonstrate the problem which i am facing.
If the getCpu() method is called from some other class, main method of class abc is not called.
If you need the count variable updated as in main method, define the implementation in a static block as below.
import java.util.ArrayList;
public class abc {
static int totalContainer;
static ArrayList<Integer> count = new ArrayList<Integer>();
static{
count.add(2);
count.add(10);
count.add(15);
count.add(6);
count.add(8);
totalContainer = count.size();
}
public static void main(String args[]) {
System.out.println(totalContainer);
}
public static float getCpu() {
float getcontainer = totalContainer;
System.out.println("in get cpu " + getcontainer);
return getcontainer;
}
}
If this is in a multi-threaded environment, it is possible that you call getCpu() before totalContainer is initialized. It looks like though as if it is a racing condition.
If you guarantee that the getCpu() is called after the completion of main method, then the value would be correct.
to test this, try this code:
System.out.println(totalContainer);
SwingUtilities.invokeLater(() -> getCpu());
What you can do since you are using multi-threading:
First initialize all you want, then start multithreading
or perform locking, to properly initialize

A local variable can't be used inside an inner class. So why does this code work?

I have a student studying for the Java 7 OCP exam, and he presented me with this problem. Both he and I understand that a local variable can't be used within the method's inner class unless it's final, but he presented me with the following code which runs just fine:
public class TestC195 {
public static void main(String[] args) {
TestC195 myObject = new TestC195();
myObject.doStuff();
}
private String x = "Outer 2";
void doStuff() {
String z = "local";
class myInner {
public void seeOuter() {
System.out.println("outer: " + x);
System.out.println("outer: " + z);
}
}
myInner in = new myInner();
in.seeOuter();
}
}
The output is:
outer: Outer 2
outer: local
So what are we both missing?
If you are compiling with java 8 it is because it is effectively final link here

Simple ArrayList question

I have this class:
public class User {
public User(String nickname, String ipAddress) {
nickname = nickname.toLowerCase();
System.out.println(nickname + " " + ipAddress);
}
}
And another class that creates an array containing User objects.
class UserMananger {
static User user;
static User user2;
static User user3;
static ArrayList allTheUsers;
public void UserManager() {
allTheUsers = new ArrayList();
user = new User("Slavisha", "123.34.34.34");
user2 = new User("Zare", "123.34.34.34");
user3 = new User("Smor", "123.34.34.34");
allTheUsers.add(user);
allTheUsers.add(user2);
allTheUsers.add(user3);
}
}
What I want to do is to call a main method that will give me all elements from the list that are type User in format: "nickname ipAddress"
public static void main(String args[]) {
System.out.println(allTheUsers.get(0));
}
For example, this main method should give me something like:
Slavisha 123.34.34.34
but it doesn't. What seems to be the problem?
First problem: you haven't overridden toString() in User. For example:
#Override
public String toString() {
return nickname + " " + ipAddress;
}
Second problem: each time an instance of UserManager is created, you're changing the values of your static variables... but you're not doing anything unless an instance of UserManager is created. One option is to change the constructor of UserManager into a static initializer:
static {
// Initialize the static variables here
}
Third problem: you haven't shown us where your main method is, so we don't know whether it has access to allTheUsers.
Fourth problem: "it doesn't" isn't a good description of your problem. Always say what appears to be happening: are you getting an exception? Is it just printing the wrong thing?

Categories