日期:2014-05-20  浏览次数:20739 次

急急急!!!!!这几道java试题谁会做!
1.有一百盏灯,全部亮着并且从一到一百进行编号,对每盏灯做如下处理,如果该灯的编号能被1整除则拨一下开关,能被二整除再拨一下,以此类推,直到该灯的编号为至,问最后哪几盏灯亮着。
2、编写一个类,向外提供一个这样的方法:查看该类在内存中有多少个实例。
3、自己写出一个满足单例模式的类。

------解决方案--------------------
2、原理是利用静态成员记数,生成对象(以下这个类只能通过构造函数生成)的时候记数加1,JVM回收对象的时候记数-1。代码如下:

public class Test {
private static int count = 0;
public Test() {
count++;
}
public static int getInstanceNumbre() {
return count;
}
protected void finalize() throws Throwable {
count--;
super.finalize();
}
}
------解决方案--------------------
说一下我对第一道题目的解题思路吧:这道题其实是求一个整数的因子数(包括1和本身),如果为偶数就是开着的。例如2的因子为1、2,双数,所以是开着的。4的因子为1、2、4,单数,所以是关着的。
------解决方案--------------------
1,没看懂
2,public class QueryInstance {
private static int total = 0;
public QueryInstance(){
total ++;
}
public static int getTotal() {
return total;
}
public static void main(String[] args) throws Exception{
Class clazz = Class.forName( "test.QueryInstance ");
QueryInstance qi0 = (QueryInstance)clazz.newInstance();
for (int i = 0; i < 10; i++){
QueryInstance qi = new QueryInstance();
System.out.println(QueryInstance.getTotal());
}
}
}
3,
public class Singleton {
private int total;
private Singleton(){
}
private static Singleton instance;
/**
*
* 考虑到并发的话,需要synchronized
*/
public synchronized static Singleton getInstance(){
if (instance == null){
instance = new Singleton();
}
return instance;
}

public void print(){
System.out.println(total ++);
}

public static void main(String[] args) {
for (int i = 0; i < 10; i ++){
Singleton instance = Singleton.getInstance();
instance.print();
}
}

}
------解决方案--------------------
1
public class Baideng{
public static void main(String []args){
boolean []deng= new boolean[101];//数组默认值为false, 表示灯是开着的;
for(int i=1;i <=100;i++){
for(int j=1;j <=100;j++){
if((j%i)==0)
deng[j]=!deng[j];
}
}
for(int i=1;i <deng.length;i++){
if(!deng[i])
System.out.println( "第 "+i+ "灯是亮着的 ");
}
}
}
------解决方案--------------------
brooksychen(初晨之阳) 正解,典型的面向对象编程,理解得太好了

1、代码如下:

class Lamp {
private int number; //灯的编号
private boolean isOn = true; //最初灯是开着的
public Lamp(int i) {
number = i;
}
public int getNumber() {
return number;
}
public boolean lampIsOn() {
return isOn;
}
public void operate() {
int count = 0; //开关灯次数
for (int i = 1; i <= number; i++) {
//第i次操作时,如果i能整除number,则开关灯次数加1
if (number % i == 0) {
count++;
}
}
if (count % 2 != 0) {
isOn = false;
//如果开关灯次数为奇数,则最后灯是关着的
}
}
}
public class Lamps {
public static void main(String[] args) {