Let the Balloon Rise

Let the Balloon Rise_第1张图片
根据问题描述,我们可以提取信息如下:
1、先输入一个数字n,若数字n不为0,则输入n个String类型的颜色的单词,若数字n为0,则停止输入。
2、最后统计每个数字后面颜色最多的单词。

先建立一个colour类

public class Colour {
	public List colour = new ArrayList();//储存单词
	public int num[] = null;//储存每个颜色单词的个数
	
	public List getColour() {
		return colour;
	}
	public void setColour(List colour) {
		this.colour = colour;
	}
	public int[] getNum() {
		return num;
	}
	public void setNum(int[] num) {
		this.num = num;
	}
	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result +
		((colour == null) ? 0 : colour.hashCode());
		result = prime * result + Arrays.hashCode(num);
		return result;
	}
	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		Colour other = (Colour) obj;
		if (colour == null) {
			if (other.colour != null)
				return false;
		} else if (!colour.equals(other.colour))
			return false;
		if (!Arrays.equals(num, other.num))
			return false;
		return true;
	}
	public Colour(List colour, int[] num) {
		super();
		this.colour = colour;
		this.num = num;
	}
	public Colour() {
		super();
	}
	@Override
	public String toString() {
		return "colour = " + colour + ", num=" +
		Arrays.toString(num) + "]";
	}
}
public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		
		//定义一个colour类型容器   储存colour对象
		List colour = new ArrayList();
		
		while(true){
			Colour colo = new Colour();
			int a = sc.nextInt();
			if(a == 0){
				break;
			}else{
				colo.num = new int[a];
				for (int j = 0; j < colo.num.length; j++) {
					colo.num[j] = 0;
				}
				//输入n个颜色单词
				for (int j = 0; j < a; j++) {
					String str = sc.next();
					if(colo.colour.contains(str)){//若该单词存在
						int index = colo.colour.indexOf(str);
						colo.num[index]++;
					}else{//若该单词不存在
						colo.colour.add(str);
						int index = colo.colour.indexOf(str);
						colo.num[index]++;
					}
				}
			}
			colour.add(colo);//把颜色对象加入list容器中
		}
		
		//通过迭代器,依次输出每个colour对象中出险次数最多的颜色单词
		Iterator it = colour.iterator();
		while(it.hasNext()){
			Colour c = it.next();
			int index = getMax(c);
			System.out.println(c.colour.get(index));
		}
		sc.close();
	}
	
	
	/**
	 * @param c是colour对象
	 * @return 颜色个数最大的下标
	 */
	private static int getMax(Colour c) {
		int max = 0;
		for (int i = max + 1; i < c.num.length; i++) {
			if(c.num[i] > c.num[max]){
				max = i;
			}
		}
		return max;
	}

例:
Let the Balloon Rise_第2张图片
这是学习Java时在网上找的一个练习题,用的方法也是最简单粗暴的方法,主要是为了练习Java编程;当然若是学过算法设计,会有更好的解决方法,日后若是有时间回和大家分享。

你可能感兴趣的:(Java,Java,Let,the,Balloon,Rise,伏都哥哥)