gpt4 book ai didi

java - 输入指令并使用ArrayList逆序打印出来

转载 作者:太空宇宙 更新时间:2023-11-04 14:50:37 24 4
gpt4 key购买 nike

我必须输入一些指令并以相反的顺序打印出来。我只能输入一条指令,同时输出一条指令。

public class ReturningHome {

public static void main(String[] args) {
// TODO Auto-generated method stub

String direction;
String Street;


while (true){
System.out.println("Enter instructions from Home to School");
System.out.println("Please input instructions in the format:"
+ "\nDirections: [L/R]"
+ "\nStreet Name: [Street Name]");
System.out.println("The final instruction should be SCHOOL");

System.out.println("");
System.out.println("Enter a Direction");
direction = TextIO.getlnString();
switch (direction){
case "L":
System.out.println("Enter a Street Name");
Street = TextIO.getlnString();
switch (Street){
case "SCHOOL":
System.out.println("Instructions from School to Home:");
System.out.println("Turn RIGHT into your HOME");
System.exit(0);

break;
default:
System.out.println("Instructions from School to Home:");
System.out.println("Turn RIGHT onto "+Street+ " Street");
System.out.println("");
break;
}
break;

case "R":
System.out.println("Enter a Street Name");
Street = TextIO.getlnString();
switch (Street){
case "SCHOOL":
System.out.println("Instructions from School to Home:");
System.out.println("Turn LEFT into your HOME");
System.exit(0);
break;
default:
System.out.println("Instructions from School to Home:");
System.out.println("Turn LEFT onto "+Street+ " Street");
System.out.println("");
break;
}

break;


default:
System.out.println("Invalid Choice");
break;

}
}
}
}

如何使用 ArrayList 执行此操作?

最佳答案

这是一种实现方法:

public class Instructions {

public static void main(String[] args) {

// Print instructions...

List<String> instructionsList = new ArrayList<>();
Scanner scanner = new Scanner(System.in);
String input = null;

while (true) {

do {
System.out.println("Enter a direction");
input = scanner.next();
} while (!input.matches("L|R"));
instructionsList.add(input);

System.out.println("Enter a street name");
input = scanner.next();
if (input.matches("SCHOOL"))
break;
instructionsList.add(input);
}

scanner.close();

System.out.print("From SCHOOL ");
for (int i = instructionsList.size() - 1; i >= 0; i--) {
if ((instructionsList.size() - i)%2 == 1)
System.out.printf("turn %s to%n", instructionsList.get(i));
else
System.out.printf("%s, then ", instructionsList.get(i));
}
System.out.println("HOME");
}
}

您可以向列表中添加任意数量的指令。我还对输出进行了一些格式化,但这不是必需的。

关于java - 输入指令并使用ArrayList逆序打印出来,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23838886/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com