华为机试第三道编程题:
题目大致如下:
输入:starttimer:1,1000
会打开一个id为1的计数器,初始秒数是1000ms。
还可以输入:elapse:1000
这会使得当前所有计时器减去1000ms。
输入:end
将打印出所有计时器的状态,如:timer:2,1000
时间用完的计时器就不会输出了。
如果所有计时器都计时完毕,打印:None
例如:(输入)
starttimer:1,1000
starttimer:2,2000
elapse:1000
end
(输出)
timer:2,1000
我的思路,当时在考场是想要用线程来解决,因为最近看了一点,但是我发现我简直是中邪了才想到用线程= =
回学校想了一下,只花了20多分钟完成现在的代码。
思路如下:
内部类:Timer,属性有id和time,方法包括:1.修改time;2.打印自己。
main方法内:建立ArrayList,存放所有新建
import java.util.*;
public class Test03
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
String cmd ="";
int timerID=0;
ArrayList<Test03.Timer> list = new ArrayList<Test03.Timer>();
while(sc.hasNextLine())
{
String string = sc.nextLine();
if(string.equals("end"))
{
if(list.isEmpty())
{
System.out.println("none");
}else{
int countNone =0;
for(int j =0;j<list.size();j++)
{
if(list.get(j).getTime()==0)
{
countNone++;
}else
{
list.get(j).print();
}
}
if(countNone==list.size())
{
System.out.println("None");
}
}
break;
}else{
String[] str = string.split(":");
cmd =str[0];
if(cmd.equals("starttimer"))
{
String[] str2 = str[1].split(",");
timerID = Integer.parseInt(str2[0]);
int time = Integer.parseInt(str2[1]);
list.add(new Test03().new Timer(timerID,time));
} else if(cmd.equals("elapse"))
{
if(list.isEmpty())
{
System.out.println("No timer! Please initial a Timer before elapse!");
} else
{
int elapseTime = Integer.parseInt(str[1]);
for(int i =0;i<list.size();i++)
{
list.get(i).elapse(elapseTime);
}
}
}
}
}
}
class Timer
{
private int id=0;
private int time=0;
public Timer(int id,int time)
{
this.id = id;
this.time = time;
}
public int getID()
{
return this.id;
}
public int getTime()
{
return this.time;
}
public void setTime(int time)
{
this.time=time;
}
public void setID(int id)
{
this.id = id;
}
public void elapse(int elapseTime)
{
int currentTime = getTime();
if(currentTime>elapseTime)
{
setTime(currentTime-elapseTime);
}else
{
setTime(0);
}
}
public void print()
{
//timer:2,1000
System.out.println("timer:"+getID()+","+getTime());
}
}
}