201803-2 碰撞的小球 Java

思路:
直接按照题意模拟,感觉没什么太好的办法。另外注意:int这种基础数据类型不能用equals这个方法 ,必须是Integer类型

import java.util.Scanner;
public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int L = sc.nextInt();
        int t = sc.nextInt();
        int timeCount = 0; //计时器
        Ball [] ball = new Ball[n];
        for (int i = 0; i < n; i++)
            ball[i] = new Ball(sc.nextInt(), 1);
        while (++timeCount <= t) {
            for (int i = 0; i < n; i++) {//到达端点则反向
                if(ball[i].direction == 1) {
                    ball[i].position++;
                    if(ball[i].position == L)
                        ball[i].direction *= -1; //使球反向
                } else {
                    ball[i].position--;
                    if(ball[i].position == 0)
                        ball[i].direction *= -1;
                }
            }
            for (int i = 0; i < n - 1; i++) //判断相撞
                for (int j = i + 1; j < n; j++)
                    if (ball[i].position.equals(ball[j].position)) {
                        ball[i].direction *= -1;
                        ball[j].direction *= -1;
                        break;
                    }
        }
        sc.close();
        for(int i = 0; i < n; i ++) { //输出结果
        	System.out.print(ball[i].position + " ");
        }
    }
}
class Ball {
    public Integer position; //球的位置
    public Integer direction; //球的方向,1为向右,-1为向左
    public Ball(Integer position, Integer direction) {
        this.position = position;
        this.direction = direction;
    }
}
原文地址:https://www.cnblogs.com/yu-jiawei/p/12371098.html