HUAWEI 20140911 Java机试题:计时器问题

华为机试第三道编程题:

题目大致如下:

输入: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());
		}
		
	}

}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值