Value below 0 Change program - java

If there is any way to change program when the "a" is below 0
I mean when the A is larger than 0 that the program will be like this and when below 0 than the program will be like B-A
private Button Button;
private EditText Num1;
private EditText Num2;
private EditText Num3;
private EditText Num4;
private EditText Num5;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_zisk);
Button = findViewById(R.id.btnBtn);
Num1 = findViewById(R.id.etNum1);
Num2 = findViewById(R.id.etNum2);
Num3 = findViewById(R.id.etNum3);
Num4 = findViewById(R.id.etNum4);
Num5 = findViewById(R.id.etNum5);
Button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
double a,b,c,d,e;
a = Double.parseDouble(Num1.getText() . toString());
b = Double.parseDouble(Num2.getText() . toString());
d = b-a;
e = d*0.80;
c = e*0.79;
Num3.setText(Double.toString(c));
Num4.setText(Double.toString(d));
Num5.setText(Double.toString(e));
}
});
}

Related

Equal function is not working in my java code

I have 2 textviews, 1 editbox and 1 button in my xml.
In my code, this line is not working:
if(c.equals(str)){
Toast.makeText(GameActivity.this, "Alright",Toast.LENGTH_LONG).show();
}
But next line (else statement) is working and In both cases (if & else statement) it shows else function toast ("Wrong").
Here is my code:
public class GameActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.game);
Button b1 = (Button) findViewById(R.id.button1);
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
TextView tv = (TextView) findViewById(R.id.textView1);
TextView tv2 = (TextView) findViewById(R.id.textView2);
Random r = new Random();
int i = r.nextInt(10 - 2) + 2;
tv.setText(i +"");
Random r1 = new Random();
int j = r1.nextInt((9 - 2) + 1) + 2;
tv2.setText(j +"");
int a = Integer.parseInt(tv.getText().toString());
int b = Integer.parseInt(tv2.getText().toString());
int result = a*b;
String str = String.valueOf(result);
EditText txt4 = (EditText) findViewById(R.id.editText1);
String c = txt4.getText().toString();
if(TextUtils.isEmpty(txt4.getText().toString())) {
txt4.setError("Please enter your answer");
return;
}
if(c.equals(str)){
Toast.makeText(GameActivity.this, "Alright",Toast.LENGTH_LONG).show();
}
else{
Toast.makeText(GameActivity.this, "wrong",Toast.LENGTH_LONG).show();
}
txt4.setText("");
}
});
}
Try this,
I got result
public class Test extends AppCompatActivity {
Button b1;
TextView t1,t2;
EditText e1;
int a,b;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
b1 = (Button) findViewById(R.id.button2);
t1=(TextView) findViewById(R.id.textView4);
t2=(TextView) findViewById(R.id.textView5);
e1=(EditText) findViewById(R.id.editText);
Random r = new Random();
int i = r.nextInt(10 - 2) + 2;
t1.setText(i +"");
Random r1 = new Random();
int j = r1.nextInt((9 - 2) + 1) + 2;
t2.setText(j +"");
a = Integer.parseInt(t1.getText().toString());
b = Integer.parseInt(t2.getText().toString());
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int result = a*b;
String str = String.valueOf(result);
String c = e1.getText().toString();
if(TextUtils.isEmpty(c)) {
e1.setError("Please enter your answer");
return;
}
if(c.equals(str)){
Toast.makeText(Test.this, "Alright",Toast.LENGTH_LONG).show();
}
else{
Toast.makeText(Test.this, "wrong",Toast.LENGTH_LONG).show();
}
e1.setText("");
}
});
}}
Instead of
String str = String.valueOf(result);
you should use
String str = Integer.toString(result);

Exception Handling in If statement?

I'm struggling to create a very simple app. There are Product Names with matching Product Numbers. User enters a Number and the corresponding Name appears.
editTextField1 = the number user types
button1 = the search button
editTextField2 = the product name appears
Now my code is working but there is only one problem, when the user doesn't enter anything and clicks on button1 the app crashes. So I need some sort of exception handler maybe? Im struggling to get my head around it. I know how I'm coding, by declaring loads of variables, is long-winded lol.
public class MainActivity extends AppCompatActivity {
private Button button1;
private EditText editText1;
private EditText editText2;
private int a = 123;
private String b = "TV";
private int c = 333;
private String d = "Radio";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button1 = (Button) findViewById(R.id.button1);
editText1 = (EditText) findViewById(R.id.editText1);
editText2 = (EditText) findViewById(R.id.editText2);
View.OnClickListener myOnClickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
double pNumber = Double.parseDouble(editText1.getText().toString());
if(pNumber == a){
editText2.setText(b);
}
else if (pNumber == c){
editText2.setText(d);
}
else
editText2.setText("Invalid Product Number");
}
};
button1.setOnClickListener(myOnClickListener);
In Addition to Spartas Answer, it would also be a good idea to check for a valid Double input:
try {
double pNumber = Double.parseDouble(text);
catch(NumberFormatException e){
//Do ExceptionHandling
}
Use this:
View.OnClickListener myOnClickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
String text = editText1.getText().toString();
if(!TextUtils.isEmpty(text)) {
// EditText1 is not empty
try {
double pNumber = Double.parseDouble(text);
if(pNumber == a)
editText2.setText(b);
else if (pNumber == c){
editText2.setText(d);
else
editText2.setText("Invalid Product Number");
}
catch(NumberFormatException e) {
// Invalid input, not a double
editText2.setText("Invalid double input");
}
}
else {
// EditText1 is empty
editText2.setText("EditText1 is empty");
}
}
};
There are basically 2 ways how you can handle this
1) Use try - catch
try{
double pNumber = Double.parseDouble(editText1.getText().toString());
}catch(NumberFormatException e){
//show a message to user
}
2) Use input sanitation
String number = editText1.getText().toString();
boolean isNumber = number.matches("^-?\\d+$"));//haven't tried this though
if(!isNumber) //if not number
//show a message to user

switch statement only incrementing once

I am creating a coffee ordering app for school. My intent for the code below is to increment or decrement the coffee integer based on whether the subtractCoffeeButton or addCoffeeButton is clicked. coffeeTV is used to show the user the number of coffee's queued to be ordered. subtotal and subtotalTV are used to hold the price and display it to the user.
As it is, the subtractCoffee and addCoffee buttons work to increment coffee and coffeeTV from 0 to 1 and vise-versa, subtotal and subtotalTV also work for displaying 0.00 and 2.5, but it won't increment any further than that. Further button clicks result in nothing happening when it is expected to increment coffee to 2,3,4,etc. and subtotal to 5.00,7.50,10.00,etc.
Code:
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_relative);
Button subtractCoffee = (Button) findViewById(R.id.subtractCoffeeButton);
subtractCoffee.setOnClickListener(this);
Button addCoffee = (Button) findViewById(R.id.addCoffeeButton);
addCoffee.setOnClickListener(this);
}
#Override
public void onClick(View v) {
double subtotal = 0.00;
int coffee = 0;
double coffeePrice = 2.50;
TextView coffeeTV = (TextView) findViewById(R.id.tvCoffeeOrder);
String coffeeString = coffeeTV.getText().toString();
int coffeeTracker = Integer.parseInt(coffeeString);
TextView subTotalTV = (TextView) findViewById(R.id.tvSubtotalCost);
switch (v.getId()) {
case R.id.subtractCoffeeButton:
if (coffeeTracker == 0) {
break;
} else if (coffeeTracker == 1) {
coffee = 0;
coffeeTracker = 0;
coffeeTV.setText(Integer.toString(coffee));
break;
} else {
coffee = coffee - 1;
coffeeTV.setText(Integer.toString(coffee));
subtotal = subtotal - coffeePrice;
subTotalTV.setText(Double.toString(subtotal));
}
break;
case R.id.addCoffeeButton:
coffee += 1;
coffeeTracker+=1;
coffeeTV.setText(Integer.toString(coffee));
subtotal = subtotal + coffeePrice;
subTotalTV.setText(Double.toString(subtotal));
break;
}
}
#Override
public void onClick(View v) {
double subtotal = 0.00;
int coffee = 0;
double coffeePrice = 2.50;
These variables have to be outside the onClick method.
Everytime you call onClick they get initiated again with 0.
because
double subtotal = 0.00;
int coffee = 0;
double coffeePrice = 2.50;
are in the local scope of your method. Declare as member variable and their value will persist as long as the current Activity is not destroyed
The problem is that you have
double subtotal = 0.00;
int coffee = 0;
at the beginning of your onClick() function. Thus, every time you click a button, you reset the number to 0 and then increment it to 1.
Besides, I'd recommend you to define separate OnClickListener instead of a global one. Something like:
public class MainActivity extends AppCompatActivity {
AppWidgetManager appWidgetManager;
SharedPreferences preferences;
SharedPreferences.Editor editor;
InputMethodManager inputMethodManager;
EditText mainEditText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Fabric.with(this, new Crashlytics());
setContentView(R.layout.activity_main);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
ActivityManager.TaskDescription taskDescription =
new ActivityManager.TaskDescription(null, null, getResources().getColor(R.color.primaryDark));
setTaskDescription(taskDescription);
getWindow().setNavigationBarColor(getResources().getColor(R.color.primary));
}
appWidgetManager = AppWidgetManager.getInstance(this);
inputMethodManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
preferences = PreferenceManager.getDefaultSharedPreferences(this);
editor = preferences.edit();
String savedText = preferences.getString("mainText", "");
mainEditText = (EditText) findViewById(R.id.mainEditText);
mainEditText.setMovementMethod(new ScrollAndSelectMovingMethod());
mainEditText.getText().append(savedText);
Selection.setSelection(mainEditText.getText(), savedText.length());
mainEditText.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
inputMethodManager.showSoftInput(mainEditText, InputMethodManager.SHOW_IMPLICIT);
}
});
mainEditText.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
onEditTextTextChanged(charSequence.toString());
}
#Override
public void afterTextChanged(Editable editable) {
}
});
}
#Override
public void onBackPressed() {
finish();
}
private void onEditTextTextChanged(String text) {
saveText(text);
updateWidget();
}
private void saveText(String text) {
editor.putString("mainText", text);
editor.commit();
}
private void updateWidget() {
int[] ids = appWidgetManager.getAppWidgetIds(new ComponentName(this, Widget.class));
for (int id : ids)
Widget.updateAppWidget(appWidgetManager, id);
}
}
As already said subtotal, coffe and coffePrice need to be outside of the onClick function. Also coffeTracker should always be the same as coffe as far as I can see, so you dont need the variable
This should be your code:
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
double subtotal = 0.00;
int coffee = 0;
double coffeePrice = 2.50;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_relative);
Button subtractCoffee = (Button) findViewById(R.id.subtractCoffeeButton);
subtractCoffee.setOnClickListener(this);
Button addCoffee = (Button) findViewById(R.id.addCoffeeButton);
addCoffee.setOnClickListener(this);
}
#Override
public void onClick(View v) {
TextView coffeeTV = (TextView) findViewById(R.id.tvCoffeeOrder);
TextView subTotalTV = (TextView) findViewById(R.id.tvSubtotalCost);
switch (v.getId()) {
case R.id.subtractCoffeeButton:
if (coffee == 0) {
break;
} else if (coffee == 1) {
coffee = 0;
coffeeTV.setText(Integer.toString(coffee));
break;
} else {
coffee = coffee - 1;
coffeeTV.setText(Integer.toString(coffee));
subtotal = subtotal - coffeePrice;
subTotalTV.setText(Double.toString(subtotal));
}
break;
case R.id.addCoffeeButton:
coffee += 1;
coffeeTV.setText(Integer.toString(coffee));
subtotal = subtotal + coffeePrice;
subTotalTV.setText(Double.toString(subtotal));
break;
}
}
Either you go with the other answers approach (field variables) or you read and parse the amounts on each onClick(). In code it would look something like:
static final double COFFEE_PRICE = 2.50;
#Override
public void onClick(View v) {
TextView coffeeTV = (TextView) findViewById(R.id.tvCoffeeOrder);
String coffeeString = coffeeTV.getText().toString();
int coffee = Integer.parseInt(coffeeString);
TextView subtotalTV = (TextView) findViewById(R.id.tvSubtotalCost);
String subtotalString = subtotalTV.getText().toString();
double subtotal = Double.parseDouble(subtotalString);
switch (v.getId()) {
case R.id.subtractCoffeeButton:
if (coffee == 0) {
break;
}
coffee--;
subtotal -= COFFEE_PRICE;
coffeeTV.setText(Integer.toString(coffee));
subtotalTV.setText(Double.toString(subtotal));
break;
case R.id.addCoffeeButton:
coffee++;
subtotal += COFFEE_PRICE;
coffeeTV.setText(Integer.toString(coffee));
subtotalTV.setText(Double.toString(subtotal));
break;
}
}

Clear a TextView when EditText inputs

I have 2 EditText fields set up for numeric inputs, a button to start a calculation on the 2 inputs when pressed, and a TextView to display the result of the calculation. For repeated calculations I want to clear the TextView result as soon as either EditText is changed.
Following the reply to "A better way to OnClick for EditText fields" given by 'avalancha', my program clears the result when the first EditText field is changed, but retains the previous answer if only the second EditText field is changed. Yet I have used the same source code for both fields.
Can someone explain why, and how to cure this? my code is appended:
public class DoublesActivity extends ActionBarActivity {
private EditText textBox1, textBox2;
private Button calcButton;
private Context context;
#Override
protected void onCreate(Bundle outState) {
super.onCreate(outState);
setContentView(R.layout.activity_doubles); // Sets the layout .xml file
context = this.getApplicationContext();
textBox1 = (EditText) findViewById(R.id.editText1); //textBox1 holds a reference to the editText1 object in the xml layout
textBox2 = (EditText) findViewById(R.id.editText2);
textBox1.setText("");
textBox2.setText("");
final TextView textBox3 = (TextView) findViewById(R.id.textView1);
textBox2.setOnFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View v2, boolean hasFocus2) {
if (hasFocus2) {
textBox3.setText("");
}
}
});
textBox1.setOnFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View v1, boolean hasFocus1) {
if (hasFocus1) {
textBox3.setText("");
}
}
});
calcButton = (Button) findViewById(R.id.button1);
calcButton.setBackgroundColor(Color.CYAN);
calcButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
CharSequence userNumber1 = textBox1.getText(); //userNumber1 is a CharSequence holding the text in textBox1
CharSequence userNumber2 = textBox2.getText();
Float handicap1 = Float.parseFloat(userNumber1.toString()); //convert to integer
Float handicap2 = Float.parseFloat(userNumber2.toString()); //convert to integer
Float handicapT = calculate(handicap1, handicap2);
CharSequence userNumber = String.valueOf(handicapT);
if (handicapT > 98.5) {
userNumber = "Non-valid h'cap 1!";
}
if (handicapT < -98.5) {
userNumber = "Non-valid h'cap 2!";
}
textBox3.setText(userNumber); // put result in the TextView
}
});
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
TextView textBox3 = (TextView) findViewById(R.id.textView1);
CharSequence userNumber = textBox3.getText();
outState.putCharSequence("savedText", userNumber);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
final TextView textBox3 = (TextView) findViewById(R.id.textView1);
CharSequence userText = savedInstanceState.getCharSequence("savedText");
textBox3.setText(userText);
}
Float calculate(Float h1, Float h2) {
float[] handicapArray;
handicapArray = new float[29];
handicapArray[0] = 28;
handicapArray[1] = 26;
handicapArray[2] = 24;
handicapArray[3] = 22;
handicapArray[4] = 20;
handicapArray[5] = 18;
handicapArray[6] = 16;
handicapArray[7] = 14;
handicapArray[8] = 12;
handicapArray[9] = 11;
handicapArray[10] = 10;
handicapArray[11] = 9;
handicapArray[12] = 8;
handicapArray[13] = 7;
handicapArray[14] = 6;
handicapArray[15] = 5;
handicapArray[16] = 4.5F;
handicapArray[17] = 4;
handicapArray[18] = 3.5F;
handicapArray[19] = 3;
handicapArray[20] = 2.5F;
handicapArray[21] = 2;
handicapArray[22] = 1.5F;
handicapArray[23] = 1;
handicapArray[24] = 0.5F;
handicapArray[25] = 0;
handicapArray[26] = -0.5F;
handicapArray[27] = -1;
handicapArray[28] = -1.5F;
int index1 = -1;
for (int i = 0; i < 29; i++) {
if (Math.abs(h1 - handicapArray[i]) < 0.001) {
index1 = i;
break;
}
}
if (index1 == -1) {
EditText textBox1 = (EditText) findViewById(R.id.editText1);
textBox1.setText("");
}
int index2 = -1;
for (int i = 0; i < 29; i++) {
if (Math.abs(h2 - handicapArray[i]) < 0.001) {
index2 = i;
break;
}
}
if (index2 == -1) {
EditText textBox2 = (EditText) findViewById(R.id.editText2);
textBox2.setText("");
}
int indexT = (index1 + index2) / 2; // Correctly rounds indexT halves down.
Float result = handicapArray[indexT];
if (index1 == -1) {
result = 99F;
}
;
if (index2 == -1) {
result = -99F;
}
;
return result;
}
Use addTextChangedListener to clear textview.
editText.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {}
public void beforeTextChanged(CharSequence s, int start,
int count, int after) {
}
public void onTextChanged(CharSequence s, int start,
int before, int count) {
resultTextView.setText("");
}
});
For example please use below link
android on Text Change Listener

whats wrong with the android code ?

whats wrong with the android code ? I want this code to give Incorrect when the
entered answer is wrong and correct when the answer is correct but every time
get is incorrect
and are my casting variables correct
public class MainActivity extends Activity {
TextView Jlabel1;
TextView Jlabel2;
TextView Jlabel3;
EditText Jtextbox1;
Button b1;
int m;
int ans;
String ans1;
String k;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Jlabel1 = (TextView) findViewById(R.id.textView1);
Jlabel2 = (TextView) findViewById(R.id.textView2);
Jlabel3 = (TextView) findViewById(R.id.textView3);
Jtextbox1 = (EditText) findViewById(R.id.editText1);
b1 = (Button) findViewById(R.id.button1);
double q = Math.random();
double w = Math.random();
int e = (int) (q * 10);
int z = (int) (w * 10);
ans = e + z;
Jlabel1.setText(Integer.toString(e));
Jlabel2.setText(Integer.toString(z));
ans1 = String.valueOf(ans);
k = Jtextbox1.getText().toString();
b1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (ans1.equals(k)) {
Jlabel3.setText("Correct");
} else {
Jlabel3.setText("Incorrect");
}
}
});
}
}'
You're getting a copy of the contents of the edittext too early. Move the
k = Jtextbox1.getText().toString();
inside the onClick().

Categories

Resources