Fixed hasNext function