问题
how can I get it to go back to start another directory when the user types yes and also how do I print the arraylist out using a print format
thanks
import java.util.ArrayList;
import java.util.Scanner;
public class AAA
{
public static void main(String[] args)
{
ArrayList<String> name = new ArrayList<String>();
ArrayList<Integer> phone = new ArrayList<Integer>();
Scanner scanner = new Scanner(System.in);
{
System.out.println("Please enter your name: ");
name.add(scanner.next());
System.out.println("Please enter your number: ");
phone.add(scanner.nextInt());
System.out.println("Do you want to add a directory yes/no?");
String answer = scanner.nextLine();
if (answer.equals("yes"));
//want it to go back to start another direcotry here
else
{
System.out.println("Thanks for adding to the directory");
System.out.println(answer());
}
}
}
}
回答1:
Try to use a while true, and then, when the user types no, you break the look. The code seems like this:
ArrayList<String> name = new ArrayList<String>();
ArrayList<Integer> phone = new ArrayList<Integer>();
Scanner scanner = new Scanner(System.in);
while(true){
System.out.println("Please enter your name: ");
name.add(scanner.next());
System.out.println("Please enter your number: ");
phone.add(scanner.nextInt());
System.out.println("Do you want to add a directory yes/no?");
String answer = scanner.next();
if (answer.equals("no")){
System.out.println("Thanks for adding to the directory");
System.out.println(answer());
break; //
}
}
There are another strategies, like using a do/while. But essentially you have to use a loop.
回答2:
You can easily print out an ArrayList:
System.out.println(list);
It will print something like:
[one, two, three]
where one, two, three are the results of invocation of toString() or array list's elements.
You can remove [] easily by:
System.out.println(list.toString().replace("[", "").replace("]", ""));
You you need to use your custom format implement print in loop:
for (String s : list) {
System.out.println(format(s));
}
回答3:
import java.util.ArrayList;
import java.util.Scanner;
public class AAA {
public static void main(String[] args) {
ArrayList<String> name = new ArrayList<String>();
ArrayList<Integer> phone = new ArrayList<Integer>();
Scanner scanner = new Scanner(System.in);
String answer = "";
{
do {
System.out.println("Please enter your name: ");
name.add(scanner.next());
System.out.println("Please enter your number: ");
phone.add(scanner.nextInt());
System.out.println("Do you want to add a directory yes/no?");
answer = scanner.next();
} while (answer.equals("yes"));
if (answer.equals("yes")); //want it to go back to start another direcotry here
else {
System.out.println("Thanks for adding to the directory");
for (int i = 0; i < name.size(); i++) {
System.out.print(name.get(i)+"\t");
System.out.print(phone.get(i));
System.out.println("");
}
}
}
}
}
来源:https://stackoverflow.com/questions/4460788/java-arraylist-that-stores-userinput