0
我正在工作的程序應該輸入一個人的性別和姓名,例如:「m john」 然後,它應該分開男性和女性,分別打印出名稱。爲什麼我的子串沒有被添加到我的隊列中?
我有比較字符串中的第一個字符,然後使用enqueue將一個子字符串添加到男性隊列或女性隊列,然後我試圖通過打印出隊的子字符串打印每個隊列。但我得到一個錯誤,即使我在for循環中添加了字符串,我的隊列仍然是空的。
public class GenderSorter
{
public static void main(String[] args)
{
int numElements;
int maleCount = 0;
int femaleCount = 0;
Scanner keyboard = new Scanner(System.in);
System.out.println("How many people are you adding: ");
numElements = keyboard.nextInt();
keyboard.nextLine();
ArrayBndQueue male = new ArrayBndQueue<>();
ArrayBndQueue female = new ArrayBndQueue<>();
for(int index = 1; index <= numElements; index++)
{
/*
System.out.println("Enter a gender and name (ex: f jenny)");
String name = keyboard.nextLine();
System.out.println(name);
*/
System.out.println("Enter a gender and name (ex: f jenny)");
String name = keyboard.nextLine();
char character = name.charAt(0);
if(character == 'f')
{
female.enqueue(name.substring(2));
femaleCount++;
}
else
{
male.enqueue(name.substring(2));
maleCount++;
}
}
System.out.println("Females: " + "\n");
for(int index2 = 0; index2 <= femaleCount; index2++)
{
System.out.print(female.dequeue());
}
System.out.println("Males: " + "\n");
for(int index3 = 0; index3 <= maleCount; index3++)
{
System.out.print(male.dequeue());
}
}
}
這裏是我的ArrayBndQueue:
public class ArrayBndQueue<T> implements BoundedQueueInterface<T>
{
protected final int DEFCAP = 100;
protected T[] queue;
protected int numElements = 0;
protected int front = 0;
protected int rear;
public ArrayBndQueue()
{
queue = (T[]) new Object[DEFCAP];
rear = DEFCAP -1;
}
public ArrayBndQueue(int maxSize)
{
queue = (T[]) new Object[maxSize];
rear = maxSize -1;
}
public void enqueue(T element)
{
if(isFull())
{
throw new QueueOverflowException("Enqueue " + "attempted on full queue");
}
else
{
rear = (rear + 1) % queue.length;
queue[rear] = element;
numElements++;
}
}
public boolean isFull()
{
return (numElements == queue.length);
}
public boolean isEmpty()
{
return (numElements == 0);
}
public T dequeue()
{
if(isEmpty())
{
throw new QueueUnderflowException("Dequeue" +
" attempted on empty queue!");
}
else
{
T toReturn = queue[front];
queue[front] = null;
front = (front + 1) % queue.length;
numElements--;
return toReturn;
}
}
}