gpt4 book ai didi

java - 为什么我的子字符串没有添加到我的队列中?

转载 作者:行者123 更新时间:2023-12-02 05:24:52 25 4
gpt4 key购买 nike

我正在开发的程序应该让你输入一个人的性别和姓名,例如:“m john”然后应该将男性和女性分开并分别打印出名字。

我正在比较字符串中的第一个字符,然后使用排队将子字符串添加到男性队列或女性队列,然后我尝试通过打印出列的子字符串来打印每个队列。但我收到一个错误,表明我的队列为空,即使我在 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;
}
}
}

最佳答案

也许这不是唯一的问题,但是

for(int index2 = 0; index2 <= femaleCount; index2++)

应该是

for(int index2 = 0; index2 < femaleCount; index2++)

事实上,最后一次出队会给你 QueueUnderflowException ,因为您试图从仅包含 n 的队列中出列 n+1 个项目。

公环和母环都存在同样的问题。

关于java - 为什么我的子字符串没有添加到我的队列中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26154859/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com