我需要获取用户对我的“MailCostumer”类的输入。 如您所见,有3种类型:String,int和boolean。
这是班级:
class MailCostumer {
private String name;
private int id;
private String address;
private boolean isPack;
public MailCostumer(String name, int id, String address, boolean isPack) {
this.name=name;
this.id=id;
this.address=address;
this.isPack=isPack;
}
/*in the rest of the class there are the set and get methods
for class fields, if you need to see them, I will post them.*/
我的ArrayList在“Queue”类中,如下所示:
import java.util.ArrayList;
public class Queue
{
private ArrayList<MailCostumer> waiting = new ArrayList<MailCostumer>();
private Boolean isEmpty;
public Queue ()
{
this.waiting = new ArrayList<MailCostumer>();
this.isEmpty=true;
}
public void addClient(MailCostumer MC)
{
this.waiting.add(MC);
this.isEmpty=false;
}
public void delClient(MailCostumer MC)
{
if(waiting.size()!=0)
{
this.waiting.remove(0);
if(waiting.size()==0)
{
this.isEmpty=true;
}
}
}
这是主要方法的主要类:
import java.util.Scanner;
public class Costumer
{
public static void main(String[] args)
{
MailCostumer c1 = new MailCostumer("gabriel", 1234, "ashqelon", true);
MailCostumer c2 = new MailCostumer("tal", 1235, "ashdod", true);
Queue q1 = new Queue();
Scanner scan = new Scanner(System.in);
for(int i=0;i<5;i++)
{
c1.setName(scan.nextLine());
}
q1.addClient(c1);
q1.addClient(c2);
System.out.println(q1.waiting.get(1).getName());
}
}
我的问题是,如何从用户那里获得有关不同类型数据的输入并将其存储在我的“等待”ArrayList中,作为“MailCostumer”的对象? 我只需要将isPack == true的那些添加到队列中。 我试图从“主要”的方法做到这一点,但没有运气。 'c1和c2'我有构建,我需要用户输入这些信息。
答案 0 :(得分:0)
您可以让用户输入一行:
gabriel 1234 ashqelon true
并像这样编写你的for循环(注意额外的hasNextLine
条件)
这将检查用户是否键入了4个空格分隔的单词,最后一个单词是"true"
。在这种情况下,它会将新对象附加到c1
队列。
for(int i = 0; i < 5 && scan.hasNextLine(); i++) {
String line = scan.nextLine();
String[] data = line.split(" ");
if (data.length() == 4 && "true".equals(data[3])) {
q1.addClient(new MailCostumer(
data[0],
Integer.parseInt(data[1]),
data[2],
true
);
}
}
第三个选项在MailCostumer
中创建一个以行为参数的静态构造方法。这是一个很好的设计,因为生成MailCostumer
对象的特定代码应打包在类中而不是main
中:
public static MailCostumer valueOf(String line) {
String[] data = line.split(" ");
if (data.length() == 4 && "true".equals(data[3])) {
return new MailCostumer(
data[0],
Integer.parseInt(data[1]),
data[2],
true
);
}
return null;
}
for循环看起来非常精简
for(int i = 0; i < 5 && scan.hasNextLine(); i++) {
String line = scan.nextLine();
MailCostumer c = MailCostumer.valueOf(line);
if (c != null)
q1.addClient(c);
}