Problems with Else If statements in Android - android

I'm working on this program that uses a few lines of code that worked that last time I used them but the only difference this time is that I need to use else if's instead of a basic if else statement. Still trying to learn how to really use this but any help would be appreciated. My error is stemming from the if statement and I have a feeling it is to do with the float result; line.
private float caravan = 35;
private float wigwag = 25;
private float tent = 15;
private float caravan(float value){
return value * caravan;
}
private float wigwag(float value){
return value * wigwag;
}
private float tent(float value){
return value * tent;
}
Button bookButton;
public void onClick(View view) {
EditText bookAmount = (EditText)findViewById(R.id.txtNights);
EditText bookFinal = (EditText)findViewById(R.id.txtBooked);
float bookResult = Float.parseFloat(bookAmount.getText().toString());
float result;
RadioButton cbSelected = (RadioButton)findViewById(R.id.radCaravan);
if(cbSelected.isChecked()){
result = caravan(bookResult);
} else if (result == wigwag(bookResult)){
} else if (result == tent(bookResult)){
}
bookFinal.setText(String.valueOf(result));
}

Your problem is that you put a semicolon at the end of your statements, and you don't use the == operator:
if(cbSelected.isChecked()){
result = caravan(bookResult);
} else if (result = wigwag(bookResult);{
} else if (result = tent(bookResult);{
}
Fix by removing the semicolons and using the equality operator:
if(cbSelected.isChecked()){
result = caravan(bookResult);
} else if (result == wigwag(bookResult){
} else if (result == tent(bookResult){
}

used == instead of = operator
if (result == wigwag(bookResult))

Related

How to detect touching/releasing two objects with two pointers

I'm trying to touch two rectangle at the same time using two fingers. How can i implements that ?
Never mind I find a solution to this problem :
public void detectTwoRectangleTouching() {
if(Gdx.input.isTouched(0)){
int x = Gdx.input.getX(0);
int y = Gdx.input.getY(0);
if(rectangle1.contain(x,y))
isRectangle1Touched = true;
else
isRectangle1Touched = false;
if(rectangle2.contain(x,y))
isRectangle2Touched = true;
else
isRectangle2Touched = false;
}else {
isRectangle1Touched = false;
isRectangle2Touched = false;
}
if(Gdx.input.isTouched(1)){
int x = Gdx.input.getX(1);
int y = Gdx.input.getY(1);
if(rectangle1.contain(x,y))
isRectangle1Touched = true;
if(rectangle2.contain(x,y))
isRectangle2Touched = true;
}
if(isRectangle1Touched && isRectangle2Touched) {
// the two rectangle are pressed !!!
}
if(!isRectangle1Touched && !isRectangle2Touched) {
// the two rectangle are released !!!
}
}

Android Password Strength checker with seekbar

How to Create Password Strength checker with seekbar in android ?
You can use https://github.com/VenomVendor/Password-Strength-Checker for your requirement
or use TextWatcher for checking EditText length .Like this way
public void afterTextChanged(Editable s)
{
if(s.length()==0)
textViewPasswordStrengthIndiactor.setText("Not Entered");
else if(s.length()<6)
textViewPasswordStrengthIndiactor.setText("EASY");
else if(s.length()<10)
textViewPasswordStrengthIndiactor.setText("MEDIUM");
else if(s.length()<15)
textViewPasswordStrengthIndiactor.setText("STRONG");
else
textViewPasswordStrengthIndiactor.setText("STRONGEST");
if(s.length()==20)
textViewPasswordStrengthIndiactor.setText("Password Max Length Reached");
}
};
Demo Help .
afterTextChanged (Editable s) - This method is called when the text
has been changed. Because any changes you make will cause this method
to be called again recursively, you have to be watchful about
performing operations here, otherwise it might lead to infinite loop.
create a rule engine for password strength, may be a simple function which returns strength when you pass a string to it.
use a TextWatcher on your password edit text and pass any string entered through your rules.
Use returned strength value from your rule engine to set progress value and progress color of your progress bar.
https://github.com/yesterselga/password-strength-checker-android
is a really good example. I changed the code not to use string values. Instead of it I am using values from 0-4. here is the code
public enum PasswordStrength
{
WEAK(0, Color.RED), MEDIUM(1, Color.argb(255, 220, 185, 0)), STRONG(2, Color.GREEN), VERY_STRONG(3, Color.BLUE);
//--------REQUIREMENTS--------
static int REQUIRED_LENGTH = 6;
static int MAXIMUM_LENGTH = 6;
static boolean REQUIRE_SPECIAL_CHARACTERS = true;
static boolean REQUIRE_DIGITS = true;
static boolean REQUIRE_LOWER_CASE = true;
static boolean REQUIRE_UPPER_CASE = true;
int resId;
int color;
PasswordStrength(int resId, int color)
{
this.resId = resId;
this.color = color;
}
public int getValue()
{
return resId;
}
public int getColor()
{
return color;
}
public static PasswordStrength calculateStrength(String password)
{
int currentScore = 0;
boolean sawUpper = false;
boolean sawLower = false;
boolean sawDigit = false;
boolean sawSpecial = false;
for (int i = 0; i < password.length(); i++)
{
char c = password.charAt(i);
if (!sawSpecial && !Character.isLetterOrDigit(c))
{
currentScore += 1;
sawSpecial = true;
}
else
{
if (!sawDigit && Character.isDigit(c))
{
currentScore += 1;
sawDigit = true;
}
else
{
if (!sawUpper || !sawLower)
{
if (Character.isUpperCase(c))
sawUpper = true;
else
sawLower = true;
if (sawUpper && sawLower)
currentScore += 1;
}
}
}
}
if (password.length() > REQUIRED_LENGTH)
{
if ((REQUIRE_SPECIAL_CHARACTERS && !sawSpecial) || (REQUIRE_UPPER_CASE && !sawUpper) || (REQUIRE_LOWER_CASE && !sawLower) || (REQUIRE_DIGITS && !sawDigit))
{
currentScore = 1;
}
else
{
currentScore = 2;
if (password.length() > MAXIMUM_LENGTH)
{
currentScore = 3;
}
}
}
else
{
currentScore = 0;
}
switch (currentScore)
{
case 0:
return WEAK;
case 1:
return MEDIUM;
case 2:
return STRONG;
case 3:
return VERY_STRONG;
default:
}
return VERY_STRONG;
}
}
and how to use it:
if(PasswordStrength.calculateStrength(mViewData.mRegisterData.password). getValue() < PasswordStrength.STRONG.getValue())
{
message = "Password should contain min of 6 characters and at least 1 lowercase, 1 uppercase and 1 numeric value";
return null;
}
you may use PasswordStrength.VERY_STRONG.getValue() as alternative. or MEDIUM

contains in HashSet<int[]>()

In android I'm trying to save grids that the user already have pressed.
Code snipping I’m using is:
// private
private HashSet<int[]> PlayerSelectedHashField = new HashSet<int[]>();
private boolean collisionDetected = false;
In a function I’m using
collisionDetected = PlayerSelectedHashField.contains(TmpPos); // -> Fail - not working
{doing something}
PlayerSelectedHashField.add(TmpPos); // int[] TmpPos - TmpPos is x y
The .add function is working as expected, but .contains always return false.
Why does it not working - and what can I do instead?
public boolean contains(Object o) {
return map.containsKey(o);
}
containsKey:
public boolean containsKey(Object key) {
return getNode(hash(key), key) != null;
}
getNode:
final Node<K,V> getNode(int hash, Object key) {
Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
if ((tab = table) != null && (n = tab.length) > 0 &&
(first = tab[(n - 1) & hash]) != null) {
if (first.hash == hash && // always check first node
((k = first.key) == key || (key != null && key.equals(k))))
return first;
if ((e = first.next) != null) {
if (first instanceof TreeNode)
return ((TreeNode<K,V>)first).getTreeNode(hash, key);
do {
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
return e;
} while ((e = e.next) != null);
}
}
return null;
}
It will not work since equals of arrays will do a == compare, and it will return true only if they point to the same instance.
Your problem could be fixed without work with Arrays.equals (the way to compare two arrays elements and not reference) (could be problematic (at least, for me.) i prefer an easy way)
Since you save X and Y coordinates, just make a class Point
public class Point {
public final int X;
public final int Y;
public Point(int x, int y)
{
X = x;
Y = y;
}
#Override
public boolean equals(Object obj)
{
if (obj == this) {
return true;
}
if (obj instanceof Point) {
Point pObj = (Point) obj;
return pObj.X == X && pObj.Y == Y;
}
return false;
}
#Override
public int hashCode()
{
int result = X;
result = 31 * result + Y;
return result;
}
}
then use Point class to save X, Y points.
Instead of create your custom point class, you can use the Android Point.
Example
Set<Point> points = new HashSet<Point>();
points.add(new Point(1, 3));
points.add(new Point(1, 4));
System.out.println(points.contains(new Point(1, 3)));
System.out.println(points.contains(new Point(1, 4)));
System.out.println(points.contains(new Point(1, 5)));
From the HashSet javadocs:
public boolean contains(Object o)
Returns true if this set contains the specified element. More formally, returns true if and only if this set contains an element e such that (o==null ? e==null : o.equals(e)).
So, generally, if you don't know what happens when you call equals on a particular object type, then contains also may not behave as you expect. It is never a bad idea to make a class for a particular object if that object type has conceptual meaning in your program. If you do that, you can override the equals method to make sure it is behaving exactly as you want.

Method to add two values of type float and integer in Android

Small Android application, which performs addition and other basic operations, and the OnClick() is as follows
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btnAdd:
isValidToProcess(1);
break;
......
/*Switch continues for all other operations like Subtraction,etc*/
}
}
and my isValidToProcess() is as follows
private boolean isValidToProcess(int a) {
String num1 = mEdit1.getText().toString();
String num2 = mEdit2.getText().toString();
if (num1.matches("") || num2.matches(""))
{
ValueEmptyWarning();
}
else {
float numa = Float.parseFloat(num1);
float numb = Float.parseFloat(num2);
switch (a) {
case 1:
addition(numa, numb);
break;
......
/*Switch continues for all other operations like Subtraction,etc*/
}
}
My addition() function
public void addition(float numa, float numb) {
answer = numa + numb;
mEdit3.setText(String.valueOf(answer));
Log.v(TAG, "Error at Subtraction");
}
This program is working fine for Float and Integer numbers, But the problem is, for both Integer and Float values the answer will be in fractions, For example Number1=2 and Number2=3 and the answer=5.0
Objective: If User inputs Integer, The decimal point should not be there.
Is this possible to get the type of Value which user has entered on EditText?
first check for Integer.parseInt(numer) and catch for NumberFormatException . if it will parse it correctly then it is an integer else you can go for float.
For more control, try the basic OOP concept of overloading methods like
public float addition(float numa, float numb) {
// will return float
return numa + numb;
}
public int addition(int numa, float numb) {
// explicitly cast to int
return numa + (int) numb;
}
public int addition(float numa, int numb) {
// explicitly cast to int
return (int) numa + numb;
}
public int addition(int numa, int numb) {
// will return int
return numa + numb;
}
To examin your in put, try something like this...
public void examineInput(String input1, String input2) {
// For both are float
if (input1.indexOf(".") != -1 && input2.indexOf(".") != -1) {
float numa = Float.parseFloat(input1);
float numb = Float.parseFloat(input2);
float ans = addition(numa, numb);
Log.i(TAG, String.format("%f + %f = %f", numa, numb, ans));
}
// for first to be int and second to be float
else if (input1.indexOf(".") == -1 && input2.indexOf(".") != -1) {
int numa = Integer.parseInt(input1);
float numb = Float.parseFloat(input2);
int ans = addition(numa, numb);
Log.i(TAG, String.format("%d + %f = %d", numa, numb, ans));
}
// for first to be float and second to be int
else if (input1.indexOf(".") != -1 && input2.indexOf(".") == -1) {
float numa = Float.parseFloat(input1);
int numb = Integer.parseInt(input2);
int ans = addition(numa, numb);
Log.i(TAG, String.format("%f + %d = %d", numa, numb, ans));
}
// for both to be int
else if (input1.indexOf(".") == -1 && input2.indexOf(".") == -1) {
int numa = Integer.parseInt(input1);
int numb = Integer.parseInt(input2);
int ans = addition(numa, numb);
Log.i(TAG, String.format("%d + %d = %d", numa, numb, ans));
}
}
And the is the input to test this code, with output
examineInput("5.2", "6.2"); // 5.200000 + 6.200000 = 11.400000
examineInput("5", "3.6"); // 5 + 3.600000 = 8
examineInput("1.6", "5"); // 1.600000 + 5 = 6
examineInput("5", "5"); // 5 + 5 = 10
Note: you need to verify that examineInput always get valid numbers, not strings of non numaric characters...
Hope this helps to improve OOP concepts as well..:)
I don't think there is an usable api in EditText for developer to get the type of value.You can find another way in JAVA,apache may provider some widget to handle this.
You can use String formatters in this case.
Formatting Numeric Print Output
For your case, you have to use a pattern like this.
DecimalFormat df = new DecimalFormat("0.##");
String finalAnswer = df.format(answer);
You can use the following code in your addition function if your answer is float
answer = numa + numb;
String answerString = String.valueOf(answer);
String decimalString = answerString.substring(answerString.indexOf(".") + 1);
if (Integer.parseInt(decimalString) == 0)
answerString = answerString.substring(0, answerString.indexOf("."));
This will return a float value if your answer has other than 0 after the decimal or else it will return int in String
The user always enters String there is no other type entered using editText however, you need to check if the editText has (.) therefore it is float and then parse it as float otherwise, it is Integer and then parse it as Integer.
The code could look like the following.
if (num1.indexOf(".") != 0) {
float numa = Float.parseFloat(num1);
float numb = Float.parseFloat(num2);
}
else
{
int numa = Integer.parseInt(num1);
int numb = Integer.parseInt(num2);
}
by doing so the output for integers wont be in fraction style
P.S:
You have to make sure that the keyboard only enters number. so your app doesn't crash while parsing.
hope this helps
The type of Value which user has entered on EditText will be always String only. but you can restrict user to enter any perticular type value by android:inputType="" property inside EditText.

Indexable Listview in Android

I'm trying to get an indexable list in my list view. I referred this. But while using the code, I'm facing with an error while using Korean Characters in the StringMatcher class. Can anyone explain me the usage of this class? Is this class required for English Characters as well?
Thanks in advance.
There are some changes to be done to make it work. In order to compile the project and get rid of korean text update the StringMatcher class
package com.woozzu.android.util;
public class StringMatcher {
public static boolean match(String value, String keyword) {
if (value == null || keyword == null)
return false;
if (keyword.length() > value.length())
return false;
int i = 0, j = 0;
do {
int vi = value.charAt(i);
int kj = keyword.charAt(j);
if (isKorean(vi) && isInitialSound(kj)) {
} else {
if (vi == kj) {
i++;
j++;
} else if (j > 0)
break;
else
i++;
}
} while (i < value.length() && j < keyword.length());
return (j == keyword.length())? true : false;
}
private static boolean isKorean(int i) {
return false;
}
private static boolean isInitialSound(int i) {
return false;
}
}

Categories

Resources