以下是需求场景 - 这是一个 hackerearth 问题。
一个街区有 7 层,只有 2 部电梯。最初,电梯 A 位于底层,电梯 B 位于顶层。每当有人从第N层调用电梯时,离该层最近的电梯就会来接他。如果两部电梯距N层等距,则下层电梯上行。
我正在尝试为上述场景编写java代码,但无法得到预期的结果
我已经初始化了两个电梯位置的整数和楼层调用的整数。我使用 if 条件与运算符(operator)一起找到位置并打印哪个电梯将到达用户。对于问题陈述来说,正确的编程过程是什么?请帮忙。 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
最佳答案
您刚刚错过了,距离应该始终是正整数。
计算距离时使用Math.abs()
。
另外,第一个 if
block 后缺少一个 else
。
另外,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
(顺便说一句:很好的作业...)
关于java - 如何在java程序中解决两部电梯的场景,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56181106/