How do I make this get method for array lists simpler?
本问题已经有最佳答案,请猛点这里访问。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 | import java.util.*; public class ChristmasParty { private Scanner input = new Scanner(System.in); public static void main(String[] args) { ChristmasParty cp = new ChristmasParty(); cp.run(); } public void run() { menu(); addName(); } public void menu() { System.out.println("Welcome to the guests lists program"); System.out.println("Enter a name or enter X to quit"); } public void addName() { String nameAdded =""; ArrayList<String> guestsLists = new ArrayList<String>(); do { System.out.print("Enter a name:"); nameAdded = input.nextLine(); guestsLists.add(nameAdded); System.out.println("-----------------------------------------------"); System.out.println(nameAdded +" has been added to the guests list."); }while(!nameAdded.equals("X")); System.out.println("Guests lists:"); System.out.println("========================"); System.out.println(guestsLists.get(0)); System.out.println(guestsLists.get(1)); System.out.println(guestsLists.get(2)); System.out.println(guestsLists.get(3)); System.out.println(guestsLists.get(4)); System.out.println(guestsLists.get(5)); System.out.println(guestsLists.get(6)); System.out.println(guestsLists.get(7)); System.out.println(guestsLists.get(8)); System.out.println(guestsLists.get(9)); System.out.println(guestsLists.get(10)); System.out.println(guestsLists.get(11)); System.out.println(guestsLists.get(12)); System.out.println(guestsLists.get(13)); System.out.println(guestsLists.get(14)); System.out.println(guestsLists.get(15)); } } |
您好,我正在尝试编写一个代码,它将提示用户输入一个名称,该名称将保存在ArrayList中,然后一旦用户退出并按"x"退出,它将显示列表中的所有名称。但是,如何使system.out.println(guessLists.get());代码比全部输入简单?
放这个代码:
1 2 3 4 5 6 7 8 9 |
或
然后移除
system.out.println("================");
只需使用增强的
当您不需要循环内的索引,但只想遍历集合时,可以使用
另请参见https://docs.oracle.com/javase/tutorial/java/nutsandbolts/for.html