我非常感谢我对java代码的一些帮助。我正在使用ArrayLists来存储用户喜欢的车辆类型。因此他们将输入车辆,直到他们输入“退出”以退出循环。然后它将打印数组列表。现在,它只是阅读所有其他输入。根据输入的输入数量,用户可能必须在打印结果之前键入“退出”两次。非常感谢任何帮助,谢谢!
package bacaCCh6Sec8;
import java.util.ArrayList;
import java.util.Scanner;
public class BacaCCh6Sec8 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
ArrayList<String> vehicles = new ArrayList<>();
boolean done = false;
final String EXIT = "Exit";
System.out.printf("Enter your favorite vehicles.\n");
System.out.printf("Type Exit after you have input all your vehicles.\n");
do {
String input = in.next();
if (!input.equals(EXIT)) {
vehicles.add(in.next());
} else {
done = true;
} // end If
} while (!done); // End Do While
System.out.printf("Your favorite vehicles are %s.\n" , vehicles);
} // End Main
} // End Class
答案 0 :(得分:1)
用户可能必须输入&#34;退出&#34;在打印结果之前两次 出
问题是您要两次调用docker exec -it <container_id> bash
方法,因此用户必须输入两次值。解决方案是简单地使用您从第一个next()
方法获得的值,而不是丢弃它。
next()
答案 1 :(得分:0)
.next()
的每次调用实际上都会读取输入。因此,如果您拨打.next()
两次,它会读两行。要将更改vehicles.add(in.next());
更正为vehicles.add(input);
答案 2 :(得分:0)
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
ArrayList<String> vehicles = new ArrayList<>();
boolean done = false;
final String EXIT = "Exit";
System.out.printf("Enter your favorite vehicles.\n");
System.out.printf("Type Exit after you have input all your vehicles.\n");
do {
String word = in.next();
if(word.equalsIgnoreCase("exit")) break;
vehicles.add(word);
} while (!done); // End Do While
System.out.printf("Your favorite vehicles are %s.\n" , vehicles);
}
}
不是我最好的代码,但有帮助
Enter your favorite vehicles.
Type Exit after you have input all your vehicles.
hola
mundo
exit
Your favorite vehicles are [hola, mundo].