![](/img/trans.png)
[英]Using GenericQueue to print words input by user in reverse order. Java
[英]Input instructions and print them out in reverse order using ArrayList
我必須輸入一些說明並以相反的順序打印出來。 我只能輸入一條指令,同時只能輸出一條指令。
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");
}
}
您可以在列表中添加任意數量的指令。 我也格式化了輸出,但這不是必需的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.