Can't find class in namespace - vb.net

I have created a class, but when I try to access it using
Dim obj As New FabSalesDB.BusinessLayer.DayEnd
the compiler can't find it in FabSalesDB.BusinessLayer but it can find other classes. What could be the reason?
namespace FabSalesDB.BusinessLayer
{
public class DayEnd : BusinessObjectBase
{
public enum DayEndFields
{
date,
CashTaken,
CardsTaken,
CashRegistered,
CardsRegistered,
CashVariance,
CardVariance,
R200,
R100,
R50,
R20,
R10,
R5,
R2,
R1,
c50,
c20,
c10,
c5,
c1
}
DateTime _date;
float _CashTaken;
float _CardsTaken;
float _CashRegistered;
float _CardsRegistered;
float _CashVariance;
float _CardVariance;
int _R200;
int _R100;
int _R50;
int _R20;
int _R10;
int _R5;
int _R2;
int _R1;
int _c50;
int _c20;
int _c10;
int _c5;
int _c1;
public DateTime date
{
get { return _date; }
set
{
if (_date != value)
{
_date = value;
PropertyHasChanged("date");
}
}
}
public float CashTaken
{
get { return _CashTaken; }
set
{
if (_CashTaken != value)
{
_CashTaken = value;
PropertyHasChanged("CashTaken");
}
}
}
public float CardsTaken
{
get { return _CardsTaken; }
set
{
if (_CardsTaken != value)
{
_CardsTaken = value;
PropertyHasChanged("CardsTaken");
}
}
}
public float CashRegistered
{
get { return _CashRegistered; }
set
{
if (_CashRegistered != value)
{
_CashRegistered = value;
PropertyHasChanged("CashRegistered");
}
}
}
public float CardsRegistered
{
get { return _CardsRegistered; }
set
{
if (_CardsRegistered != value)
{
_CashRegistered = value;
PropertyHasChanged("CardsRegistered");
}
}
}
public float CashVariance
{
get { return _CashVariance; }
set
{
if (_CashVariance != value)
{
_CashVariance = value;
PropertyHasChanged("CashVariance");
}
}
}
public float CardVariance
{
get { return _CardVariance; }
set
{
if (_CardVariance != value)
{
_CardVariance = value;
PropertyHasChanged("CardVariance");
}
}
}
public int R200
{
get { return _R200; }
set
{
if (_R200 != value)
{
_R200 = value;
PropertyHasChanged("R200");
}
}
}
public int R100
{
get { return _R100; }
set
{
if (_R100 != value)
{
_R100 = value;
PropertyHasChanged("R100");
}
}
}
public int R50
{
get { return _R50; }
set
{
if (_R50 != value)
{
_R50 = value;
PropertyHasChanged("R50");
}
}
}
public int R20
{
get { return _R20; }
set
{
if (_R20 != value)
{
_R20 = value;
PropertyHasChanged("R20");
}
}
}
public int R10
{
get { return _R10; }
set
{
if (_R10 != value)
{
_R10 = value;
PropertyHasChanged("R10");
}
}
}
public int R5
{
get { return _R5; }
set
{
if (_R5 != value)
{
_R5 = value;
PropertyHasChanged("R5");
}
}
}
public int R2
{
get { return _R2; }
set
{
if (_R2 != value)
{
_R2 = value;
PropertyHasChanged("R2");
}
}
}
public int R1
{
get { return _R1; }
set
{
if (_R1 != value)
{
_R1 = value;
PropertyHasChanged("R1");
}
}
}
public int c50
{
get { return _c50; }
set
{
if (_c50 != value)
{
_c50 = value;
PropertyHasChanged("c50");
}
}
}
public int c20
{
get { return _c20; }
set
{
if (_c20 != value)
{
_c20 = value;
PropertyHasChanged("c20");
}
}
}
public int c10
{
get { return _c10; }
set
{
if (_c10 != value)
{
_c10 = value;
PropertyHasChanged("c10");
}
}
}
public int c1
{
get { return _c1; }
set
{
if (_c1 != value)
{
_c1 = value;
PropertyHasChanged("c1");
}
}
}
public int c5
{
get { return _c5; }
set
{
if (_c5 != value)
{
_c5 = value;
PropertyHasChanged("c5");
}
}
}
}

Your class should have a constructor if you want to use it with Class Var=new Class();
The constructor should be:
public DayEnd ()
{
//
// TODO: Add constructor logic here
//
}

Related

How to put different limit for multi chekbox in recyclerview item

I can choose 2 items from the first group and choose 1 item from the second group.
Now there should be a certain limit for each group and the whole choice as well.
How can I apply it?
#Override
public void onBindViewHolder(#NonNull Holder holder, int position) {
holder.txt_ingredient.setText(ingredients.get(position).getName());
ArrayList<HomeList.Ingredient> sizeArrayList = new ArrayList<>();
sizeArrayList.addAll(ingredients);
for (int i = 0; i < ingredients.get(position).getIngredients().size(); i++) {
indi.add(ingredients.get(position).getIngredients().get(i).getId());
}
for (int i = 0; i < sizeArrayList.get(position).getIngredients().size(); i++) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View rowView = inflater.inflate(R.layout.checkbox_feild, null);
holder.parentLinearSize.addView(rowView, holder.parentLinearSize.getChildCount() - 1);
}
for (int itemPos = 0; itemPos < holder.parentLinearSize.getChildCount(); itemPos++) {
View view1 = holder.parentLinearSize.getChildAt(itemPos);
CheckBox ch = (CheckBox) view1.findViewById(R.id.chkSpe);
TextView cat_value = (TextView) view1.findViewById(R.id.cat_value);
String c = String.valueOf(sizeArrayList.get(position).getIngredients().size());
ch.setText(sizeArrayList.get(position).getIngredients().get(itemPos).getTitle());
ch.setOnCheckedChangeListener(null);
int finalItemPos = itemPos;
ch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
int limit = Integer.parseInt(sizeArrayList.get(position).getSelectionLimit());
int globalInc = 0;
if (globalInc == limit && isChecked) {
ch.setChecked(false);
Toast.makeText(context,
"Limit reached!!!", Toast.LENGTH_SHORT).show();
} else if (isChecked) {
globalInc++;
Toast.makeText(context,
globalInc + " checked!",
Toast.LENGTH_SHORT)
.show();
ch.setSelected(isChecked);
if (ch.isChecked()) {
for (int i = 0; i < ingredients.get(position).getIngredients().size(); i++) {
if (i == finalItemPos) {
ingredients.get(position).getIngredients().get(i).setQty("1");
} else
ingredients.get(position).getIngredients().get(i).setQty("0");
}
ingredients.get(position).setIsOpenSection("1");
onItemCheckListener.onItemCheck(sizeArrayList.get(position).getIngredients(), sizeArrayList.get(position));
Toast.makeText(context, sizeArrayList.get(position).getIngredients().get(finalItemPos).getPrice(), Toast.LENGTH_SHORT).show();
onRecycleItemClickListenerExtra.onItemClickListener(holder, position, "selectExtra", sizeArrayList.get(position).getIngredients().get(finalItemPos).getPrice(), "trextra");
} else {
onItemCheckListener.onItemUncheck(sizeArrayList.get(position).getIngredients().get(position));
onRecycleItemClickListenerExtra.onItemClickListener(holder, position, "DeselectExtra", sizeArrayList.get(position).getIngredients().get(finalItemPos).getPrice(), "trextra");
sizeArrayList.get(position).getIngredients().get(finalItemPos).setQty("0");
}
} else if (!isChecked) {
globalInc--;
}
}
});
cat_value.setText(sizeArrayList.get(position).getIngredients().get(itemPos).getPrice());
holder.maximum_amt.setText(sizeArrayList.get(position).getMaximumAmount());
holder.select_limit.setText(sizeArrayList.get(position).getSelectionLimit());
String count = String.valueOf(getItemCount());
holder.total_itm_count.setText(c);
String eql_les_grt = sizeArrayList.get(position).getEqualGraterLess();
if (eql_les_grt.equalsIgnoreCase("1")) {
if (lan.equals("English")) {
String eql_ls_status = "Greater";
holder.euql_grt_les.setText(eql_ls_status);
}
if (lan.equals("Español")) {
String eql_ls_status = "Máximo";
holder.euql_grt_les.setText(eql_ls_status);
}
}
if (eql_les_grt.equalsIgnoreCase("2")) {
if (lan.equals("English")) {
String eql_ls_status = "Exactly";
holder.euql_grt_les.setText(eql_ls_status);
}
if (lan.equals("Español")) {
String eql_ls_status = "solo";
holder.euql_grt_les.setText(eql_ls_status);
}
}
if (eql_les_grt.equalsIgnoreCase("3")) {
if (lan.equals("English")) {
String eql_ls_status = "Less";
holder.euql_grt_les.setText(eql_ls_status);
}
if (lan.equals("Español")) {
String eql_ls_status = "Mínimo";
holder.euql_grt_les.setText(eql_ls_status);
}
}
holder.img_arrow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
holder.rl_details.setVisibility(View.VISIBLE);
holder.img_dwn_arrow.setVisibility(View.VISIBLE);
holder.img_dwn_arrow.setVisibility(View.VISIBLE);
holder.img_arrow.setVisibility(View.GONE);
holder.parentLinearSize.setVisibility(View.VISIBLE);
}
});
holder.img_dwn_arrow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
holder.rl_details.setVisibility(View.GONE);
holder.img_dwn_arrow.setVisibility(View.GONE);
holder.img_dwn_arrow.setVisibility(View.GONE);
holder.img_arrow.setVisibility(View.VISIBLE);
holder.parentLinearSize.setVisibility(View.GONE);
}
});
}

Can Uncrustify be configured to align braces in one-line functions in header files?

Scenario: C++, a bunch of one-line setters and getters inlined in the header file, as follows:
bool hasVoices(int staffIdx) const { return m_mstaves[staffIdx]->hasVoices(); }
void setHasVoices(int staffIdx, bool v) { return m_mstaves[staffIdx]->setHasVoices(v); }
StaffLines* staffLines(int staffIdx) { return m_mstaves[staffIdx]->lines(); }
Spacer* vspacerDown(int staffIdx) const { return m_mstaves[staffIdx]->vspacerDown(); }
Spacer* vspacerUp(int staffIdx) const { return m_mstaves[staffIdx]->vspacerUp(); }
void setStaffVisible(int staffIdx, bool visible) { m_mstaves[staffIdx]->setVisible(visible); }
void setStaffStemless(int staffIdx, bool stemless) { m_mstaves[staffIdx]->setStemless(stemless); }
bool corrupted(int staffIdx) const { return m_mstaves[staffIdx]->corrupted(); }
void setCorrupted(int staffIdx, bool val) { m_mstaves[staffIdx]->setCorrupted(val); }
MeasureNumber* noText(int staffIdx) const { return m_mstaves[staffIdx]->noText(); }
void setNoText(int staffIdx, MeasureNumber* t) { m_mstaves[staffIdx]->setNoText(t); }
MeasureNumberMode measureNumberMode() const { return m_noMode; }
void setMeasureNumberMode(MeasureNumberMode v) { m_noMode = v; }
Fraction timesig() const { return m_timesig; }
void setTimesig(const Fraction& f) { m_timesig = f; }
bool isIrregular() const { return m_timesig != _len; }
int size() const { return m_segments.size(); }
Segment* first() const { return m_segments.first(); }
Segment* first(SegmentType t) const { return m_segments.first(t); }
Segment* firstEnabled() const { return m_segments.first(ElementFlag::ENABLED); }
Segment* last() const { return m_segments.last(); }
SegmentList& segments() { return m_segments; }
const SegmentList& segments() const { return m_segments; }
void setUserStretch(qreal v) { m_userStretch = v; }
The function bodies are aligned for the sake of readability. The repository I'm contributing to has just begun using Uncrustify and added a test to enforce the code style for new pull requests. Uncrustify as currently configured wants this changed to:
bool hasVoices(int staffIdx) const { return m_mstaves[staffIdx]->hasVoices(); }
void setHasVoices(int staffIdx, bool v) { return m_mstaves[staffIdx]->setHasVoices(v); }
StaffLines* staffLines(int staffIdx) { return m_mstaves[staffIdx]->lines(); }
Spacer* vspacerDown(int staffIdx) const { return m_mstaves[staffIdx]->vspacerDown(); }
Spacer* vspacerUp(int staffIdx) const { return m_mstaves[staffIdx]->vspacerUp(); }
void setStaffVisible(int staffIdx, bool visible) { m_mstaves[staffIdx]->setVisible(visible); }
void setStaffStemless(int staffIdx, bool stemless) { m_mstaves[staffIdx]->setStemless(stemless); }
bool corrupted(int staffIdx) const { return m_mstaves[staffIdx]->corrupted(); }
void setCorrupted(int staffIdx, bool val) { m_mstaves[staffIdx]->setCorrupted(val); }
MeasureNumber* noText(int staffIdx) const { return m_mstaves[staffIdx]->noText(); }
void setNoText(int staffIdx, MeasureNumber* t) { m_mstaves[staffIdx]->setNoText(t); }
MeasureNumberMode measureNumberMode() const { return m_noMode; }
void setMeasureNumberMode(MeasureNumberMode v) { m_noMode = v; }
Fraction timesig() const { return m_timesig; }
void setTimesig(const Fraction& f) { m_timesig = f; }
bool isIrregular() const { return m_timesig != _len; }
int size() const { return m_segments.size(); }
Segment* first() const { return m_segments.first(); }
Segment* first(SegmentType t) const { return m_segments.first(t); }
Segment* firstEnabled() const { return m_segments.first(ElementFlag::ENABLED); }
Segment* last() const { return m_segments.last(); }
SegmentList& segments() { return m_segments; }
const SegmentList& segments() const { return m_segments; }
void setUserStretch(qreal v) { m_userStretch = v; }
Can Uncrustify be configured to produce something more like the first example instead?
You can use:
# Don't split one-line function definitions, as in 'int foo() { return 0; }'.
# might modify nl_func_type_name
nl_func_leave_one_liners = true # true/false
But that won't help you with the spacing for cases where you have a const in your member function. Open up a bug ticket and well see what we can do about that / point you in the directions to create a PR for that.

How to move the snap position from center to left of RecycleView using SnapHelper?

I have an RecycleView that contains ImageViews and my question is how can i move the snap to be on the left side of the RecycleView instead of the center?
When i move the ImageViews they get snapped in the center and I can move them to the left or right inside that "snap window" by overriding the CalculateDistanceToFinalSnap method. I think I would now need to move that "snap window" to the left side of the RecycleView but I don't know how, or maybe there is another way, please help.
Here is a image of my problem, maybe it will help you to understand more clearly:
image
#Jessie Zhang -MSFT's solution works for me. The code was a little oddly formatted and I had some difficulty bringing it over. Here is the same solution (for a horizontal snap only) in Kotlin.
class StartSnapHelper: LinearSnapHelper() {
override fun calculateDistanceToFinalSnap(layoutManager: RecyclerView.LayoutManager, targetView: View): IntArray? {
return if (layoutManager.canScrollHorizontally()) {
val outer = mutableListOf<Int>()
outer.add(distanceToStart(targetView, getHorizontalHelper(layoutManager)))
outer.add(0)
outer.toIntArray()
} else {
super.calculateDistanceToFinalSnap(layoutManager, targetView)
}
}
override fun findSnapView(layoutManager: RecyclerView.LayoutManager?): View? {
return if (layoutManager is LinearLayoutManager) {
if (layoutManager.canScrollHorizontally()) {
getStartView(layoutManager, getHorizontalHelper(layoutManager))
} else {
super.findSnapView(layoutManager)
}
} else {
super.findSnapView(layoutManager)
}
}
private fun distanceToStart(targetView: View, helper: OrientationHelper): Int {
return helper.getDecoratedStart(targetView) - helper.startAfterPadding
}
private fun getStartView(layoutManager: RecyclerView.LayoutManager, orientationHelper: OrientationHelper): View? {
val firstChild = (layoutManager as LinearLayoutManager).findFirstVisibleItemPosition()
val isLastItem = (layoutManager.findLastCompletelyVisibleItemPosition() == layoutManager.itemCount - 1)
if (firstChild == RecyclerView.NO_POSITION || isLastItem) {
return null
}
val child = layoutManager.findViewByPosition(firstChild)
return if (orientationHelper.getDecoratedEnd(child) >= orientationHelper.getDecoratedMeasurement(child) / 2
&& orientationHelper.getDecoratedEnd(child) > 0) {
child;
} else {
if (layoutManager.findFirstCompletelyVisibleItemPosition() == layoutManager.itemCount -1) {
null
} else {
layoutManager.findViewByPosition(firstChild + 1)
}
}
}
private fun getHorizontalHelper(layoutManager: RecyclerView.LayoutManager): OrientationHelper {
return OrientationHelper.createHorizontalHelper(layoutManager)
}
}
I have achieved this function ,we juse need to create a class and extent class LinearSnapHelper and override method CalculateDistanceToFinalSnap and FindSnapView. You can check out the full demo here .
The main code is as follows:
public class StartSnapHelper: LinearSnapHelper
{
private OrientationHelper mVerticalHelper, mHorizontalHelper;
public StartSnapHelper()
{
}
public override void AttachToRecyclerView(RecyclerView recyclerView)
{
base.AttachToRecyclerView(recyclerView);
}
public override int[] CalculateDistanceToFinalSnap(RecyclerView.LayoutManager layoutManager, View targetView)
{
//return base.CalculateDistanceToFinalSnap(layoutManager, targetView);
int[] outer = new int[2];
if (layoutManager.CanScrollHorizontally())
{
outer[0] = distanceToStart(targetView, getHorizontalHelper(layoutManager));
} else {
outer[0] = 0;
}
if (layoutManager.CanScrollVertically()) {
outer[1] = distanceToStart(targetView, getVerticalHelper(layoutManager));
} else {
outer[1] = 0;
}
return outer;
}
private int distanceToStart(View targetView, OrientationHelper helper)
{
return helper.GetDecoratedStart(targetView) - helper.StartAfterPadding;
}
public override View FindSnapView(RecyclerView.LayoutManager layoutManager)
{
if (layoutManager is LinearLayoutManager) {
if (layoutManager.CanScrollHorizontally())
{
return getStartView(layoutManager, getHorizontalHelper(layoutManager));
}
else
{
return getStartView(layoutManager, getVerticalHelper(layoutManager));
}
}
return base.FindSnapView(layoutManager);
}
private View getStartView(RecyclerView.LayoutManager layoutManager,
OrientationHelper helper)
{
if (layoutManager is LinearLayoutManager) {
int firstChild = ((LinearLayoutManager)layoutManager).FindFirstVisibleItemPosition();
bool isLastItem = ((LinearLayoutManager)layoutManager)
.FindLastCompletelyVisibleItemPosition()
== layoutManager.ItemCount - 1;
if (firstChild == RecyclerView.NoPosition || isLastItem)
{
return null;
}
View child = layoutManager.FindViewByPosition(firstChild);
if (helper.GetDecoratedEnd(child) >= helper.GetDecoratedMeasurement(child) / 2
&& helper.GetDecoratedEnd(child) > 0)
{
return child;
}
else
{
if (((LinearLayoutManager)layoutManager).FindLastCompletelyVisibleItemPosition()
== layoutManager.ItemCount - 1)
{
return null;
}
else
{
return layoutManager.FindViewByPosition(firstChild + 1);
}
}
}
return base.FindSnapView(layoutManager);
}
private OrientationHelper getVerticalHelper(RecyclerView.LayoutManager layoutManager)
{
if (mVerticalHelper == null)
{
mVerticalHelper = OrientationHelper.CreateVerticalHelper(layoutManager);
}
return mVerticalHelper;
}
private OrientationHelper getHorizontalHelper(RecyclerView.LayoutManager layoutManager)
{
if (mHorizontalHelper == null)
{
mHorizontalHelper = OrientationHelper.CreateHorizontalHelper(layoutManager);
}
return mHorizontalHelper;
}
}
And use like this:
SnapHelper snapHelperStart = new StartSnapHelper();
snapHelperStart.AttachToRecyclerView(recyclerView);

Class is CLS Compliant to .NET but not in Mono

I had to build my own Version class. In .NET it's CLS Compliant but in Mono its not for some reason. Any ideas why?
[Serializable]
public class Version : ICloneable, IComparable, IComparable<Version>, IEquatable<Version>
{
private int major;
private int minor;
private int revision;
private int build;
protected Version()
{
}
public Version(int major, int minor)
{
Major = major;
Minor = minor;
}
public Version(int major, int minor, int revision, int build) : this(major, minor)
{
Revision = revision;
Build = build;
}
public Version(string version)
{
if (string.IsNullOrWhiteSpace(version))
{
throw new ControlInfluence.Exceptions.ArgumentNullStringException("version");
}
string[] parts = version.Split('.');
if ((parts.Length != 4) && (parts.Length != 2))
{
throw new ArgumentException("'version' must have 2 or 4 numbers separated by '.'.", "version");
}
if (!int.TryParse(parts[0], out major))
{
throw new ArgumentException("'version' must have 2 or 4 numbers separated by '.'.", "version");
}
if (!int.TryParse(parts[1], out minor))
{
throw new ArgumentException("'version' must have 2 or 4 numbers separated by '.'.", "version");
}
if (!int.TryParse(parts[2], out revision))
{
throw new ArgumentException("'version' must have 2 or 4 numbers separated by '.'.", "version");
}
if (!int.TryParse(parts[3], out build))
{
throw new ArgumentException("'version' must have 2 or 4 numbers separated by '.'.", "version");
}
}
public int Major
{
get
{
return major;
}
set
{
major = value;
}
}
public int Minor
{
get
{
return minor;
}
set
{
minor = value;
}
}
public int Build
{
get
{
return build;
}
set
{
build = value;
}
}
public int Revision
{
get
{
return revision;
}
set
{
revision = value;
}
}
public override string ToString()
{
return string.Format(CultureInfo.InvariantCulture, "{0}.{1}.{2}.{3}", Major, Minor, Revision, Build);
}
public static bool operator <(Version left, Version right)
{
if ((left == null) || (right == null))
{
return false;
}
return left.CompareTo(right) < 0;
}
public static bool operator >(Version left, Version right)
{
if ((left == null) || (right == null))
{
return false;
}
return left.CompareTo(right) > 0;
}
#region ICloneable Members
public object Clone()
{
return new Version(Major, Minor, Revision, Build);
}
#endregion
#region IComparable Members
public int CompareTo(object obj)
{
Version other = obj as Version;
if (other == null)
{
return -1;
}
return CompareTo(other);
}
#endregion
#region IComparable<Version> Members
public int CompareTo(Version other)
{
if (other == null)
{
return -1;
}
int compareMajor = Major.CompareTo(other.Major);
if (compareMajor != 0)
{
return compareMajor;
}
int compareMinor = Minor.CompareTo(other.Minor);
if (compareMinor != 0)
{
return compareMinor;
}
int compareRevision = Revision.CompareTo(other.Revision);
if (compareRevision != 0)
{
return compareRevision;
}
return Build.CompareTo(other.Build);
}
#endregion
#region IEquatable<Version> Members
public bool Equals(Version other)
{
return CompareTo(other) == 0;
}
#endregion
public override bool Equals(object obj)
{
Version version = obj as Version;
if (version == null)
{
return false;
}
return Equals(version);
}
public static bool operator ==(Version left, Version right)
{
if (Object.ReferenceEquals(left, null) && Object.ReferenceEquals(right, null))
{
return true;
}
if (Object.ReferenceEquals(left, null) || Object.ReferenceEquals(right, null))
{
return false;
}
return left.Equals(right);
}
public static bool operator !=(Version left, Version right)
{
if ((left == null) || (right == null))
{
return false;
}
return !left.Equals(right);
}
}
The custom exception classes I throw are simply wrappers around ArgumentNullException that "auto fill" the message for me so they aren't adding any types to it really.
If it's CLS compliant in .NET but not on Mono, it is a bug in Mono. Please file a bug in http://bugzilla.xamarin.com

Exporting a non public Type through public API

I am trying to follow Trees tutorial at: http://cslibrary.stanford.edu/110/BinaryTrees.html
Here is the code I have written so far:
package trees.bst;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
/**
*
* #author sachin
*/
public class BinarySearchTree {
Node root = null;
class Node {
Node left = null;
Node right = null;
int data = 0;
public Node(int data) {
this.left = null;
this.right = null;
this.data = data;
}
}
public void insert(int data) {
root = insert(data, root);
}
public boolean lookup(int data) {
return lookup(data, root);
}
public void buildTree(int numNodes) {
for (int i = 0; i < numNodes; i++) {
int num = (int) (Math.random() * 10);
System.out.println("Inserting number:" + num);
insert(num);
}
}
public int size() {
return size(root);
}
public int maxDepth() {
return maxDepth(root);
}
public int minValue() {
return minValue(root);
}
public int maxValue() {
return maxValue(root);
}
public void printTree() { //inorder traversal
System.out.println("inorder traversal:");
printTree(root);
System.out.println("\n--------------");
}
public void printPostorder() { //inorder traversal
System.out.println("printPostorder traversal:");
printPostorder(root);
System.out.println("\n--------------");
}
public int buildTreeFromOutputString(String op) {
root = null;
int i = 0;
StringTokenizer st = new StringTokenizer(op);
while (st.hasMoreTokens()) {
String stNum = st.nextToken();
int num = Integer.parseInt(stNum);
System.out.println("buildTreeFromOutputString: Inserting number:" + num);
insert(num);
i++;
}
return i;
}
public boolean hasPathSum(int pathsum) {
return hasPathSum(pathsum, root);
}
public void mirror() {
mirror(root);
}
public void doubleTree() {
doubleTree(root);
}
public boolean sameTree(BinarySearchTree bst) { //is this tree same as another given tree?
return sameTree(this.root, bst.getRoot());
}
public void printPaths() {
if (root == null) {
System.out.println("print path sum: tree is empty");
}
List pathSoFar = new ArrayList();
printPaths(root, pathSoFar);
}
///-------------------------------------------Public helper functions
public Node getRoot() {
return root;
}
//Exporting a non public Type through public API
///-------------------------------------------Helper Functions
private boolean isLeaf(Node node) {
if (node == null) {
return false;
}
if (node.left == null && node.right == null) {
return true;
}
return false;
}
///-----------------------------------------------------------
private boolean sameTree(Node n1, Node n2) {
if ((n1 == null && n2 == null)) {
return true;
} else {
if ((n1 == null || n2 == null)) {
return false;
} else {
if ((n1.data == n2.data)) {
return (sameTree(n1.left, n2.left) && sameTree(n1.right, n2.right));
}
}
}
return false;
}
private void doubleTree(Node node) {
//create a copy
//bypass the copy to continue looping
if (node == null) {
return;
}
Node copyNode = new Node(node.data);
Node temp = node.left;
node.left = copyNode;
copyNode.left = temp;
doubleTree(copyNode.left);
doubleTree(node.right);
}
private void mirror(Node node) {
if (node == null) {
return;
}
Node temp = node.left;
node.left = node.right;
node.right = temp;
mirror(node.left);
mirror(node.right);
}
private void printPaths(Node node, List pathSoFar) {
if (node == null) {
return;
}
pathSoFar.add(node.data);
if (isLeaf(node)) {
System.out.println("path in tree:" + pathSoFar);
pathSoFar.remove(pathSoFar.lastIndexOf(node.data)); //only the current node, a node.data may be duplicated
return;
} else {
printPaths(node.left, pathSoFar);
printPaths(node.right, pathSoFar);
}
}
private boolean hasPathSum(int pathsum, Node node) {
if (node == null) {
return false;
}
int val = pathsum - node.data;
boolean ret = false;
if (val == 0 && isLeaf(node)) {
ret = true;
} else if (val == 0 && !isLeaf(node)) {
ret = false;
} else if (val != 0 && isLeaf(node)) {
ret = false;
} else if (val != 0 && !isLeaf(node)) {
//recurse further
ret = hasPathSum(val, node.left) || hasPathSum(val, node.right);
}
return ret;
}
private void printPostorder(Node node) { //inorder traversal
if (node == null) {
return;
}
printPostorder(node.left);
printPostorder(node.right);
System.out.print(" " + node.data);
}
private void printTree(Node node) { //inorder traversal
if (node == null) {
return;
}
printTree(node.left);
System.out.print(" " + node.data);
printTree(node.right);
}
private int minValue(Node node) {
if (node == null) {
//error case: this is not supported
return -1;
}
if (node.left == null) {
return node.data;
} else {
return minValue(node.left);
}
}
private int maxValue(Node node) {
if (node == null) {
//error case: this is not supported
return -1;
}
if (node.right == null) {
return node.data;
} else {
return maxValue(node.right);
}
}
private int maxDepth(Node node) {
if (node == null || (node.left == null && node.right == null)) {
return 0;
}
int ldepth = 1 + maxDepth(node.left);
int rdepth = 1 + maxDepth(node.right);
if (ldepth > rdepth) {
return ldepth;
} else {
return rdepth;
}
}
private int size(Node node) {
if (node == null) {
return 0;
}
return 1 + size(node.left) + size(node.right);
}
private Node insert(int data, Node node) {
if (node == null) {
node = new Node(data);
} else if (data <= node.data) {
node.left = insert(data, node.left);
} else {
node.right = insert(data, node.right);
}
//control should never reach here;
return node;
}
private boolean lookup(int data, Node node) {
if (node == null) {
return false;
}
if (node.data == data) {
return true;
}
if (data < node.data) {
return lookup(data, node.left);
} else {
return lookup(data, node.right);
}
}
public static void main(String[] args) {
BinarySearchTree bst = new BinarySearchTree();
int treesize = 5;
bst.buildTree(treesize);
//treesize = bst.buildTreeFromOutputString("4 4 4 6 7");
treesize = bst.buildTreeFromOutputString("3 4 6 3 6");
//treesize = bst.buildTreeFromOutputString("10");
for (int i = 0; i < treesize; i++) {
System.out.println("Searching:" + i + " found:" + bst.lookup(i));
}
System.out.println("tree size:" + bst.size());
System.out.println("maxDepth :" + bst.maxDepth());
System.out.println("minvalue :" + bst.minValue());
System.out.println("maxvalue :" + bst.maxValue());
bst.printTree();
bst.printPostorder();
int pathSum = 10;
System.out.println("hasPathSum " + pathSum + ":" + bst.hasPathSum(pathSum));
pathSum = 6;
System.out.println("hasPathSum " + pathSum + ":" + bst.hasPathSum(pathSum));
pathSum = 19;
System.out.println("hasPathSum " + pathSum + ":" + bst.hasPathSum(pathSum));
bst.printPaths();
bst.printTree();
//bst.mirror();
System.out.println("Tree after mirror function:");
bst.printTree();
//bst.doubleTree();
System.out.println("Tree after double function:");
bst.printTree();
System.out.println("tree size:" + bst.size());
System.out.println("Same tree:" + bst.sameTree(bst));
BinarySearchTree bst2 = new BinarySearchTree();
bst2.buildTree(treesize);
treesize = bst2.buildTreeFromOutputString("3 4 6 3 6");
bst2.printTree();
System.out.println("Same tree:" + bst.sameTree(bst2));
System.out.println("---");
}
}
Now the problem is that netbeans shows Warning: Exporting a non public Type through public API for function getRoot().
I write this function to get root of tree to be used in sameTree() function, to help comparison of "this" with given tree.
Perhaps this is a OOP design issue... How should I restructure the above code that I do not get this warning and what is the concept I am missing here?
The issue here is that some code might call getRoot() but won't be able to use it's return value since you only gave package access to the Node class.
Make Node a top level class with its own file, or at least make it public
I don't really understand why you even created the getRoot() method. As long as you are inside your class you can even access private fields from any other object of the same class.
So you can change
public boolean sameTree(BinarySearchTree bst) { //is this tree same as another given tree?
return sameTree(this.root, bst.getRoot());
}
to
public boolean sameTree(BinarySearchTree bst) { //is this tree same as another given tree?
return sameTree(this.root, bst.root);
}
I would also add a "short path" for the case you pass the same instance to this method:
public boolean sameTree(BinarySearchTree bst) { //is this tree same as another given tree?
if (this == bst) {
return true;
}
return sameTree(this.root, bst.root);
}