如何在Java程序中解决两个电梯场景

时间:2019-05-17 06:55:05

标签: java io java.util.scanner data-manipulation

以下是需求方案-这是一个黑客问题。

一个街区共有7层,只有2部电梯。最初,电梯A位于一楼,电梯B位于顶层。每当有人从第N楼呼叫电梯时,最接近该楼层的电梯就会接他。如果两个电梯都与第N楼等距,则它们从较低楼层的电梯就会出现。

我正在尝试为上述情况编写Java代码,但无法获得预期的结果

我已经为两个升降机的位置初始化了一个整数,并为楼层呼叫初始化了一个整数。我使用了是否有操作员的条件来查找位置,并打印出将到达用户的电梯。问题陈述的正确编程过程是什么?请帮助。 TIA。

import java.util.*;

class TestClass {
    public static void main(String args[] ) throws Exception {

        Scanner s = new Scanner(System.in);
        int count=s.nextInt();
        int[] fc=new int[count];
        int posA=0;
        int posB=7;


        for(int i=0;i<count;i++){
            fc[i]=s.nextInt();

            if((fc[i]-posA)<(posB-fc[i])){
                posA=fc[i];
                System.out.println("A");
            }

            if((fc[i]-posA)==(posB-fc[i])){
                if(posA<posB){
                    posA=fc[i];
                    System.out.println("A");
                }
                else if(posA>posB){
                    posB=fc[i];
                    System.out.println("B");
                }
            }
            else{
                posB=fc[i];
                System.out.println("B");
            }            
        }
    }
}

我的输入,当前和预期输出在下面提到。

输入-10 0 6 4 1 1 2 4 0 3 1

当前输出-A B B B A B B B A B

预期的输出-A B B A A A B A B A

2 个答案:

答案 0 :(得分:2)

您刚刚错过了,距离应始终为正整数。

计算距离时使用Math.abs()

另外,在第一个else块之后,缺少if。 另外,if(posA>posB)太多了,因为它过滤掉了posA==posB

我的代码:

package de.test.lang.stackexchange;

public class Lifts {

    public static void main(String args[]) throws Exception {
        int[] fc = new int[]{0, 6, 4, 1, 1, 2, 4, 0, 3, 1};
        int posA = 0;
        int posB = 7;

        for (int reqPos: fc) {
            final int distA = Math.abs(reqPos - posA);
            final int distB = Math.abs(reqPos - posB);

            if (distA < distB) {
                posA = reqPos;
                System.out.println("A");
            } else if (distA == distB) {
                if (posA < posB) {
                    posA = reqPos;
                    System.out.println("A");
                } else {
                    posB = reqPos;
                    System.out.println("B");
                }
            } else {
                posB = reqPos;
                System.out.println("B");
            }
        }
    }
}

输出:A B B A A A B A B A

(顺便说一句:很好的作业...)

答案 1 :(得分:0)

您好,有一个建议,我们可以在Java中使用三元运算符来减少行数

public static void main(String[] args) {
        int numberOfFloors = 7 ;            
        int midFloor = Math.round((float)numberOfFloors/2);
        System.out.println(midFloor);
        int[] fc = new int[]{0, 6, 4, 1, 1, 2, 4, 0, 3, 1};

        for (int currentFloor : fc) {
            String liftToBeCalled = numberOfFloors-currentFloor> midFloor?"A":"B";
            System.out.print(liftToBeCalled+" ");
        }
    }

这将给

A B B A A A B A B A