当前位置:首页 > java2实用教程第四版实验 清华大学出版社4-3,4-4(北华大学吕磊)
4-3共饮同井水 class Village {
static int waterAmount; int peopleNumber; String name;
Village(String s){ name =s; }
static void setWaterAmount(int m){ if(m>0)
waterAmount=m; }
void drinkWater(int n){ if(waterAmount-n>=0){
waterAmount=waterAmount-n;
System.out.println(name+\喝了\+n+\升水\); } else
waterAmount=0; }
static int lookWaterAmount(){ return waterAmount; }
void setPeopleNumber(int n){ peopleNumber=n; }
int getPeopleNumber(){ return peopleNumber; } }
public class Land{
public static void main(String args[]){ Village.setWaterAmount(200);
int leftWater=Village.waterAmount;
System.out.println(\水井中有\+leftWater+\升水\);
Village zhaoZhuang,maJiaHeZhi; zhaoZhuang = new Village(\赵庄\);
maJiaHeZhi = new Village(\马家河子\); zhaoZhuang.setPeopleNumber(80); maJiaHeZhi.setPeopleNumber(120); zhaoZhuang.drinkWater(50);
leftWater=maJiaHeZhi.lookWaterAmount(); String name=maJiaHeZhi.name;
System.out.println(name+\发现水井中有\+leftWater+\升水\);
maJiaHeZhi.drinkWater(100);
leftWater=zhaoZhuang.lookWaterAmount(); name=zhaoZhuang.name;
System.out.println(name+\发现水井中有\+leftWater+\升水\); int
peopleNumber=zhaoZhuang.getPeopleNumber(); System.out.println(\赵庄的人口:\+peopleNumber);
peopleNumber=maJiaHeZhi.getPeopleNumber(); System.out.println(\马家河子的人口:\+peopleNumber); } }
4-4方程的根
package tom.jiafei;
public class SquareEquation { double a,b,c;
double root1,root2;
boolean boo;
public SquareEquation(double a,double b,double c){ this.a=a; this.b=b; this.c=c; if(a!=0) boo=true; else
boo=false; }
void getRoots(){ if(boo){
System.out.println(\是一元二次方程\); double disk=b*b-4*a*c; if(disk>=0){
root1=(-b+Math.sqrt(disk))/(2*a); root2=(-b+Math.sqrt(disk))/(2*a); System.out.printf(\方程的根:%f,%f\\n\,root1,root2); }
else{
System.out.printf(\方程没有实根\\n\); } }
else{
System.out.println(\不是一元二次方程\); } }
void setCoefficient(double a,double b,double this.a=a; this.b=b; this.c=c; if(a!=0) boo=true;
c){ else
boo=false; } }
class SunRise{
public static void main(String args[]){ SquareEquation equation=new SquareEquation(4,5,1); equation.getRoots();
equation.setCoefficient(-3,4,5); equation.getRoots(); } }
共分享92篇相关文档