我必须输入一些指令并以相反的顺序打印出来。我只能输入一条指令并同时输出一条指令。
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
?
答案 0 :(得分:0)
这是一种方法:
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");
}
}
您可以向列表中添加任意数量的指令。我也稍微格式化了输出,但这不是必需的。