public variable in java? - java

I have four classes in my program in which One contains main()
but there is a error in first three lines in fruit, ch and demand variable. I want to use these variables in each class.
import java.util.Scanner;
public static int fruit = 0;
public static int ch;
public static boolean demand = false;
class stock{
synchronized int getfruit(){
while(demand){
try{
wait();
}catch(InterruptedException e){
System.out.println("Wait fruits uploading");
}
System.out.println("cutomer got : " + ch);
demand = true;
notify();
}
return ch;
}
synchronized void putfruits(int ch){
while(!demand){
try{
wait();
}catch(InterruptedException e){
System.out.println("uploaded already");
}
System.out.println("Uploading your demand : "+ ch + " fruits");
demand = false;
notify();
}
}
}
class vendor implements Runnable{
stock obj;
public vendor(stock obj) {
// TODO Auto-generated constructor stub
this.obj = obj;
new Thread(this, "vendor").start();
}
#Override
public void run() {
// TODO Auto-generated method stub
obj.putfruits(ch);
}
}
class customer implements Runnable {
stock obj;
public customer(stock obj) {
// TODO Auto-generated constructor stub
this.obj = obj;
new Thread(this, "cutomer").start();
}
#Override
public void run() {
// TODO Auto-generated method stub
obj.getfruit();
}
}
public class Fruitmarket {
public static void main (String args[]){
stock obj2 = new stock();
System.out.println("Initially market no capacity");
System.out.println("Enter how much quantity you want ?");
Scanner in = new Scanner ( System.in);
ch = in.nextInt();
}
}
How can I do this ? I'm beginner in java ?

This code will not compile. You need to put these variables inside a class like so:
import java.util.Scanner;
class stock {
public static int fruit = 0;
public static int ch;
public static boolean demand = false;
....
If you want to access these variables outside, you can do this by referring to it like this: stock.fruit

If you want to use constants, you can declare an Interface, which you will then use to store constants as public static final <type> <name>
EDIT : You should not implement the interface, instead simply call it : InterfaceName.CONSTANT
It is also good practice to name your constants in all capital letter.
EDIT 2 : It seems that since java 5 (I Guess I'm really outdated...) te use of static imports is considered better practice

Outside the Class definition you can't declare variables. Like the other guys said, you need to declare them inside the class.
If they are public and declared inside class Stock, you can access them from any other class. If they are friendly (no keyword, just static int fruit = 0;) you can access them from any class in the package. How to access them will depend on whether they're static or not. static fields can be accessed by referencing the class itself (e.g. stock.fruit), while for non-static fields you'll need to reference an object that is an instance of the class holding the field.
Now, with that said, I would very much recommend that you declare your variables where they should logically be placed, according to the context of the program. I'm not entirely sure what demand and ch are intended to mean, but just know that you can put them in any class, including Fruitmarket, so long as they have the correct access level modifiers (public, friendly, etc) and you attempt to access them in the right way (through the declaring class if they are static or through an instance of the declaring class if they are non-static)

Related

how to use a list in another class?

I want to create a list, add blocks to it and then use it in a BlockBreakEvent to check if the block is in the list and cancel the event if it's not. But I can't seem to create and add things in it any other way than in the actual event itself (which looks to me like it would create issues). The only thing that is working for me is creating the list in the event and adding blocks to it one by one which looks really messy compared to: creating the list in a separate class and just checking the list with if(Listname.contains(block)) does anyone know how I can achieve this? Whether its dependency injection, or whatever else. I just can't figure out how to put it to use.
Here's what I've tried and is currently working for me, but I believe it's theoretically incorrect:
public class Event implements Listener {
#EventHandler
public void onBreak(BlockBreakEvent e) {
List<Material> allowedblocks = new ArrayList<Material>();
allowedblocks.add(Material.STONE);
//repeat this 10-50 times for whatever item
Player p = e.getPlayer();
Material block = e.getBlock().getType();
if(allowedblocks.contains(block)){
p.sendMessage("Invalid block. Break cancelled");
e.setCancelled(true);
}else{
p.sendMessage("Valid Block");
}
}
}
You can make allowedBlocks List a class field and fill it with elements inside of the constructor.
public class YourClass {
private List<Material> allowedBlocks = new ArrayList<>();
public YourClass() {
allowedBlocks.add(Material.STONE);
//repeat this 10-50 times for whatever item
}
#EventHandler
public void onBreak(BlockBreakEvent e) {
Player p = e.getPlayer();
Material block = e.getBlock().getType();
if(allowedBlocks.contains(block)){
p.sendMessage("Valid Block");
} else {
p.sendMessage("Invalid block. Break cancelled");
e.setCancelled(true);
}
}
}
Another approach would be to make the list static and fill it with values inside of a static block. I would not recommend making the list static if you are planning to change its values, but if your allowed blocks are going to remain the same, it may be a good idea to even go further and make it public, so you can access it from anywhere without an instance of YourClass
public class YourClass {
public static final List<Material> allowedBlocks;
static {
List<Materials> list = new ArrayList<>();
list.add(Material.STONE);
//repeat this 10-50 times for whatever item
//use an unmodifiable list,
//so you do not accidentally change its content later
allowedBlocks = Collections.unmodifiableList(list);
}
#EventHandler
public void onBreak(BlockBreakEvent e) {
Player p = e.getPlayer();
Material block = e.getBlock().getType();
if(allowedBlocks.contains(block)){
p.sendMessage("Valid Block");
} else {
p.sendMessage("Invalid block. Break cancelled");
e.setCancelled(true);
}
}
}
In the first case, there will be a list of allowedBlocks per instance of YourClass, which means, that every time you call new YourClass() a new List will be created and filled. In the second case, there will be only one list which will be created and populated on class loading (at the very beginning of the program) start up.
P.S. I would rather use a Set instead of a List here, considering you are using contains very often.
Since you are using an enum to store your Material types, you can simply call the static .values() method through Material.
Ex:
#EventHandler
public void onBreak(BlockBreakEvent e) {
Player p = e.getPlayer();
Material block = e.getBlock().getType();
if(List.of(Material.values()).contains(block)){
p.sendMessage("Invalid block. Break cancelled");
e.setCancelled(true);
}else{
p.sendMessage("Valid Block");
}
}
}
If you need to be able to customize what values are in the List you can use the singleton pattern to access that information globally.
The instance can be accessed statically from anywhere in the application:
import java.util.List;
public class BlockController {
public static BlockController instance = new BlockController();
private List<Material> allowedBlocks;
public BlockController() {
this.allowedBlocks = new ArrayList<>();
}
public void addAllowedBlock(Material mat) {
this.allowedBlocks.add(mat);
}
public void removeAllowedBlock(Material mat) {
this.allowedBlocks.remove(mat);
}
public boolean containsBlock(Material mat) {
return this.allowedBlocks.contains(mat);
}
public void clear() {
this.allowedBlocks.clear();
}
/**
* You can add more functionality here...
* This class can be accessed anywhere in the application
*
* use:
*
* BlockController controller = BlockController.instance;
* controller.containsBlock(Material.BLOCK);
*/
}
One approach to creating the list in a separate class is to use a static initializer block:
public class MyClass {
public static final List<Material> ALLOWED_MATERIALS = new ArrayList<>();
static {
ALLOWED_MATERIALS.add( Material.STONE );
}
public static List<Material> getAllowedMaterials() {
return Collections.unmodifiableList( ALLOWED_MATERIALS );
}
...
}
Try to create the List in a static context. This way the list is the same for all instances:
public class MyClass {
public static List<Material> allowedblocks = new ArrayList<Material>();
#EventHandler
public void onBreak(BlockBreakEvent e) {
allowedblocks.add(Material.STONE);
...
Then you can call the List from everywhere like this (e.g. if statement):
if(MyClass.allowedblocks.contains(block))
Your problem seems similar to this question, maybe this answer helps too: .

Anonymous inner class example validity concern

I was trying to review some of the Java language using a spark chart I had once bought. Regarding the use of anonymous inner classes they give this example :
Dice rollDice() {
return new Dice() {
int number = (int)( Math.random() * 6 ) + 1;
};
}
Problem is, I do not see how this would work, and can not get the compiler to accept it as a method within another class. The compiler complains about each reference to Dice "symbol can not be found."
Am I not understanding their example correctly or is this completely invalid code? Thanks in advance!
p.s. if this is working code, could someone provide me with an example of how it can be used?
Edit: I have found something that finally makes sense
The syntax for an anonymous inner class is shown below
new SuperClassName/InterfaceName() {
// Implement or override methods in superclass or interface
// Other methods if necessary
}
This above code is passed to a method that takes an instance of Superclass or completely implements the Interface. For instance, a method that has an EventHandlerparameter and we have not already defined a class that implements the handle(ActionEvent e) method.
enlargeButton.setOnAction(
new EventHandler<ActionEvent>() {
public void handle(ActionEvent e) {
circlePane.enlarge();
}
});
In this way, it will truly be anonymous. I think the example given in Java's own tutorial to be very poor.
It looks like you've mostly answered your own question and you will probably want to go through some full tutorial or documentation to understand things fully, but here are some answers to your immediate questions.
Your first sample code wont compile until you have a Dice class or interface you can extend. So as an example you can get this code to compile:
class Dicey {
interface Dice {
}
Dice rollDice() {
return new Dice() {
int number = (int) (Math.random() * 6) + 1;
};
}
public static void main(String... none) {
Dice dice = new Dicey().rollDice();
// dice.number; <-- not available
}
}
Now you can do this, but as you suspect this is not a very useful things to do (for a few reasons) but the biggest problem is that after you create this anonymous instance there isn't really a way to get to the .number member.
More usually you would have an anonymous subclass implement some methods on the interface, so that you can actually do something with it. So for example
class HelloAnonymous {
interface Hello {
String say();
}
Hello hello(String world) {
return new Hello() {
public String say() {
return world;
}
};
}
public static void main(String... none) {
System.out.println(new HelloAnonymous().hello("world").say());
// prints 'world'
}
}
gives you a way of making fantastically useful Hello objects that can say something. Having said all this, writing anonymous inner classes is fairly old school because functional interfaces now largely replace the need for them. So in this example you could have:
class HelloAnonymous {
#FunctionalInterface
interface Hello {
String say();
}
// old school
Hello hello(String world) {
return new Hello() {
public String say() {
return world;
}
};
}
// with lambda notation
Hello alsoHello(String world) {
return () -> {
return world;
};
}
public static void main(String... none) {
System.out.println(new HelloAnonymous().hello("world").say());
System.out.println(new HelloAnonymous().alsoHello("world").say());
}
}
since I don't know about 'Dice' class I cannot write same method but I try some thing similar to that. It compile and work can access 'number' variable by using reflection. My opinion is it is not very useful. Following is my code:
public class TestClass {
public static void main(String a[]){
TestClass aClass = rollDice();
try {
System.out.println("value of number : " + aClass.getClass().getDeclaredField("number").getInt(aClass));
}
catch (NoSuchFieldException e) {
e.printStackTrace();
}
catch (IllegalAccessException e) {
e.printStackTrace();
}
}
static TestClass rollDice() {
return new TestClass() {
int number = (int) (Math.random() * 6) + 1;
};
}
}
That example is extremely broken. Throw that source away. Try this:
import java.util.Random;
public class DieFactory {
interface Die { int roll(); }
static Die create(long seed) {
Random random = new Random(seed);
return new Die() {
#Override
public int roll() {
return random.nextInt(6) + 1;
}
};
}
// Now you can roll 2 dice pretty easily.
public static void main(String [] args) {
DieFactory.Die die1 = DieFactory.create(42);
DieFactory.Die die2 = DieFactory.create(24);
for (int i = 0; i < 40; i++) {
System.out.println(die1.roll() + die2.roll());
}
}
}
Incidentally, the word "dice" is plural for the singular "die."

How can a static method change a variable? (Java)

I have this class:
class Inventory {
boolean smallknife = false;
boolean SRLockerkey = false;
void checkinv () {
System.out.println("You have the following items in your inventory: ");
System.out.println(smallknife);
System.out.println(SRLockerkey);
}
}
The Inventory test class
class InvTester {
public static void main(String args[]) {
Inventory TestInv = new Inventory();
System.out.println("This program tests the Inventory");
SKTrue.truth(TestInv.smallknife);
TestInv.checkinv();
}
}
and this class with a method to try to change the inventory
class SKTrue {
static boolean truth(boolean smallknife) {
return true;
}
}
class SKTrue {
static void truth(boolean smallknife) {
smallknife = true;
}
}
I would like to avoid using TestInv.smallknife = SKTrue.truth(TestInv.smallknife) and still change the variable but with a method. Is there a way that this can be done? I want that the truth method does the variable changing and I don't want to do the pass by reference part in the Inventory Test class. Thanks. Is there a way to do this in Java? (I also tried the second version which I think makes more sense)
Assuming you don't want to reference the variables directly (i.e. TestInv.smallknife = blah), the best practice in Java is to declare the variables as private and access them by getters/setters, e.g.:
class Inventory {
private boolean smallknife;
public boolean isSmallknife() {
return smallknife;
}
public void setSmallknife(boolean smallknife) {
this.smallknife = smallknife;
}
}
Now, you can do this:
Inventory TestInv = new Inventory();
TestInv.setSmallknife(SKTrue.truth(blah));
It is called Encapsulation, you can read more about it here.

Calling an array from a different class - Java

How can I access my array from a different class? I have 3 classes; Main (where I want to access the array from) FramePanel (my GUI and where the value from UserInputNum is taken from) and StoryArray (where my array is saved).
I need to access the array in the nested If loop in the Main class, this is because I want too save the specific array data to a string and eventually append it into a JTextArea.
Here are the two classes needed:
Main.java
public class Main
{
public static String UserInput;
public static int UserInputNum;
public static void main(String[] args)
{
FramePanel.main();
StoryArray.main();
UserInputNum = Integer.parseInt(UserInput);
if (UserInputNum >= 0)
{
if (UserInputNum <= 399)
{
StoryArray.storyLine[UserInputNum];
}
else
{
}
}
else
{
}
}
}
StoryArray.java
public class StoryArray
{
public static String storyLine[] = null ;
public String[] getStoryLine()
{
return storyLine;
}
public static void main()
{
//String[] storyLine;
storyLine = new String[399];
storyLine[0] ("1")
storyLine[1] ("2")
storyLine[2] ("3")
storyLine[3] ("4")
storyLine[4] ("5")
storyLine[5] ("6")
In another class you can call the array like this:
String value = StoryArray.storyLine[index];
As it is a static public field you can access it directly by StoryArray.storyLine. But as you have a getter ethod I would suggest to make this getter setter static and the array field private and access it through getter method like that: StoryArray.getStoryLine() (to see why read about encapsulation).
You also shouldn't start your class (main) name from lower case, here are standard coding conventions for java language: http://www.oracle.com/technetwork/java/codeconvtoc-136057.html
Once you've called StoryArray.main(), then you should be able to do StoryArray.storyLine[/*element id*/] = "whatever you want" to get or set any element in storyLine. Additionally, you aren't defining any default array values. In StoryArray.main(), you need to have lines of the form storyLine[n] = "n".

How to write an Iterator for a custom class in Java

I have this class:
public class MyClass{
private Test test;
public class Test{
int num;
String color;
public Test(int num, String color){
this.num = num;
this.color = color;
}
}
public MyClass(){
}
public void setNum(int number){
test.num = number;
}
public void setColor(String color){
test.color = color;
}
public Test getTest(){
return test;
}
}
I am setting the values from another class and at the end I call the method getTest:
MyClass myclass = new MyClass();
.
.
.
Test test1 = myclass.getTest();
I want to Iterate the object test1 to get the values. Is that possible? Do I have to implement hasNext() method inside the class MyClass? If yes, how can I do it?
You question has already been asked and answered.
Basic idea - you need to use reflection API . E.g construction test.getClass().getDeclaredFields();
Note: you will not create iterator this way, but you will be able to iterate through class fields. That slightly different things.
You want this?
public static void main(String[] args) {
MyClass myclass = new MyClass();
Test test1 = myclass.getTest();
//you need modify private Test test = new Test(1, "hahs");
//import java.lang.reflect.Field;
Field[] fields = test1.getClass().getDeclaredFields();
for (int j = 0; j < fields.length-1; j++) {
fields[j].setAccessible(true);
try {
System.out.println(fields[j].get(test1));
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//output
//1
//hahs
}
You will have to use reflection in order to iterate through the members of the test class. You will have to import java.lang.reflect.* and call Class.forName("test1) to get a Class object, and call the getDeclaredFields method of the Class object to get an array of Field objects. The Field object has get and set methods that get or set the value of the field.

Categories