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
Related
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 ..).
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);
How would I develop the driver class for this code ive written ?
Array Class:
import java.util.Scanner;
public class Array
{
Scanner sc = new Scanner(System.in);
private double[] array = new double[];
public void setArray(double[] arr)
{
//I must set a value for the array length. set by user.
//user must input data
}
public boolean isInIncreasingOrder()
{
//must test if input is in increasing order
}
public boolean isInDecreasingOrder()
{
//must test if input is in descending order
}
public double getTotal()
{
//must find the total of all input
//total +=total
}
public double getAverage()
{
//must calculate average
//average = total/array.length
}
}
I guess what I'm asking is what exactly do i call in the DriverClass and how do I do it.
Thanks
The simplest way to test a class is to have a "public static void main(String[] args)" method in the class itself.
In this "main" method, you first create an instance of the class, and then call the various methods in the class, and verify that they do what you expect. To make testing easier, you might want to print out a message after each call to the class under test, showing the expected result, the actual result, and a friendly "OK" or "FAIL" to let you see easily if the method did what you wanted.
Example:
class MyClass {
private int x = 0;
public int getX() { return x;}
public void setX(int x) { this.x = x; }
public static void main(String[] args) {
MyClass instance = new MyClass();
instance.setX(42);
int value = instance.getX();
System.out.print("Expected 42, got "+value);
if (value == 42) {
System.out.println("OK");
}
else {
System.out.println("FAIL");
}
}
}
Once you're familiar with this approach to testing, you might look into unit test frameworks such as JUnit, which provide better ways to "assert" that a particular test is passing, and to understand the results of your testing.
When I play it in NETBEANS IDE 8.0 it keeps saying there is no main class even though I added the main class already?
Need help can't understand.
PS. If I delete the static in magic() it blocks the magic() in main.
package fibotail;
import java.util.Scanner;
public class Fibotail {
public static int fibo(int control, int currentValue, int previousValue) {
if (control < 2) {
return currentValue;
}
return fibo(control - 1, currentValue + previousValue, currentValue);
}
public static void magic() {
String cCharacter;
do {
System.out.println("Input here: ");
int something = new Scanner(System.in).nextInt();
for (int i = 1; fibo(i, 0, 1) <= something; i++) {
System.out.println(fibo(i, 0, 1));
}
do {
System.out.println("Do you want to try again? ");
cCharacter = new Scanner(System.in).next();
} while (!(cCharacter.equals("y") || cCharacter.equals("Y") || cCharacter.equals("N") || cCharacter.equals("n")));
} while (cCharacter.equals('y') || cCharacter.equals('Y'));
}
public static int main(String args[]) {
magic();
return 0;
}
}
Return type should be void, not int:
public static void main(String args[]) { ... }
The JVM looks for the exact signature of the method.
When you run your project you would get:
Error: Main method must return a value of type void in class MainTest, please
define the main method as:
public static void main(String[] args)
In other languages than java, where main returns int (such as C and C++) the return code of main becomes the exit code of the process, which is often used by command interpreters and other external programs to determine whether the process completed successfully.
But java needs void as the return value. (Java internal architecture)
If you reaaly need to return a value just use the following:
System#exit(int)
To enable your program quit with a specific exit code which can be interpreted by the operating system.
Your main() method must have return type void
public static void main(String[] args){
}
Not int or other.
main() method is the entry point of your program and JVM is looking exact main() method.
You have to change your code a little bit. It should be:
public static void main(String args[])
The return type of main method is void
When I run this code i get 2 numbers (which is good) but the numbers generated are the same (which is bad) and I dont want the numbers to be the same. I've done this as an experiment for a rpg I was going to make so I thought it would be beter if each weapon had a different class.
The main class:
package battlesimMK2;
public class Main {
public static void main(String Arg[]) {
String WeponEquiped = "BasicAxe";
System.out.print(BasicAxe.Str);
System.out.print(BasicAxe.Str);
}
}
The basic axe class:
package battlesimMK2;
import java.util.Random;
public class BasicAxe {
static Random rnd = new Random();
static int Str = rnd.nextInt(4)+5;
}
This line:
static int Str = rnd.nextInt(4)+5;
declares a static variable and initializes it once. If you want the code to run each to you access Str, you should make it a method:
public static int getStrength() {
return rnd.nextInt(4)+5;
}
Then call it with this code in Main.main:
System.out.print(BasicAxe.getStrength());
System.out.print(BasicAxe.getStrength());
An alternative which would probably be more object-oriented would be to make the strength an instance field, so that each axe created had a possibly-different (but persistent) strength:
public class BasicAxe {
private static final Random rnd = new Random();
private final int strength;
public BasicAxe() {
strength = rnd.nextInt(4)+5;
}
public int getStrength() {
return strength;
}
}
Then in Main.main:
BasicAxe axe1 = new BasicAxe();
BasicAxe axe2 = new BasicAxe();
System.out.println(axe1.getStrength());
System.out.println(axe2.getStrength());
System.out.println(axe1.getStrength());
Here, the first and third lines of output will be the same - but the second will (probably) be different.
You're generating a single random number and printing it twice. Try something like this instead:
package battlesimMK2;
public class Main {
public static void main(String Arg[]) {
String WeponEquiped = "BasicAxe";
System.out.print(BasicAxe.Str());
System.out.print(BasicAxe.Str());
}
}
package battlesimMK2;
import java.util.Random;
public class BasicAxe {
static Random rnd = new Random();
static int Str() { return rnd.nextInt(4)+5; }
}
This because this line
static int Str = rnd.nextInt(4)+5;
runs just one time in whole the lifecycle of your application. It's static value, you should use static method instead.
Because you define the Str variable as static, only a single copy of that variable is shared between all your BasicAxe classes.
The way to get a different answer each time you ask for the int value is, to use the example posted by the previous poster,
String WeponEquiped = "BasicAxe";
System.out.print(BasicAxe.getStrength());
System.out.print(BasicAxe.getStrength());
But, if you want to create an actual instance of the class BasicAxe, which keeps it's value so that each time you ask for the strength you get the same value, you'll need something different.