【发布时间】:2015-04-14 19:27:03
【问题描述】:
基本上我正在寻找我的问题。我的ABookclass 看起来像这样:
import java.io.*;
import java.util.*;
public class ABook
{
public static void main (String args[])
{
LinkedList addressBook = new LinkedList();
Scanner input = new Scanner(System.in);
System.out.println("Would you like to add a friend? (Say Y or N)");
String reply = input.nextLine();
if(reply.equals("Y"))
{
System.out.println("What is the name of your friend?");
String name = input.nextLine();
System.out.println("What is the age of your friend?");
int age = input.nextInt();
Friend newFriend = new Friend(name,age);
addressBook.add("Name: " + newFriend.name + "; " + "Age: " + newFriend.age);
System.out.println("This is your Address Book so far: " + addressBook);
}
else if(reply.equals("N")){
System.out.println("Thank you for your time");
}
}
}
如果你需要我在这里使用的 Friend 类,就是这样:
public class Friend
{
public String name;
public int age;
public Friend(String n, int a)
{
name = n;
age = a;
}
}
我很不确定我是否使用“do”或“while”循环或如何使用它。如果您解释了为什么或如何循环在另一个循环上工作,那就太棒了。
谢谢。
编辑:在我发布这个问题之前,我并没有意识到这个社区有多活跃,而且我认为我不会像在这么短的时间。所以,在我看到你的回复之前,我想出了自己的方法来循环它,方法是使用一个看起来像这样的 do-while 循环。
import java.io.*;
import java.util.*;
public class ABook {
public static void main(String args[]) {
LinkedList addressBook = new LinkedList();
Scanner input = new Scanner(System.in);
int n = 0;
do {
System.out.println("Would you like to add a friend? (Say Y or N)");
String reply = input.nextLine();
if (reply.equals("Y")) {
System.out.println("What is the name of your friend?");
String name = input.nextLine();
System.out.println("What is the age of your friend?");
int age = input.nextInt();
Friend newFriend = new Friend(name, age);
addressBook.add("Name: " + newFriend.name + "; " + "Age: " + newFriend.age);
System.out.println("This is your Address Book so far: " + addressBook);
n++;
} else if (reply.equals("N")) {
System.out.println("Thank you for your time");
System.out.println("Would you like to know who is in your Address Book? (Say Y or N)");
String userinput = input.nextLine();
if (reply.equals("Y")) {
System.out.println("This is your Address Book so far: " + addressBook);
System.out.println("Goodbye!");
} else if (reply.equals("N")) {
System.out.println("Okay! Goodbye!");
}
n = 101;
}
} while (n < 100);
}
}
它运作良好,我什至必须在其中添加另一个 if - else 语句。 我现在要做的是按“朋友”的整数/年龄对链表进行排序,所以当我打印链表时,它可以按从最小到最旧的顺序排列。如果有人能指出我正确的方向,那就太棒了!
无论如何,感谢所有来帮助我的人,我希望这可以帮助其他遇到寻找答案的人。
【问题讨论】:
标签: java loops for-loop while-loop linked-list