Guessing Game Binary Tree Java - binary-tree

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)

Related

Are there any Dart resources that would split a command-line String into a List<String> of arguments?

Are there any Dart resources that would split a command-line String into a List<String> of arguments?
ArgsParser takes a List<String> of already split arguments usually from main(List<String>).
To answer my own question,
I've converted a Java function I liked into a Dart Converter<String, List<String>) class:
import 'dart:convert';
/// Splits a `String` into a list of command-line argument parts.
/// e.g. "command -p param" -> ["command", "-p", "param"]
///
class CommandlineConverter extends Converter<String, List<String>>
{
#override
List<String> convert(String input)
{
if (input == null || input.isEmpty)
{
//no command? no string
return [];
}
final List<String> result = new List<String>();
var current = "";
String inQuote;
bool lastTokenHasBeenQuoted = false;
for (int index = 0; index < input.length; index++)
{
final token = input[index];
if (inQuote != null)
{
if (token == inQuote)
{
lastTokenHasBeenQuoted = true;
inQuote = null;
}
else
{
current += token;
}
}
else
{
switch (token)
{
case "'": // '
case '"': // ""
inQuote = token;
continue;
case " ": // space
if (lastTokenHasBeenQuoted || current.isNotEmpty)
{
result.add(current);
current = "";
}
break;
default:
current += token;
lastTokenHasBeenQuoted = false;
}
}
}
if (lastTokenHasBeenQuoted || current.isNotEmpty)
{
result.add(current);
}
if (inQuote != null)
{
throw new Exception("Unbalanced quote $inQuote in input:\n$input");
}
return result;
}
}

how to exclude checking words in quotations using java

It's the first time I'm doing this so I didn't want to be lengthy. I'm building a cross reference from reading a java program. I'm to exclude java keywords, commented words and words in quotations. I got through with excluding the java keywords and the commented words but I'm having problems excluding those in quotes.
public class CrossReference {
static Scanner in;
static PrintWriter out;
static int currentLine = 0;
public static void main(String[] args) throws IOException {
in = new Scanner (new FileReader("keywords.txt"));
out = new PrintWriter (new FileWriter("crossreference.out"));
LinkedList keywords = new LinkedList();
while (in.hasNextLine()) {
String word = in.nextLine();
keywords.addTail(new NodeData(word));
}
in = new Scanner (new FileReader("program.txt"));
BinaryTree bst = new BinaryTree();
while(in.hasNextLine()){
String line = in.nextLine();
out.printf("%3d. %s\n", ++currentLine,line);
getWordsOnLine(line,bst,keywords);
}
out.printf("\nWords LineNumber\n\n");
bst.inOrder();
out.close();
}
public static void getWordsOnLine(String inputLine, BinaryTree bst, LinkedList keywords){
Scanner inLine = new Scanner(inputLine);
inLine.useDelimiter("[^a-zA-Z//\"*]+");
boolean b = true;
while(inLine.hasNext() && b){
String word = inLine.next().toLowerCase();
if (word.contains("/") || word.contains("\"") || word.contains("*")) {
b = false;
} //this works for the commented words but not so well for the ones in quotes as it also excludes words after those in quotes
else {
boolean key = false;
Node curr = keywords.head;
while (curr != null) {
if (curr.data.str.equals(word)) key = true;
curr = curr.next;
}
if (key == false) {
TreeNode node = bst.findOrInsert(new TreeNodeData(word));
ListNode p = new ListNode(currentLine);
p.next = node.data.firstLine;
node.data.firstLine = p;
}
}
}
}
}
Split your string by space into an array.
Iterate through the array, checking which elements start with quotes and are words
Sum it
So the code would look like:
public class HelloWorld
{
public static void main(String[] args)
{
String a = "COPY PASTE ORIGINAL HERE";
String[] arr = a.split(" ");
int count = 0;
for(String each: arr){
if(each.charAt(0) != '\"' && each.charAt(0) < '0' || each.charAt(0) > '9'){
count++;
}
}
System.out.println("words="+count);
}
}

For Loop Returning A Range

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();
}
}
}

TableView, managing look of particular cells

I got a method which evaluates whats in the string with what was set by user in TableView cells. (string have values like "343288709789" and each cell contains null or single digit number).
It works, however now I would like TableView to highlight(change background or text color) certain cells where user set wrong value. How can I achive this?
PS. Ive read similiar questions to this but I dont think I can achieve this in TableCell class implementation, because cells should change color only after uses press "Check" option.
private void compareAndEvaluate(String source, NewTableView newTableView){
ObservableList<MyData> data = newTableView.getData();
source = source.replaceAll("\\D+","");
System.out.println("data size: " +data.size() + "\n\n" + source);
int numOfValid = 0,
numOfInvalid = 0;
ObservableList<ObjectProperty<Integer>> rowData;
for(int i=0, n=0; i < data.size(); i++){ //rows(Y)
rowData = data.get(i).returnCellsData();
for(int j = 1; j < rowData.size(); ++j, ++n){ //columns(X)
Integer iNext = Integer.valueOf(String.valueOf(source.charAt(n)));
if( iNext == rowData.get(j).get() )
++numOfValid;
else
++numOfInvalid;
}
}
Dialogs.create().title("Results").masthead(null).message("Correct: " + numOfValid + ", Invalid: " + numOfInvalid).showInformation();
}
If that helps, here is implementation of TableCell used by TableView:
public class EditingCellNumbers extends TableCell<MyData, Integer>{
private TextField textField;
private TableView<MyData> parentTableView;
public EditingCellNumbers(TableView<MyData> parent) {
this.parentTableView = parent;
}
#Override
public void startEdit(){
if (!isEmpty()) {
super.startEdit();
createTextField();
setText(null);
setGraphic(textField);
textField.selectAll();
textField.requestFocus();
}
}
#Override
public void cancelEdit() {
super.cancelEdit();
if(getItem() != null){
setText(String.valueOf(getItem()));
}else{
setText(null);
commitEdit(null);
}
setGraphic(null);
}
#Override
public void updateItem(Integer item, boolean empty) {
super.updateItem(item, empty);
if (empty) {
setText(null);
setGraphic(null);
} else {
if (isEditing()) {
if (textField != null) {
textField.setText(getString());
}
setText(null);
setGraphic(textField);
} else {
setText(getString());
setGraphic(null);
if(getTableColumn().getText() == "#"){
setStyle("-fx-font-weight: bold;"
+ "-fx-background-color: linear-gradient( from -100.0% 150.0% to 120.0% 100.0%, rgb(128,128,128) 0.0, rgb(255,255,255) 100.0);");
}else{
if(getItem() == null)
setStyle("-fx-border-color: lavender; -fx-border-width: 0 1 0 0;");
else
setStyle("-fx-border-color: palegreen; -fx-border-width: 0 1 1 0;");
}
}
}
}
private void createTextField() {
textField = new TextField(getString());
textField.setStyle("-fx-background-color: ivory; -fx-border-color: red;");
textField.setMinWidth(this.getWidth() - this.getGraphicTextGap()* 2);
textField.focusedProperty().addListener(
(ObservableValue<? extends Boolean> arg0, Boolean arg1, Boolean arg2) -> {
if (!arg2) {
if(getItem() != null){
try{
commitEdit(Integer.valueOf(textField.getText()));
}catch(NumberFormatException f){
commitEdit(null);
}
}else
commitEdit(null);
}
});
textField.setOnKeyReleased(new EventHandler<KeyEvent>() {
#Override
public void handle(KeyEvent event) {
if(event.getCode() == KeyCode.BACK_SPACE){
if(getItem() != null){
numberOfEmptyCells.set(numberOfEmptyCells.get() + 1);
numberOfFilledCells.set(numberOfFilledCells.get() - 1);
}
commitEdit(null);
}else{
try{
int i = Integer.valueOf(textField.getText());
//digit given...
if( (i>=0) && (i<10) ){//making sure cell is filled with just one digit
if(getItem() == null){
numberOfEmptyCells.set(numberOfEmptyCells.get() - 1);
numberOfFilledCells.set(numberOfFilledCells.get() + 1);
}
commitEdit(Integer.valueOf(textField.getText()));
int selectedColumn = parentTableView.getSelectionModel().getSelectedCells().get(0).getColumn(); // gets the number of selected column
int selectedRow = parentTableView.getSelectionModel().getSelectedCells().get(0).getRow();
//moving to another cell editing
if(selectedColumn < numberOfColumns-1){
parentTableView.getSelectionModel().selectNext();
parentTableView.edit(selectedRow, parentTableView.getColumns().get(selectedColumn+1));
}else{
parentTableView.getSelectionModel().select(selectedRow+1, parentTableView.getColumns().get(1));
parentTableView.edit(selectedRow+1, parentTableView.getColumns().get(1));
}
}else
textField.clear();
}catch(NumberFormatException e){
textField.clear();
}
}
}
});
}
private String getString() {
return getItem() == null ? "" : getItem().toString();
}
}
}
Instead of making your columns in your data model Integer, make them some kind of an object that stores both the integer and the evaluation result. Use the evaluation result to determine the colour of the cell in your customized TableCell.

Camera Problems

I have run into a few problems when trying to get the camera to work accordingly... The camera Demo Works on the 8520 device (Has a memory Card) but does not work on the 9780 device (Has No Memory Card) the error given
ERROR Class java.lang.ArrayOutOfBoundsException :index 0>=0
My code Sample:
public class MyScreen extends MainScreen{
Player _p;
VideoControl _videoControl;
FileConnection fileconn;
String PATH;
String GetfileName;
LabelField GetPhotofileName = new LabelField("",LabelField.FOCUSABLE){
protected boolean navigationClick(int status, int time){
Dialog.alert("Clicked");
return true;
}
};
public static boolean SdcardAvailabulity() {
String root = null;
Enumeration e = FileSystemRegistry.listRoots();
while (e.hasMoreElements()) {
root = (String) e.nextElement();
if( root.equalsIgnoreCase("sdcard/") ) {
}else if( root.equalsIgnoreCase("store/") ) {
}
}
class MySDListener implements FileSystemListener {
public void rootChanged(int state, String rootName) {
if( state == ROOT_ADDED ) {
if( rootName.equalsIgnoreCase("sdcard/") ) {
}
} else if( state == ROOT_REMOVED ) {
}
}
}
return true;
}
protected boolean invokeAction(int action){
boolean handled = super.invokeAction(action);
if(SdcardAvailabulity()){
PATH = System.getProperty("fileconn.dir.memorycard.photos")+"Image_"+System.currentTimeMillis()+".jpg";//here "str" having the current Date and Time;
} else {
// PATH = System.getProperty("file:///store/home/user/pictures/")+"Image_"+System.currentTimeMillis()+".jpg";
PATH = System.getProperty("fileconn.dir.photos")+"Image_"+System.currentTimeMillis()+".jpg";
}
if(!handled){
if(action == ACTION_INVOKE){
try{
byte[] rawImage = _videoControl.getSnapshot(null);
System.out.println("----------1");
fileconn=(FileConnection)Connector.open(PATH);
System.out.println("----------2");
if(fileconn.exists()){
fileconn.delete();
System.out.println("----------3");
}
fileconn.create();
System.out.println("----------4");
OutputStream os=fileconn.openOutputStream();
System.out.println("----------5");
os.write(rawImage);
GetfileName =fileconn.getName();
System.out.println("----------6");
System.out.println("GetfileName----------"+GetfileName);
fileconn.close();
System.out.println("----------7");
os.close();
Status.show("Image is Captured",200);
GetPhotofileName.setText(GetfileName);
System.out.println("----------8");
if(_p!=null)
_p.close();
System.out.println("----------9");
}catch(Exception e){
if(_p!=null){
_p.close();
}
if(fileconn!=null){
try{
fileconn.close();
}catch (IOException e1){
//if the action is other than click the trackwheel(means go to the menu options) then we do nothing;
}
}
}
}
}
return handled;
}
public MyScreen(){
setTitle("Camera App");
try{
System.out.println("Debug------------10");
_p = javax.microedition.media.Manager.createPlayer("capture://video?encoding=jpeg&width=1024&height=768");
_p.realize();
_videoControl = (VideoControl) _p.getControl("VideoControl");
System.out.println("Debug------------11");
if (_videoControl != null){
Field videoField = (Field) _videoControl.initDisplayMode (VideoControl.USE_GUI_PRIMITIVE, "net.rim.device.api.ui.Field");
_videoControl.setDisplayFullScreen(true);
System.out.println("Debug------------12");
_videoControl.setVisible(true);
_p.start();
System.out.println("Debug------------13");
if(videoField != null){
add(videoField);
System.out.println("Debug------------14");
}
}
}catch(Exception e){
if(_p!=null) {
_p.close();
}
Dialog.alert(e.toString());
}
add(GetPhotofileName);
}
}
on the 8520 (Has a Memory Card) the code works fine on the 9780 (Has no Memory Card) the the code stops at "System.out.println("debug---1")", can anyone please tell me if you can see any problem with my code???
public static boolean SdcardAvailabulity() {
String root = null;
Enumeration e = FileSystemRegistry.listRoots();
while (e.hasMoreElements()) {
root = (String) e.nextElement();
if( root.equalsIgnoreCase("sdcard/") ) {
return true;
}else if( root.equalsIgnoreCase("store/") ) {
return false;
}
}
class MySDListener implements FileSystemListener {
public void rootChanged(int state, String rootName) {
if( state == ROOT_ADDED ) {
if( rootName.equalsIgnoreCase("sdcard/") ) {
}
} else if( state == ROOT_REMOVED ) {
}
}
}
return true;
}
This is the sollution, My "SD card availability" code only returned true which caused the picture not to save when the blackberry had no memory card inserted. # Eugen Martynov Please read through the code and you will see it is there :)

Resources