Calculator dot function issue android - java

I am working on a calculator and practicing java and android development. Everything works fine except for the dot function. here is the problem(see the very last dot):
here are the codes:
case R.id.btn_dot:
if (dotSet) {
screenTV.append("");
} else if (isEmpty() || empty) {
screenTV.append("0.");
dotSet = true;
count++;
} else {
screenTV.append(".");
dotSet = true;
count++;
}
an operand:
ase R.id.btn_add:
if (isEmpty()) {
screenTV.append("");
} else if (screenTvGet().endsWith("+")) {
screenTV.append("");
} else if (!isEmpty()) {
screenTV.append("+");
dotSet = false;
empty = true;
resultSet = false;
count = 0;
}
break;
and a number:
case R.id.btn0:
if (resultSet) {
screenTV.append("");
} else if (isEmpty()) {
screenTV.append("");
} else {
screenTV.append("0");
empty = false;
}
Finally, the backspace function:
case R.id.btn_backspace:
String screenContent;
String screen = screenTV.getText().toString();
int screenMinusOne = screen.length() - 1;
String screenMinus = String.valueOf(screenMinusOne);
if (screen.endsWith("."))
dotSet = false;
if (isEmpty()) {
screenTV.setText("");
} else {
screenContent = screen.substring(0, screen.length() - 1);
screenTV.setText(screenContent);
}
break;
forget about the "count".
I believe you can see the whole picture. now I want somehow when I clear an operand with "BackSpace function" and the previous number has a dot in it, the dot button doesn't just add an '.' or "0." to the screen instead returns null or just adds this "". I hope my question is clear.

Remove dotSet. You don't need it.
Then, similar to how you do this for btn_add:
} else if (screenTvGet().endsWith("+")) {
screenTV.append("");
use a regex for btn_dot to check if there is a . in the last part of the text:
} else if (screenTvGet().matches(".*\\.\\d*")) {
screenTV.append("");

Related

Need help checking if a binary tree is a valid binary search tree in Java [duplicate]

This question already has answers here:
What's the simplest way to print a Java array?
(37 answers)
Closed 3 years ago.
Here is my code:
public boolean isBST() {
return isBST(this.root);
}
private boolean isBST(BinaryNode<T> rootNode) {
if (rootNode == null) {
return false;
}
if (rootNode.isLeaf()) {
return true;
}
T left = null;
T right = null;
if (rootNode.hasLeftChild()) {
left = rootNode.getLeftChild().getData();
if (left.compareTo(rootNode.getData()) < 0) {
return this.isBST(rootNode.getLeftChild());
}
else {
return false;
}
}
if (rootNode.hasRightChild()) {
right = rootNode.getRightChild().getData();
if (right.compareTo(rootNode.getData()) > 0) {
return this.isBST(rootNode.getRightChild());
}
else {
return false;
}
}
return true;
}
This code works for simple binary trees, but it doesn't work for other ones. Such as if I have a tree like so:
5
/ \
3 6
/\
1 2
It won't mark it false even thought it should since 2 is smaller than 3 and is in the wrong place. My code just checks the left child's left children, and the checks the right child's right children and not the inner children. What can I do to make this code work in the way that I wrote it? How can I modify it?
The bug is in the line
return this.isBST(rootNode.getLeftChild());
You must not exit the method just because the left part is checked (if it exists).
Instead of
if (left.compareTo(rootNode.getData()) < 0) {
return this.isBST(rootNode.getLeftChild());
}
else {
return false;
}
this should do the expected:
if (left.compareTo(rootNode.getData()) >= 0 ||
!this.isBST(rootNode.getLeftChild()) {
return false;
}
(For symmetry reasons you may also want to rewrite the right part check in a similar way, however this is not required. Your could would also work in its current form.)
I think all you need to do is when you recursively look left and right only return if it's false
if (rootNode.hasLeftChild()) {
left = rootNode.getLeftChild().getData();
if (left.compareTo(rootNode.getData()) < 0) {
boolean isValid = this.isBST(rootNode.getLeftChild());
if (!isValid) {
return false;
}
} else {
return false;
}
}
if (rootNode.hasRightChild()) {
right = rootNode.getRightChild().getData();
if (right.compareTo(rootNode.getData()) > 0) {
boolean isValid = this.isBST(rootNode.getRightChild());
if (!isValid) {
return false;
}
} else {
return false;
}
}
return true
It looks like, at a quick look, the return is happening before the right side is checked.
Slightly more succinct version that also supports duplicates appearing only on the right (if you want to allow duplicates on the left then swap the >= in left comparison for <= in the right comparison
if (rootNode.hasLeftChild()) {
left = rootNode.getLeftChild().getData();
if (left.compareTo(rootNode.getData()) >= 0) || !this.isBST(rootNode.getLeftChild()) {
return false;
}
}
if (rootNode.hasRightChild()) {
right = rootNode.getRightChild().getData();
if (right.compareTo(rootNode.getData()) < 0 || !this.isBST(rootNode.getRightChild()) {
return false;
}
}
return true;

How to catch a NumberFormatException?

I'm trying to figure out how to catch a numberformat exception error within my code such that if the user inputs a letter within a string and my program tries to parse it to an int my program won't throw up an error but instead stop and return a Boolean value. I'm also trying to understand that if the try statement works I'd like it to continue to execute the following code.
if (counter == 3) {
int compare;
boolean check = true;
String[] newip = IpAddress.split("\\.");
if (newip.length == 4) {
for (int index = 0; index < newip.length; index++) {
//There should be a try statement here.
// if the try statement fails then I'd like for it to catch
// the numberformatexception and evaluate my boolean to
//false;
//but if it passes I'd like for it to continue to execute
//the following code.
compare = Integer.parseInt(newip[index]);
if (compare >= 0 & (compare <= 255)) {
check = true;
}
else{
check = false;
}
}
if (check)
return true;
else
return false;
}
else {
check = false;
return check;
}
}
else{
return false;
}
}
Surround that line with try/catch:
try {
compare = Integer.parseInt(newip[index]);
} catch (NumberFormatException e) {
check = false;
}
and then:
if (check) {
if (compare >= 0 & (compare <= 255)) {
check = true;
} else {
check = false;
}
} else {
return false;
}
Instead of catching NumberFormatException, you can use NumberUtils from commons-lang 3.x to check if the input is a number.
NumberUtils.isNumber(newip[index])
However as per the documentation, it would be deprecated in 4.x and you would need to use isCreatable
NumberUtils.isCreatable(newip[index])

Indent all lines after a certain character until another character

For an assignment we are creating a java program that accepts a java file, fixes messy code and outputs to a new file.
We are to assume there is only one bracket { } per line and that each bracket occurs at the end of the line. If/else statements also use brackets.
I am currently having trouble finding a way to indent every line after an opening bracket until next closing bracket, then decreasing indent after closing bracket until the next opening bracket. We are also required to use the methods below:
Updated code a bit:
public static void processJavaFile() {
}
}
This algorithm should get you started. I left a few glitches that you'll have to fix.
(For example it doesn't indent your { brackets } as currently written, and it adds an extra newline for every semicolon)
The indentation is handled by a 'depth' counter which keeps track of how many 'tabs' to add.
Consider using a conditional for loop instead of a foreach if you want more control over each iteration. (I wrote this quick n' dirty just to give you an idea of how it might be done)
public String parse(String input) {
StringBuilder output = new StringBuilder();
int depth = 0;
boolean isNewLine = false;
boolean wasSpaced = false;
boolean isQuotes = false;
String tab = " ";
for (char c : input.toCharArray()) {
switch (c) {
case '{':
output.append(c + "\n");
depth++;
isNewLine = true;
break;
case '}':
output.append("\n" + c);
depth--;
isNewLine = true;
break;
case '\n':
isNewLine = true;
break;
case ';':
output.append(c);
isNewLine = true;
break;
case '\'':
case '"':
if (!isQuotes) {
isQuotes = true;
} else {
isQuotes = false;
}
output.append(c);
break;
default:
if (c == ' ') {
if (!isQuotes) {
if (!wasSpaced) {
wasSpaced = true;
output.append(c);
}
} else {
output.append(c);
}
} else {
wasSpaced = false;
output.append(c);
}
break;
}
if (isNewLine) {
output.append('\n');
for (int i = 0; i < depth; i++) {
output.append(tab);
}
isNewLine = false;
}
}
return output.toString();
}

Processing - Found one too many { characters without a } character afterward

Here is my code... can someone please tell me what is wrong?
void keyPressed() {
if (key == '\n') {
equation = typing;
switch (equation.charAt(2)) {
case "-":
if (equation.charAt(3) == "x") {
math[0] = -1;
};
else {
math[0] = int(equation.charAt(3) * -1);
};
}
}
}
I don't understand what is wrong. All of the braces match up. Is it that you can't use an if else inside a switch???
try replacing
if (equation.charAt(3)=="x") {
math[0] = -1;
};
else {
math[0] = int(equation.charAt(3)*-1);
};
with
if (equation.charAt(3)=='x') { // NOTE character comparision
math[0] = -1;
}
else {
math[0] = int(equation.charAt(3)*-1);
}

How to prevent my program from crashing due to a user's input

I am trying to implement an algorithm "recongnizng strings in a language "
L = {'w$w' : w is a possible empty string of characters other than $,
w' = reverse(w)}
my problem is whenever i input anything without having $, it crashes on the while loop. what will be the best way to prevent it from crashing?
public boolean isInLanguage(String inputString)
{
StackReferenceBased stack1 = new StackReferenceBased();
StackReferenceBased stack2 = new StackReferenceBased();
Object qItem;
Object sItem;
int index = 0;
if (inputString.length() == 0)
{
return false; // empty string not in L
}
else if (inputString.length() == 1)
{
return true;
}
**while (inputString.charAt(index) != '$')**
{
// save the first half of the string
stack1.push(inputString.charAt(index));
++index;
}
// index points to '$' or its value > than inputString.length()
while (index < inputString.length()-1)
{
// save the second half of the string
++index;
stack2.push(inputString.charAt(index));
}
do
{
// match the first half of the string with the second half
if ((stack1.isEmpty() && !stack2.isEmpty()) ||(!stack1.isEmpty() && stack2.isEmpty()))
{
return false;
}
qItem = stack1.peek();
sItem = stack2.peek();
if (qItem != sItem)
{
return false;
}
if (!stack1.isEmpty())
{
stack1.pop();
}
if (!stack2.isEmpty())
{
stack2.pop();
}
}while (!stack1.isEmpty() || !stack2.isEmpty());
if (stack1.isEmpty() && stack2.isEmpty())
{
return true;
}
else
{
return false;
}
}
Exception in thread "main" java.lang.StringIndexOutOfBoundsException:
String index out of range: 4 at java.lang.String.charAt(Unknown
Source) at
assignmnet5.StackReferenceBased.isInLanguage(StackReferenceBased.java:87)
at assignmnet5.Question3.main(Question3.java:19)
this is my main:
public static void main(String[]args)
{
StackReferenceBased stack = new StackReferenceBased();
String str;
boolean bool;
Scanner kb = new Scanner(System.in);
System.out.println( "Enter a string to be checked by the algorithm : ");
str = kb.next();
**bool = stack.isInLanguage(str);**
if (bool == true)
System.out.println( "The string is in language");
else
System.out.println("The string is not in language");
}
It sounds like this might suffice:
if (inputString == null || !inputString.contains("$")) {
return false; // empty string not in L
}
possible issue is a null pointer exception, try to add this line in the top of your function
public boolean isInLanguage(String inputString)
{
if(inputString == null){
return false;
}
...
...
complete your code
if you still have crashes, you will need to provide the error you've got when you run the code.

Categories

Resources