gpt4 book ai didi

java - java中的公共(public)变量?

转载 作者:行者123 更新时间:2023-12-04 20:46:17 25 4
gpt4 key购买 nike

我的程序中有四个类,其中一个包含 main()但是 fruit、ch 和 demand 变量的前三行有错误。我想在每个类中使用这些变量。

    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();

}
}

我该怎么做?我是 Java 初学者?

最佳答案

这段代码不会编译。您需要将这些变量放在类中,如下所示:

import java.util.Scanner;


class stock {

public static int fruit = 0;
public static int ch;
public static boolean demand = false;

....

如果你想在外部访问这些变量,你可以像这样引用它:stock.fruit

关于java - java中的公共(public)变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22769921/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com