zoukankan      html  css  js  c++  java
  • 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;
        }
    }
    
  • 相关阅读:
    第三次冲刺
    第二次冲刺
    第一次冲刺
    Beta版本的发布
    第七次冲刺
    SpringMVC+Spring+mybatis 项目实践
    JSP显示新闻
    一个简单的静态邮箱登录界面
    Java Web 基础
    总结
  • 原文地址:https://www.cnblogs.com/yu-jiawei/p/12371098.html
Copyright © 2011-2022 走看看