For Loop Returning A Range - for-loop

my BlueJ project has 2 classes: StateProvince and Country. Below is the StateProvince class first, then the Country class where I'm at. I'm stuck on a method: "public int howManyHaveThisPopulation(int min, int max)" which takes the population in millions(e.g. 4, 6) and returns how many StateProvinces there are with populations in that range(e.g. 4-6 million, inclusive). I am not able to set it up and return the right answer. I would like help on how I can do this please. With how my method is now, the error message is that I'm missing a return statement. I know my method isn't correct. I have listed the class below and my progress on the method:
public class StateProvince
{
private String name; //e.g. "British Columbia" or "California"
private String capital; //e.g. "Victoria or "Sacramento"
private int populationInMillions; //e.g. 4 or 38
private final static int DEFAULT_POPULATION_MILLIONS = 4;
private final static String DEFAULT_STATE_PROVINCE = "British Columbia";
private final static String DEFAULT_CAPITAL = "Victoria";
public StateProvince()
{
}
/**
* constructor that takes in all 3 parameters and assigns them if they follow the rules:
* name: must be one of the 50 Unites States or 10 Canadian Provinces
* capital: must be the name of the capital city
* populationInMillions: must be between 0 and 38
*/
public StateProvince(String name, String capital, int populationInMillions)
{
if(isValidPopulation(populationInMillions) && (isValidStateProvince(name) &&
(isValidCapitalCity(capital))))
{
this.populationInMillions = populationInMillions;
this.name = name;
this.capital = capital;
}else
{
this.populationInMillions = DEFAULT_POPULATION_MILLIONS; //
this.name = DEFAULT_STATE_PROVINCE; //"British Columbia"
this.capital = DEFAULT_CAPITAL; //"Victoria"
}
}
//StateProvince p1 = new StateProvince("British Columbia", "Victoria", 5);
private boolean isValidStateProvince(String name)
{
String[] provinces = new String[10];
provinces[0] = "British Columbia";
provinces[1] = "Alberta";
provinces[2] = "Saskatchewan";
provinces[3] = "Manitoba";
provinces[4] = "Ontario";
provinces[5] = "Quebec";
provinces[6] = "PEI";
provinces[7] = "Newfoundland";
provinces[8] = "New Brunswick";
provinces[9] = "Nova Scotia";
for(int index = 0; index < provinces.length; index++)
{
if(provinces[index].equalsIgnoreCase(name))
{
return true;
}
index++;
}
return false;
}
private boolean isValidCapitalCity(String capital)
{
String[] capitals = new String[10];
capitals[0] = "Victoria";
capitals[1] = "Edmonton";
capitals[2] = "Regina";
capitals[3] = "Winnipeg";
capitals[4] = "Toronto";
capitals[5] = "Quebec City";
capitals[6] = "Charlottetown";
capitals[7] = "St. John's";
capitals[8] = "Fredericton";
capitals[9] = "Halifax";
for(int index = 0; index < capitals.length; index++)
{
if(capitals[index].equalsIgnoreCase(capital))
{
return true;
}
index++;
}
return false;
}
private boolean isValidPopulation(int populationInMillions)
{
if(populationInMillions >= 4 || populationInMillions <= 38)
{
return true;
}else
{
return false;
}
}
public void setName()
{
this.name = name;
}
public void setCapital()
{
this.capital = capital;
}
public String getName()
{
return name;
}
public String getCapital()
{
return capital;
}
public int getPopulationInMillions()
{
return populationInMillions;
}
public String getDetails()
{
return ("The capital of " + getName() + " (pop. " + populationInMillions + " million) is " + getCapital());
}
}
public class Country
{
private String country;
private StateProvince[] Canada;
public Country()
{
Canada = new StateProvince[10];
Canada[0] = new StateProvince("British Columbia", "Victoria", 4);
Canada[1] = new StateProvince("Alberta", "Edmonton", 3);
Canada[2] = new StateProvince("Saskatchewan", "Regina", 1);
Canada[3] = new StateProvince("Manitoba", "Winnipeg", 1);
Canada[4] = new StateProvince("Ontario", "Toronto", 13);
Canada[5] = new StateProvince("Quebec", "Quebec City", 8);
Canada[6] = new StateProvince("PEI", "Charlottetown", 0);
Canada[7] = new StateProvince("Newfoundland", "St. John's", 0);
Canada[8] = new StateProvince("New Brunswick", "Fredericton", 1);
Canada[9] = new StateProvince("Nova Scotia", "Halifax", 1);
}
public void displayAllStates()
{
for(int index = 0; index < Canada.length; index++)
{
if(Canada[0] != null)
{
System.out.println(Canada[index].getDetails());
}
index++;
}
}
public void addStateProvince(StateProvince stateProvince)
{
if(Canada != null)
{
for(int i = 0; i < Canada.length; i++)
{
if(Canada[i] == null)
{
Canada[i] = stateProvince;
return;
}
}
}
}
public int howManyHaveThisPopulation(int min, int max)
{
for(int i = 0; i < Canada.length; i++)
{
if(i > min && i < max)
{
return Canada[i].getPopulationInMillions();
}
}
}

Related

How to bind Data Grid in DevExpress Xamarin

Generate headers like so:
public void ClearDataGrid()
{
this.xDataGrid.ItemsSource = null;
//// [Grid Headr 초기 세팅]
//this.xDataGrid.Columns.Clear();
//this.m_Model.MeasureData.Clear();
this.xDataGrid.Columns.Clear();
//// [Wave header 생성]
//Column cNo = GridUtil.Instance.SetColumn(ColumnTypes.Text, "No", "No", new ColumnWidth() { Value = 75 });
//this.xDataGrid.Columns.Add(cNo);
DevExpress.XamarinForms.DataGrid.TextColumn cNo = GridUtil.Instance.SetColumn(ColumnTypes.Text, "No", "No", 75) as DevExpress.XamarinForms.DataGrid.TextColumn;
this.xDataGrid.Columns.Add(cNo);
// [파장값 입력]
for (int i = 0; i < this.m_Model.WaveLength.Count; i++)
{
string strID = string.Empty;
if ((DisplayDataType)Enum.Parse(typeof(DisplayDataType), this.m_Model.DisplayDataUnitType.ToString()) == DisplayDataType.ABS)
{
strID = string.Format("ABS[{0}]", i);
DevExpress.XamarinForms.DataGrid.NumberColumn Col = GridUtil.Instance.SetColumn(
ColumnTypes.Numeric,
strID,
string.Format("A[{0}]", this.m_Model.WaveLength[i]),
150) as DevExpress.XamarinForms.DataGrid.NumberColumn;
this.xDataGrid.Columns.Add(Col);
}
else
{
strID = string.Format("Trans[{0}]", i);
DevExpress.XamarinForms.DataGrid.NumberColumn Col = GridUtil.Instance.SetColumn(
ColumnTypes.Numeric,
strID,
string.Format("T[{0}]", this.m_Model.WaveLength[i]),
150) as DevExpress.XamarinForms.DataGrid.NumberColumn;
this.xDataGrid.Columns.Add(Col);
}
}
DevExpress.XamarinForms.DataGrid.TextColumn cCell = GridUtil.Instance.SetColumn(ColumnTypes.Text, "Cell", "Cell", 75) as DevExpress.XamarinForms.DataGrid.TextColumn;
DevExpress.XamarinForms.DataGrid.DateColumn cDateTime
= GridUtil.Instance.SetColumn(ColumnTypes.Date, "Date", "Date", 150) as DevExpress.XamarinForms.DataGrid.DateColumn;
this.xDataGrid.Columns.Add(cCell);
this.xDataGrid.Columns.Add(cDateTime);
this.xDataGrid.ItemsSource = this.m_Model.MeasureData;
}
When a button is clicked, temporary data is created and added to the bound model.
private async void BtnMeasureClick(object sender, EventArgs e)
{
PhotometricMeasureData data = new PhotometricMeasureData();
++nIndex;
data.No = nIndex.ToString();
data.Cell = string.Format("C[{0}]", nIndex);
data.DateTime = DateTime.Now;
for (int i = 0; i < this.m_Model.WaveLength.Count; i++)
{
data.OriginABS.Add(new Random().Next(-10, 10));
data.OriginTrans.Add(new Random().Next(-10, 10));
data.ABS.Add(data.OriginABS[i] * this.m_Model.Factor);
data.Trans.Add(data.OriginTrans[i] * this.m_Model.Factor);
}
this.m_Model.MeasureData.Add(data);
//this.xDataGrid.Columns[0].Pinned = PinnedPositions.Left;
//this.xDataGrid.ScrollToLastRowByIndex(this.m_Model.MeasureData.Count-1);
}
binding model
public BindingList<PhotometricMeasureData> MeasureData
{
set; get;
} = new BindingList<PhotometricMeasureData>();
public class PhotometricMeasureData : INotifyPropertyChanged
{
//List<float> m_lstABS = new List<float>();
//List<float> m_lstTrans = new List<float>();
public string No { get; set; }
public string Cell { get; set; }
public DateTime DateTime { get; set; }
public BindingList<float> ABS
{
get; set;
} = new BindingList<float>();
public BindingList<float> Trans
{
get; set;
} = new BindingList<float>();
public BindingList<float> OriginABS
{
get; set;
} = new BindingList<float>();
public BindingList<float> OriginTrans
{
get; set;
} = new BindingList<float>();
public void UpdateABSByFactor(float factor)
{
//this.ABS.Clear();
for (int i = 0; i < this.ABS.Count; i++)
{
this.ABS[i] = this.OriginABS[i] * factor;
OnPropertyChanged(string.Format("ABS[{0}]", i));
}
}
public void UpdateTransByFactor(float factor)
{
//this.Trans.Clear();
for (int i = 0; i < this.Trans.Count; i++)
{
this.Trans[i] = this.OriginTrans[i] * factor;
OnPropertyChanged(string.Format("Trans[{0}]", i));
}
}
public event PropertyChangedEventHandler PropertyChanged;
void OnPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
In the current bound model, No and Cell DateTime are binding fine.
But the data created by BindingList is not being bound.
When creating a column in the header, the field name was created and inserted like string.Format("ABS[{0}]", i).
And I tried to bind the data accessed by the index of the ABS list of the binding model.
But it doesn't work as well as I thought.
What am I doing wrong?
enter image description here
enter image description here

android.widget.TimePicker$TimePickerDelegate.getMinute()' on a null object reference

We tried of using TimerPickerDialog with Number Picker in Xamarin android. Since we have time interval of 15mins
In Android 10 - getMinute() is returning Null
var classForid = Java.Lang.Class.ForName("com.android.internal.R$id");
var timePickerField = classForid.GetField("timePicker");
[![timePicker][1]][1] = (TimePicker)FindViewById(timePickerField.GetInt(null));
var field = classForid.GetField("minute");
NumberPicker minuteSpinner = (NumberPicker)timePicker
.FindViewById(field.GetInt(null));
minuteSpinner.MinValue = 0;
minuteSpinner.MaxValue = (60 / TimePickerInterval) - 1;
List<string> displayedValues = new List<string>();
for (int i = 0; i < 60; i += TimePickerInterval)
{
displayedValues.Add(i.ToString());
}
minuteSpinner.SetDisplayedValues(displayedValues.ToArray());
We need to get the Minute picker. Screenshot:
Try to create a custom TimePickerDialog ,here is a simple sample,you could check it:
create CustomTimePickerDialog :
public class CustomTimePickerDialog : TimePickerDialog
{
private int _interval = 1;
public CustomTimePickerDialog(Context context, EventHandler<TimeSetEventArgs> callBack, int hourOfDay, int minute, bool is24HourView, int interval)
: base(context, ThemeHoloLight, (sender, e) =>
{
callBack(sender, new TimeSetEventArgs(e.HourOfDay, e.Minute * interval));
}, hourOfDay, minute / interval, is24HourView)
{
_interval = interval;
FixSpinner(context, hourOfDay, minute, is24HourView);
}
protected CustomTimePickerDialog(IntPtr javaReference, JniHandleOwnership transfer) : base(javaReference, transfer)
{
}
public override void SetView(Android.Views.View view)
{
base.SetView(view);
}
void SetupMinutePicker(Android.Views.View view)
{
var numberPicker = FindMinuteNumberPicker(view as ViewGroup);
if (numberPicker != null)
{
int i = _interval;
List<string> values = new List<string>();
values.Add("00");
while (i < 60)
{
if (i < 10)
values.Add("0" + i);
else
values.Add(i.ToString());
i += _interval;
}
numberPicker.MinValue = 0;
numberPicker.MaxValue = values.Count - 1;
numberPicker.SetDisplayedValues(values.ToArray());
}
}
protected override void OnCreate(Android.OS.Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
GetButton((int)DialogButtonType.Negative).Visibility = Android.Views.ViewStates.Gone;
this.SetCanceledOnTouchOutside(false);
}
private NumberPicker FindMinuteNumberPicker(ViewGroup viewGroup)
{
for (var i = 0; i < viewGroup.ChildCount; i++)
{
var child = viewGroup.GetChildAt(i);
var numberPicker = child as NumberPicker;
if (numberPicker != null)
{
if (numberPicker.MaxValue == 59)
{
return numberPicker;
}
}
var childViewGroup = child as ViewGroup;
if (childViewGroup != null)
{
var childResult = FindMinuteNumberPicker(childViewGroup);
if (childResult != null)
return childResult;
}
}
return null;
}
private void FixSpinner(Context context, int hourOfDay, int minute, bool is24HourView)
{
try
{
// Get the theme's android:timePickerMode
int MODE_SPINNER = 1;
var styleableClass = Java.Lang.Class.ForName("com.android.internal.R$styleable");
var timePickerStyleableField = styleableClass.GetField("TimePicker");
int[] timePickerStyleable = (int[])timePickerStyleableField.Get(null);
var a = context.ObtainStyledAttributes(null, timePickerStyleable, Android.Resource.Attribute.TimePickerStyle, 0);
var timePickerModeStyleableField = styleableClass.GetField("TimePicker_timePickerMode");
int timePickerModeStyleable = timePickerModeStyleableField.GetInt(null);
int mode = a.GetInt(timePickerModeStyleable, MODE_SPINNER);
a.Recycle();
Android.Widget.TimePicker timePicker = (Android.Widget.TimePicker)findField(Java.Lang.Class.FromType(typeof(TimePickerDialog)), Java.Lang.Class.FromType(typeof(Android.Widget.TimePicker)), "mTimePicker").Get(this);
var delegateClass = Java.Lang.Class.ForName("android.widget.TimePicker$TimePickerDelegate");
var delegateField = findField(Java.Lang.Class.FromType(typeof(Android.Widget.TimePicker)), delegateClass, "mDelegate");
var delegatee = delegateField.Get(timePicker);
Java.Lang.Class spinnerDelegateClass;
if (Build.VERSION.SdkInt != BuildVersionCodes.Lollipop)
{
spinnerDelegateClass = Java.Lang.Class.ForName("android.widget.TimePickerSpinnerDelegate");
}
else
{
// TimePickerSpinnerDelegate was initially misnamed TimePickerClockDelegate in API 21!
spinnerDelegateClass = Java.Lang.Class.ForName("android.widget.TimePickerClockDelegate");
}
// In 7.0 Nougat for some reason the timePickerMode is ignored and the delegate is TimePickerClockDelegate
if (delegatee.Class != spinnerDelegateClass)
{
delegateField.Set(timePicker, null); // throw out the TimePickerClockDelegate!
timePicker.RemoveAllViews(); // remove the TimePickerClockDelegate views
var spinnerDelegateConstructor = spinnerDelegateClass.GetConstructors()[0];
spinnerDelegateConstructor.Accessible = true;
// Instantiate a TimePickerSpinnerDelegate
delegatee = spinnerDelegateConstructor.NewInstance(timePicker, context, null, Android.Resource.Attribute.TimePickerStyle, 0);
delegateField.Set(timePicker, delegatee); // set the TimePicker.mDelegate to the spinner delegate
// Set up the TimePicker again, with the TimePickerSpinnerDelegate
timePicker.SetIs24HourView(Java.Lang.Boolean.ValueOf(is24HourView));
timePicker.Hour = hourOfDay;
timePicker.Minute = minute;
timePicker.SetOnTimeChangedListener(this);
}
// set interval
SetupMinutePicker(timePicker);
}
catch (Exception e)
{
throw new Java.Lang.RuntimeException(e.ToString());
}
}
private static Java.Lang.Reflect.Field findField(Java.Lang.Class objectClass, Java.Lang.Class fieldClass, String expectedName)
{
try
{
var field = objectClass.GetDeclaredField(expectedName);
field.Accessible = true;
return field;
}
catch (Java.Lang.NoSuchFieldException e) { } // ignore
// search for it if it wasn't found under the expected ivar name
foreach (var searchField in objectClass.GetDeclaredFields())
{
if (Java.Lang.Class.FromType(searchField.GetType()) == fieldClass)
{
searchField.Accessible = true;
return searchField;
}
}
return null;
}
}
call like this:
CustomTimePickerDialog timePickerDlg = new CustomTimePickerDialog(this, new EventHandler<TimePickerDialog.TimeSetEventArgs>((o,e)=> { }),
hourOfDay, minute, true,15);// the 15 is the minute interval
timePickerDlg.Show();

How can I make my PokerHand class randomly deal a thousand hands?

public class PokerHand
{
// ArrayList for cards
private ArrayList<Card> cards;
/**
* Constructor for class Pokerhand
*/
public PokerHand()
{
cards = new ArrayList<Card>(); // arrayList of cards
}
/**
* Add cards to list
*/
public void addCard(Card card1, Card card2, Card card3)
{
cards.add(card1);
cards.add(card2);
cards.add(card3);
}
}
This is my Card Class
public class Card()
{
private int value;
private int suit;
private static String[] suits = { "hearts", "spades", "diamonds", "clubs" };
private static String[] values = { "Ace", "2", "3", "4", "5", "6", "7",
"8", "9", "10", "Jack", "Queen", "King" };
public static String valueAsString( int value ) {
return values[value];
}
Card(int suit, int rank)
{
this.value=value;
this.suit=suit;
}
public String toString()
{
return values[value] + " of " + suits[suit];
}
public int getValue() {
return value;
}
public int getSuit() {
return suit;
}
}
How can I deal a 1000 three card hands? I am stuck on how a variety of things, including what additional methods I need. How can I construct a deal method and how can I make the deal method dish out a thousand random hands while shuffling every time a hand is dealt?
All of these are implementations are based on code from my card library.
Shuffle
public Card[] shuffle(Card[] deck) {
Random gen = new Random();
boolean[] added = new boolean[deck.length];
int positionToAdd = gen.nextInt(deck.length);
Card[] newDeck = new Card[deck.length];
for (int i = 0; i < deck.length; i++) {
while (newDeck[i] == null) {
if (!added[positionToAdd]) {
newDeck[i] = deck[positionToAdd];
positionToAdd = gen.nextInt(deck.length);
added[i] = true;
} else {
positionToAdd = gen.nextInt(deck.length);
}
}
}
return newDeck;
}
Implementation
ArrayList<Card> dealFrom = new ArrayList<Card>();
PokerHand[] hands = new PokerHand[1000];
/*Populate the "dealFrom" yourself here*/
dealFrom = Array.asList(shuffle(dealFrom.toArray()));
for (int i = 0; i < 3000; i += 3) {
//Write your deal method here
hands[i] = new PokerHand(dealFrom[i], dealFrom[i + 1], dealFrom[i + 2]);
}
Hope this helps.

Generate list from treeitem using c#

we have a list of the class
public class DummyClass
{
public string Text { get; set; }
public int LevelNo { get; set; }
public List<DummyClass> Children { get; set; }
}
we want to add this list to another list with class.
public class FragmentLevel
{
public int currentLevelNo { get; set; }
public int ParentLevelNo { get; set; }
public string Text { get; set; }
}
we need the result like
var list = new List<FragmentLevel>
{
new FragmentLevel{ id = 1, text = "Root" },
new FragmentLevel{ id = 2, parent= 1, text = "Node-1.1" },
new FragmentLevel{ id = 3, parent= 2, text = "Node-1.1.1" }
};
For getting result we are doing like
for (int i = 0; i < DummyClassList.Count; i++)
{
list.Add(new FragmentLevel
{
currentLevelNo = DummyClassList[i].LevelNo,
Text = DummyClassList[i].Text,
});
do
{
for (int j = 0; j < DummyClassList[i].Children.Count; j++)
{
list1.Add(new FragmentLevel
{
LevelNo = DummyClassList[i].Children[j].LevelNo,
Text = DummyClassList[i].Children[j].Text,
});
}
} while (DummyClassList[i].Children[i].Children != null);
}
But this will give wrong result. How we can get the result?
Try this way of filling the fragments recursively,
private static void FillFragments(List<DummyClass> DummyClassList, List<FragmentLevel> list)
{
for (int i = 0; i < DummyClassList.Count; i++)
{
list.Add(new FragmentLevel
{
currentLevelNo = DummyClassList[i].LevelNo,
Text = DummyClassList[i].Text,
});
if (DummyClassList[i].Children != null && DummyClassList[i].Children.Count > 0)
{
FillFragments(DummyClassList[i].Children, list);
}
}
}
and the main method would look like this
static void Main(string[] args)
{
var DummyClassList = new List<DummyClass>
{
new DummyClass
{
Children = new List<DummyClass>
{
new DummyClass{
Children = null,
LevelNo=2,
Text = "two"
}
},
LevelNo = 1,
Text = "one"
}
};
var list = new List<FragmentLevel>();
FillFragments(DummyClassList, list);
}

Guessing Game Binary Tree Java

I'm making a program in java that essentially knows a variety of ocean animals, asks the user to think of an animal, and then asks the user questions until it is ready to make a guess. I used a binary tree to do this. here is my code as of right now:
import java.util.Scanner;
public class TwentyQuestions
{
private static Scanner stdin = new Scanner(System.in);
public static void main(String[ ] args)
{
BTNode<String> root;
instruct( );
root = beginningTree( );
do
play(root);
while (query("Shall we play again?"));
System.out.println("Thanks for teaching me a thing or two.");
System.out.println ("Here is the tree:");
root.print(1);
}
public static void instruct( )
{
System.out.println("Please think of an ocean animal.");
System.out.println("I will ask some yes/no questions to try to figure out which animal you're thinking of.");
}
public static void play(BTNode<String> current)
{
while (!current.isLeaf( ))
{
if (query(current.getData( )))
current = current.getLeft( );
else
current = current.getRight( );
}
System.out.print("My guess is " + current.getData( ) + ". ");
if (!query("Am I right?"))
learn(current);
else
System.out.println("I knew it all along!");
}
public static BTNode<String> beginningTree( )
{
BTNode<String> root;
BTNode<String> child;
BTNode<String> child1;
BTNode<String> child2;
BTNode<String> child3;
BTNode<String> child4;
BTNode<String> child5;
BTNode<String> child6;
BTNode<String> child7;
BTNode<String> child8;
BTNode<String> child9;
BTNode<String> child10;
BTNode<String> child11;
BTNode<String> child12;
BTNode<String> child13;
BTNode<String> child14;
final String ROOT_QUESTION = "Is it a mammal?";
final String LEFT_QUESTION = "Is it able to move on land?";
final String LEFT_QUESTION2 = "Is it a solitary animal?";
final String RIGHT_QUESTION2 = "Is it larger than a truck?";
final String RIGHT_QUESTION3 = "Does it have tusks?";
final String RIGHT_QUESTION = "Does it have any limbs/tentacles?";
final String LEFT_QUESTION4 = "Does it have more than four limbs/tentacles?";
final String LEFT_QUESTION5 = "Does it have an exoskeleton?";
final String LEFT_QUESTION6 = "Does it have claws?";
final String LEFT_QUESTION7 = "Does it have a long tail?";
final String RIGHT_QUESTION7 = "Does it have 8 arms?";
final String RIGHT_QUESTION5 = "Does it have a shell?";
final String RIGHT_QUESTION4 = "Can it sting?";
final String LEFT_QUESTION8 = "Is it long and snakelike?";
final String RIGHT_QUESTION8 = "Is it generally smaller than a car?";
final String ANIMAL1 = "Seal";
final String ANIMAL2 = "Sea Lion";
final String ANIMAL3 = "Walrus";
final String ANIMAL4 = "Whale";
final String ANIMAL5 = "Dolphin";
final String ANIMAL6 = "Shrimp";
final String ANIMAL7 = "Lobster";
final String ANIMAL8 = "Crab";
final String ANIMAL9 = "Jellyfish";
final String ANIMAL10 = "Octopus";
final String ANIMAL11 = "Squid";
final String ANIMAL12 = "Turtle";
final String ANIMAL13 = "Alligator";
final String ANIMAL14 = "Eel";
final String ANIMAL15 = "Stingray";
final String ANIMAL16 = "Shark";
final String ANIMAL17 = "Fish";
// Create the root node with the question “Are you a mammal?”
root = new BTNode<String>(ROOT_QUESTION, null, null);
child = new BTNode<String>(LEFT_QUESTION, child2, child14);
root.setLeft(child);
child2 = new BTNode<String>(LEFT_QUESTION2,null,child3);
child2.setLeft(new BTNode<String>(ANIMAL1, null, null));
child.setLeft(child2);
child14 = new BTNode<String>(RIGHT_QUESTION2,null,null);
child14.setLeft(new BTNode<String>(ANIMAL4,null,null));
child14.setRight(new BTNode<String>(ANIMAL5,null,null));
child.setRight(child14);
child3 = new BTNode<String>(RIGHT_QUESTION3, null, null);
child3.setLeft(new BTNode<String>(ANIMAL3, null, null));
child3.setRight(new BTNode<String>(ANIMAL2, null, null));
child.setRight(child3);
child1 = new BTNode<String>(RIGHT_QUESTION, child4, child8);
root.setRight(child1);
child4 = new BTNode<String>(LEFT_QUESTION4,child5,child10);
child1.setLeft(child4);
child5 = new BTNode<String>(LEFT_QUESTION5,child6,child8);
child4.setLeft(child5);
child6 = new BTNode<String>(LEFT_QUESTION6,child7, null);
child6.setRight(new BTNode<String>(ANIMAL6,null,null));
child5.setLeft(child6);
child7 = new BTNode<String>(LEFT_QUESTION7, null, null);
child7.setLeft(new BTNode<String>(ANIMAL7,null,null));
child7.setRight(new BTNode<String>(ANIMAL8,null,null));
child6.setLeft(child7);
child8 = new BTNode<String>(RIGHT_QUESTION4,null,child9);
child8.setLeft(new BTNode<String>(ANIMAL9,null,null));
child5.setRight(child8);
child9 = new BTNode<String>(RIGHT_QUESTION7,null,null);
child9.setLeft(new BTNode<String>(ANIMAL10,null,null));
child9.setRight(new BTNode<String>(ANIMAL11,null,null));
child8.setRight(child9);
child10 = new BTNode<String>(RIGHT_QUESTION5,null,null);
child10.setLeft(new BTNode<String>(ANIMAL12,null,null));
child10.setRight(new BTNode<String>(ANIMAL13,null,null));
child4.setRight(child10);
child11 = new BTNode<String>(RIGHT_QUESTION4,child12,child13);
child1.setRight(child11);
child12 = new BTNode<String>(LEFT_QUESTION8,null,null);
child12.setLeft(new BTNode<String>(ANIMAL14,null,null));
child12.setRight(new BTNode<String>(ANIMAL15,null,null));
child11.setLeft(child12);
child13 = new BTNode<String>(RIGHT_QUESTION8,null,null);
child13.setLeft(new BTNode<String>(ANIMAL17,null,null));
child13.setRight(new BTNode<String>(ANIMAL16,null,null));
child11.setRight(child13);
return root;
}
public static void learn(BTNode<String> current)
{
String guessAnimal; // The animal that was just guessed
String correctAnimal; // The animal that the user was thinking of
String newQuestion; // A question to distinguish the two animals
// Set Strings for the guessed animal, correct animal and a new question.
guessAnimal = current.getData( );
System.out.println("I give up. What are you? ");
correctAnimal = stdin.nextLine( );
System.out.println("Please type a yes/no question that will distinguish a");
System.out.println(correctAnimal + " from a " + guessAnimal + ".");
newQuestion = stdin.nextLine( );
// Put the new question in the current node, and add two new children.
current.setData(newQuestion);
System.out.println("As a " + correctAnimal + ", " + newQuestion);
if (query("Please answer"))
{
current.setLeft(new BTNode<String>(correctAnimal, null, null));
current.setRight(new BTNode<String>(guessAnimal, null, null));
}
else
{
current.setLeft(new BTNode<String>(guessAnimal, null, null));
current.setRight(new BTNode<String>(correctAnimal, null, null));
}
}
public static boolean query(String prompt)
{
String answer;
System.out.print(prompt + " [Y or N]: ");
answer = stdin.nextLine( ).toUpperCase( );
while (!answer.startsWith("Y") && !answer.startsWith("N"))
{
System.out.print("Invalid response. Please type Y or N: ");
answer = stdin.nextLine( ).toUpperCase( );
}
return answer.startsWith("Y");
}
}
The error that keeps coming up is that the "variable child(+whatever number) may have not been inititalized." how do I fix this?
Oh, and here is the code for the BTNode:
public class BTNode<E>
{
private E data;
private BTNode<E> left, right;
public BTNode(E initialData, BTNode<E> initialLeft, BTNode<E> initialRight)
{
data = initialData;
left = initialLeft;
right = initialRight;
}
public E getData( )
{
return data;
}
public BTNode<E> getLeft( )
{
return left;
}
public E getLeftmostData( )
{
if (left == null)
return data;
else
return left.getLeftmostData( );
}
public BTNode<E> getRight( )
{
return right;
}
public E getRightmostData( )
{
if (left == null)
return data;
else
return left.getRightmostData( );
}
public void inorderPrint( )
{
if (left != null)
left.inorderPrint( );
System.out.println(data);
if (right != null)
right.inorderPrint( );
}
public boolean isLeaf( )
{
return (left == null) && (right == null);
}
public void preorderPrint( )
{
System.out.println(data);
if (left != null)
left.preorderPrint( );
if (right != null)
right.preorderPrint( );
}
public void postorderPrint( )
{
if (left != null)
left.postorderPrint( );
if (right != null)
right.postorderPrint( );
System.out.println(data);
}
public void print(int depth)
{
int i;
// Print the indentation and the data from the current node:
for (i = 1; i <= depth; i++)
System.out.print(" ");
System.out.println(data);
if (left != null)
left.print(depth+1);
else if (right != null)
{
for (i = 1; i <= depth+1; i++)
System.out.print(" ");
System.out.println("--");
}
if (right != null)
right.print(depth+1);
else if (left != null)
{
for (i = 1; i <= depth+1; i++)
System.out.print(" ");
System.out.println("--");
}
}
public BTNode<E> removeLeftmost( )
{
if (left == null)
return right;
else
{
left = left.removeLeftmost( );
return this;
}
}
public BTNode<E> removeRightmost( )
{
if (right == null)
return left;
else
{
right = right.removeRightmost( );
return this;
}
}
public void setData(E newData)
{
data = newData;
}
public void setLeft(BTNode<E> newLeft)
{
left = newLeft;
}
public void setRight(BTNode<E> newRight)
{
right = newRight;
}
public static <E> BTNode<E> treeCopy(BTNode<E> source)
{
BTNode<E> leftCopy, rightCopy;
if (source == null)
return null;
else
{
leftCopy = treeCopy(source.left);
rightCopy = treeCopy(source.right);
return new BTNode<E>(source.data, leftCopy, rightCopy);
}
}
public static <E> long treeSize(BTNode<E> root)
{
if (root == null)
return 0;
else
return 1 + treeSize(root.left) + treeSize(root.right);
}
}
When you declare your variables, make sure you also initialize them before using them. That is, instead of writing
BTNode<String> root;
BTNode<String> child;
BTNode<String> child1;
...
write
BTNode<String> root = null;
BTNode<String> child = null;
...
This is because when you later go on and write the statement
child = new BTNode<String>(LEFT_QUESTION, child2, child14);
child2 and child14 would have been initialized (Whereas in your case, they have only been declared, not initialized)

Resources