程序原题如下:设计一类 Parking, 构造函数参数为停车位的数量
如下方法:int bookPlace() 返回 一个空闲的停车位
void freePlace(int index) 把index号的车位置为空闲
void printPlace()
比如停车位输入3,则打印如下信息:
Number place total:3
place 0:occupy
place 1:free
place 2:occupy我初写了程序,有些问题,希望高手帮忙看看程序,还有后面2个方法也帮忙解决下
public class Parking
{
int bloc[];
boolean occupe[]=new int[nbplace];
public Parking(int nbplace)
{
this.nbplace=nbplace;
}
public int bookPlace()
{
for(int i=0;i<nbplace;i++)
if(occupe[i]==0)
System.out.println("place "+ i +" free\n");
return 0;
} public static void main (String args[])
{
Parking v=new Parking(10);
v.bookPlace();
}
}
如下方法:int bookPlace() 返回 一个空闲的停车位
void freePlace(int index) 把index号的车位置为空闲
void printPlace()
比如停车位输入3,则打印如下信息:
Number place total:3
place 0:occupy
place 1:free
place 2:occupy我初写了程序,有些问题,希望高手帮忙看看程序,还有后面2个方法也帮忙解决下
public class Parking
{
int bloc[];
boolean occupe[]=new int[nbplace];
public Parking(int nbplace)
{
this.nbplace=nbplace;
}
public int bookPlace()
{
for(int i=0;i<nbplace;i++)
if(occupe[i]==0)
System.out.println("place "+ i +" free\n");
return 0;
} public static void main (String args[])
{
Parking v=new Parking(10);
v.bookPlace();
}
}
public class Parking
{
boolean occupe[];
public Parking(int nbplace)
{
occupe = new boolean[nbplace];
for(int i=0;i<occupe.length;i++)
occupe[i]=false;
}
public int bookPlace()
{
for(int i=0;i<occupe.length;i++)
if(!occupe[i])
return i;
return -1;
} void freePlace(int index)
{
occupe[index] = false;
}
void printPlace()
{
System.out.println("Number place total:"+occupe.length);
for(int i=0;i<occupe.length;i++)
{
System.out.print("place "+i+":");
System.out.println(occupe[i]?"occupy":"free");
}
}
public static void main (String args[])
{
Parking v=new Parking(10);
v.bookPlace();
}
}
1、nbplace没有定义
2、int bloc[]; 数组写法上有些问题,不过不影响程序正常运行,只是个人习惯问题,建意写成int[] bloc
cheng_young(古道西风瘦马) 程序应该是正确的。
public class Parking extends Thread{ private int nbplace = 0; private boolean[] occupe; /** constructor */
public Parking(int nbplace) {
this.nbplace = nbplace;
occupe = new boolean[nbplace];
} /** freeplace */
public void freePlace(int index) {
occupe[index] = false;
} /** bookPlace */
public int bookPlace() {
for (int i = 0; i < nbplace; i++)
if (!occupe[i])
return i;
return -1;
} /** printPlace */
public void printPlace() {
for(int i=0;i<getNbplace();i++){
System.out.println(i+"is :"+(occupe[i]?"occupied":"free"));
}
}
/** getPlace from kbd */
public String getPlace() throws IOException {
String place = null;
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader bf = new BufferedReader(isr);
place = bf.readLine();
return place;
} public static void main(String args[]) throws IOException {
Parking v = new Parking(10);
v.run();
v.printPlace();
} public void run() {
int p=(int)(Math.random()*9)+1;
if(!occupe[p])
occupe[p]=true;
} public int getNbplace() {
return nbplace;
}
}