为啥我的值都是0
package com.imooc.weather;
public class Weather {
private int temperature;
private int humidity;
boolean flag=false;
public int getTemperature() {
return temperature;
}
public void setTemperature(int temperature) {
this.temperature = temperature;
}
public int getHumidity() {
return humidity;
}
public void setHumidity(int humidity) {
this.humidity = humidity;
}
public synchronized void generate() {
if(flag) {
try {
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
setTemperature((int)(Math.random())*100);
setHumidity((int)(Math.random())*40);
System.out.println("生成天气数据:"+new Weather());
flag=true;
notifyAll();
}
public synchronized void read() {
if(!flag) {
try {
wait();
}catch(InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("读取天气数据:"+new Weather());
flag=false;
notifyAll();
}
public String toString() {
return "[温度:"+this.getTemperature()+",湿度:"+this.getHumidity()+"]";
}
}
package com.imooc.weather;
public class GenerateWeather implements Runnable{
Weather weather;
public GenerateWeather(Weather weather){
this.weather=weather;
}
@Override
public void run() {
// TODO Auto-generated method stub
for(int i=0;i<100;i++) {
weather.generate();
try {
Thread.sleep(5000);
}catch(InterruptedException e) {
e.printStackTrace();
}
}
}
}
package com.imooc.weather;
public class ReadWeather implements Runnable{
Weather weather;
public ReadWeather(Weather weather){
this.weather=weather;
}
@Override
public void run() {
// TODO Auto-generated method stub
for(int i=0;i<100;i++) {
weather.read();
try {
Thread.sleep(100);
}catch(InterruptedException e) {
e.printStackTrace();
}
}
}
}
package com.imooc.weather;
public class Test {
public static void main(String[] args) {
Weather one=new Weather();
new Thread(new GenerateWeather(one)).start();
new Thread(new ReadWeather(one)).start();
}
}
正在回答 回答被采纳积分+1
有两点
1、setTemperature((int)(Math.random())*100);
setHumidity((int)(Math.random())*40); 的括号位置写错了,应该把Math.random()*100 放到一个大括号里,改为setTemperature((int(Math.random()*100)); setHumidity((int(Math.random()*40));
2输入的时候,不应该new 一个新的 Weather类,它里边什么都没设置,当然为0,应该的调用get方法,获取当前.Weather的温度和湿度,修改后的代码如下:
System.out.println("生成天气数据:" +"湿度"+this.getHumidity()+"温度" +this.getTemperature());
System.out.println("读取天气数据:" + "湿度"+this.getHumidity()+"温度" +this.getTemperature());
如果我的回答解决了你的疑惑,请采纳!祝学习愉快!
- 参与学习 人
- 提交作业 7317 份
- 解答问题 14452 个
想要入门学编程?多年一直活跃在编程语言排行版前列的Java是一个很好的选择。本路径将从Java基础语法、面向对象、常用工具类三部分,为你开启软件开发的大门!
了解课程
恭喜解决一个难题,获得1积分~
来为老师/同学的回答评分吧
0 星