Bengali calculator Android studio - android

I am trying to build a Bengali calculator. Here is the layout of English calculator :
By editing layout I can easily replace English digits with Bengali digits. But when it comes to the calculation i am unable to do it. Like i want it to calculate in Bengali too. e.g it will perform in Bengali like this (২+২=৪) instead of (2+2=4). I have tried the replacing method but it didn't work.
Bengali digits(০ ১ ২ ৩ ৪ ৫ ৬ ৭ ৮ ৯)
English digits(1 2 3 4 5 6 7 8 9)
Thank you for your time.
public class MainActivity extends AppCompatActivity {
private TextView screen;
private String str2, result, str, sign;
private double a, b;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
screen = (TextView) findViewById(R.id.textview);
str = "";
}
public void onclick(View v) {
Button button = (Button) v;
str += button.getText().toString();
screen.setText(str);
a = Double.parseDouble(str);
}
public void onclicksign(View v) {
Button button = (Button) v;
sign = button.getText().toString();
screen.setText(sign);
str = "";
}
public void calculate(View v) {
Button button = (Button) v;
str2 = screen.getText().toString();
b = Double.parseDouble(str2);
if (sign.equals("+")) {
result = a + b + "";
} else if (sign.equals("-")) {
result = a - b + "";
} else if (sign.equals("*")) {
result = a * b + "";
} else if (sign.equals("/")) {
result = a / b + "";
} else {
screen.setText("?????? ???");
}
{
screen.setText(result);
}
}
}

Your code tries to extract numerical values from the text on buttons.
You should write custom Double parser which parses Bengali number text to numerical value.
Also you should write a method which converts numerical double value to Bengali number text. You have to use this method while setting screen text.
public class MainActivity extends AppCompatActivity {
private TextView screen;
private String str2, result, str, sign;
private double a, b;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
screen = (TextView) findViewById(R.id.textview);
str = "";
}
public void onclick(View v) {
Button button = (Button) v;
str += button.getText().toString();
screen.setText(str);
a = BengaliUtils.toDouble(str);
}
public void onclicksign(View v) {
Button button = (Button) v;
sign = button.getText().toString();
screen.setText(sign);
str = "";
}
public void calculate(View v) {
Button button = (Button) v;
str2 = screen.getText().toString();
b = BengaliUtils.toDouble(str2);
if (sign.equals("+")) {
result = a + b + "";
} else if (sign.equals("-")) {
result = a - b + "";
} else if (sign.equals("*")) {
result = a * b + "";
} else if (sign.equals("/")) {
result = a / b + "";
} else {
screen.setText("?????? ???");
}
{
screen.setText(BengaliUtils.toString(result));
}
}
}
class BengaliUtils {
static String toString(double value) {
//TODO implement logic
// You can convert value to regular number text, and then replace each char with the Bengali version. The performance could be improved with better logic.
return text;
}
static double toDouble(String text) {
//TODO implement logic
//You can do that, first replace each Bengali char with normal number char. The use Double.parse on new text. The performance could be improved with better logic.
return value;
}
}

#Override
public void onClick(View view) {
String num = editText.getText().toString();
//split the num
char[] charArray = num.toCharArray();
StringBuilder stringBuilder = new StringBuilder(charArray.length);
// loop and convert using switch case
for (int i=0; i<charArray.length; i++ ){
char character = charArray[i];
switch (character){
case '.':
stringBuilder.append(".");
break;
case '0':
stringBuilder.append("০");
break;
case '1':
stringBuilder.append("১");
break;
}
}
//Final result..
textView.setText(stringBuilder);
}
Try above code...
Here is the output
NOTE
I am taking English numbers from EditText on Button click. You will
have to change that in your code.
Currently, switch can handle 0,1,.(decimal) only. You can easily
add cases for other numbers too.
Please Check this answer too. Convert String to another locale in java

Related

I'm repeatedly getting the initialized value after using if statement in android studio

I've just started off learning Adroid studio and coding with Java. I'm not sure why my if statement returns a value of 0(The initialized value).
The code above the onclicklistener works fine.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_thecart);
Intent caller = getIntent();
String item = caller.getStringExtra("choice");
TextView disptext = (TextView) findViewById(R.id.carttoptext);
disptext.setText("You selected " + item);
EditText quantity = (EditText) findViewById(R.id.inputquantity);
Button calc= (Button) findViewById(R.id.calc);
calc.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
double price=0;
double vquant = valueOf(quantity.getText().toString());
String item = caller.getStringExtra("choice");
if (item.equals("Eggs")) {
price = vquant * 4;
} else if (item.equals("Milk")) {
price = vquant * 30;
} else if (item.equals("Bread")) {
price = vquant * 23;
} else if (item.equals("Chips")) {
price = vquant * 20;
} else if (item.equals("Maggi")) {
price = vquant * 15;
}
DecimalFormat formatval = new DecimalFormat("##.##");
TextView pricetext = (TextView) findViewById(R.id.pricetext);
pricetext.setText("Total: " + formatval.format(price));
}
});
}
}
I'm expecting the textview beneath the edittext to give me the value vquant*(if condition value). But I'm getting the Textview as Total: 0 , which is the initializing value.
What changes should I make to the code so that I get desired output?
check if the vquant is able to fetch the value from the quantity as a double.
ValueOf() change the data into String and you are taking that data to a double variable. It won't work. Use Double.valueOf()
Have you tried "Double.parseDouble(..)" instead of valueOf?

User Input of int won't be null

I made a code where user put value between some range and my code generate random number for them. Randomization working properly but when fields are blank my app is crash how should I fix it.
randNum.java
Button generateNum = findViewById(R.id.generate_number);
generateNum.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
EditText et = findViewById(R.id.fromNum);
String sTextFromET = et.getText().toString();
int fNum = Integer.valueOf(sTextFromET);
EditText et1 = findViewById(R.id.toNum);
String sTextFromET1 = et1.getText().toString();
int sNum = Integer.valueOf(sTextFromET1);
TextView ans = findViewById(R.id.ans);
// if(sNum == null || fNum == null){
//
// ans.setText(getString(R.string.enterNumError));
//
// }
// else
if(sNum < fNum){
ans.setText(getString(R.string.max_min_error));
}else {
final int random = new Random().nextInt((sNum - fNum) + 1) + fNum;
String ras = Integer.toString(random);
ans.setText(ras);
}
}
});
I try to use null but it is not working.
You need to put validation first on button click. (For checking if user has entered nothing or just spaces in any of edittexts).
btnSubmit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
strNum1 = edtl.getText().toString().trim();
strNum2 = edt2.getText().toString().trim();
if (strNum1.length() == 0)
{
showAlert("Please enter Num 1");
}
else if (strNum2.length() == 0)
{
showAlert("Please enter Num 2");
}
else
{
int numvalue1 = Integer.parseInt(strNum1);
int numvalue2 = Integer.parseInt(strNum2);
generateNum (numvalue1, numvalue2); //Call your function for generation of random number here
//do your stuff here
}
}
});
Hope this helps you understand the validation of forms for empty input fields.
P.S: I would recommend you put inputType attribute for your EditTexts if you have not added it already in xml file like:
android:inputType="number"
So you can avoid exception at Integer.parseInt if user enters any alphabet or symbol.
You need to handle NumberFormatException thrown by Integer.valueOf() function
try {
EditText et = findViewById(R.id.fromNum);
String sTextFromET = et.getText().toString();
int fNum = Integer.valueOf(sTextFromET);
EditText et1 = findViewById(R.id.toNum);
String sTextFromET1 = et1.getText().toString();
int sNum = Integer.valueOf(sTextFromET1);
TextView ans = findViewById(R.id.ans);
if(sNum < fNum){
ans.setText(getString(R.string.max_min_error));
}else {
final int random = new Random().nextInt((sNum - fNum) + 1) + fNum;
String ras = Integer.toString(random);
ans.setText(ras);
}
}catch(NumberFormatException e){
Toast.makeText(this, "Invalid Input", Toast.LENGTH_SHORT).show();
}

Buttons text to string

I have an array of buttons which contains two elements.
I'd like to create a string from the text of the buttons.
The thing i am struggling with is the if statement. Basically, it is never firing the toast. Why?
String word2 = "ok";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Button buttons[] = new Button[2];
buttons[0] = (Button) findViewById(R.id.btn);
buttons[1] = (Button) findViewById(R.id.btn2);
buttons[0].setText("o");
buttons[1].setText("k");
buttons[0].setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String word = "";
for (int i = 0; i < 2; i++) {
word += buttons[i].getText().toString();
}
if (word == word2) {
Toast.makeText(getApplicationContext(), "Good",
Toast.LENGTH_LONG).show();
}
}
});
}
Change this:
if (word == word2) {
with this:
if(word.equals(word2)) {
You can't compare String with ==
Write Better Questions (basically questions)
Compare string with .equals() not ==.
Just use if(word.equals(word2) {
Why? The first one is content comparision, but the second one i just
a reference comparision so:
String a = new String("x");
String b = new String("x");
if(a==b){
System.out.println("It wont work");
}else if(a.equals(b)){
System.out.println("It will");
}
Dont ever use new String(), it was just for proof
I must write it.
Change line
for (int i = 0; i < 2; i++) {
into
for (int i = 0; i < buttons.length; i++) {
So your application will be easier to change

Putting double value into TextView

In my Android app I am calculating a double value using values entered into EditTexts and trying to put the answer into a TextView. My code is this:
double scoreDouble;
TextView score;
EditText gpa;
EditText sat;
EditText act;
Button calc;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
gpa = (EditText) findViewById(R.id.gpa);
String gpaString = gpa.getText().toString();
if(gpaString.equals("")){
gpaString = "0";
}
final double gpaDouble = Double.parseDouble(gpaString);
sat = (EditText) findViewById(R.id.sat);
String satString = sat.getText().toString();
if(satString.equals("")){
satString = "0";
}
final int satInt = Integer.parseInt(satString);
act = (EditText) findViewById(R.id.act);
String actString = act.getText().toString();
if(actString.equals("")){
actString = "0";
}
final int actInt = Integer.parseInt(actString);
score = (TextView) findViewById(R.id.score);
calc = (Button) findViewById(R.id.calc);
calc.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if(actInt/36>satInt/2400){
scoreDouble= (0.6*gpaDouble*25)+(0.4*(actInt/36)*100);
String scoreString = Double.toString(scoreDouble);
score.setText("Your score is "+scoreString);
}else{
scoreDouble = (0.6*gpaDouble*25)+(0.4*(satInt/2400)*100);
String scoreString = Double.toString(scoreDouble);
score.setText("Your score is "+scoreString);
}
}
});
}
As of now, when the button is pressed the TextView says: "Your score is 0.0." I feel this has something to do with the fact that I set the default values of the EditTexts to 0. Before I did this, I was getting an error stating NumberFormatException: invalid double: "". If this is the problem, how should I fix it. If that is not the problem, what it?
You define the actInt and satInt as final variables, and they will be assigned to a value only once (when the execution of the onCreate method) and the initial value will be zero as at the begining the edittext contain nothing.
To solve this issue:
move he actInt and satInt from local variables to a field variables and remove the final keyword. (I mean define those variables as a private variables inside the class) and assign the values for the variables inside the onclick Method.
public class test extends Activity {
double scoreDouble;
TextView score;
EditText gpa;
EditText sat;
EditText act;
Button calc;
private int satInt;
private int actInt;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
gpa = (EditText) findViewById(R.id.gpa);
sat = (EditText) findViewById(R.id.sat);
act = (EditText) findViewById(R.id.act);
score = (TextView) findViewById(R.id.score);
calc = (Button) findViewById(R.id.calc);
calc.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String gpaString = gpa.getText().toString();
if (gpaString.equals("")) {
gpaString = "0";
}
double gpaDouble = Double.parseDouble(gpaString);
String satString = sat.getText().toString();
if (satString.equals("")) {
satString = "0";
}
int satInt = Integer.parseInt(satString);
String actString = act.getText().toString();
if (actString.equals("")) {
actString = "0";
}
int actInt = Integer.parseInt(actString);
if (actInt / 36 > satInt / 2400) {
scoreDouble = (0.6 * gpaDouble * 25)
+ (0.4 * (actInt / 36) * 100);
String scoreString = Double.toString(scoreDouble);
score.setText("Your score is " + scoreString);
} else {
scoreDouble = (0.6 * gpaDouble * 25)
+ (0.4 * (satInt / 2400) * 100);
String scoreString = Double.toString(scoreDouble);
score.setText("Your score is " + scoreString);
}
}
});
}
}
You are doing everything on your onCreate method. So all your code is called at the start of your application. At this moment, your EditTexts are empty and your code goes to these parts:
if(gpaString.equals("")){
gpaString = "0";
}
if(actString.equals("")){
actString = "0";
}
if (actString.equals("")) {
actString = "0";
}
Which means that your values gpaDouble, actInt and satInt are equals 0.
Then, you are doing the following:
scoreDouble = (0.6*gpaDouble*25)+(0.4*(satInt/36)*100);
and this:
scoreDouble = (0.6*gpaDouble*25)+(0.4*(satInt/2400)*100);
With the 0 values, your scoreDouble value can only be equal to 0.
To fix it, get your EditTexts' texts in the onClick method of your Button.

calculator with one input edittext android

i am a beginner in android. i am trying to make a calculator with just one input edit text.
when i click + button it doesn't give a sum output. to get a correct ans i have to click the +button after both the entries. like to get a sum i will do it as 1"+" 1"+""=. then it would give 2. here's my code,someoneplease help me.
public void onClick(View v){
double sum=0;
switch(v.getId()){
case R.id.buttonplus:
sum += Double.parseDouble(String.valueOf(textView.getText()));
numberDisplayed.delete(0,numberDisplayed.length());
break;
case R.id.buttonequal:
resultView.setText(String.valueOf(sum));
sum=0;
}
If I understand you correctly, you want the sum to show after you press the "equals" button. If so, then you need to have
sum += Double.parseDouble(String.valueOf(textView.getText()));
in this line also
case R.id.buttonequal:
sum += Double.parseDouble(String.valueOf(textView.getText()));
resultView.setText(String.valueOf(sum));
sum=0;
The second number isn't entered yet when you press the "plus" button so the sum is only the first number. Then you have to press it again to add to sum
So in if equals btn pressed, something like
if (lastOp.equals("sub")
{
sum -= Double.parseDouble(String.valueOf(textView.getText()));
...
}
Example
public class SimpleCalculatorActivity extends Activity
{
//variables needing class scope
double answer = 0, number1, number2;
int operator = 0, number;
boolean hasChanged = false, flag = false;
String display = null;
String display2 = null;
String curDisplay = null;
String calcString = "";
String inputLabel;
String inputString = null;
String inputString2 = null;
String inputString3 = null;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
this.setTitle("Super Duper Calculator");
initButtons();
}
//when button is pressed, send num to calc function
button1.setOnClickListener
(new Button.OnClickListener()
{
public void onClick(View v)
{
inputString = button1.getText().toString();
displayCalc(inputString);
}
}
);
button2.setOnClickListener
(new Button.OnClickListener()
{
public void onClick(View v)
{
inputString = button2.getText().toString();
displayCalc(inputString);
}
}
);
...
//send operator to calc function
addButton.setOnClickListener
(new Button.OnClickListener()
{
public void onClick(View v)
{
calculation(1);
}
}
);
subButton.setOnClickListener
(new Button.OnClickListener()
{
public void onClick(View v)
{
calculation(2);
}
}
);
calcButton.setOnClickListener
(new Button.OnClickListener()
{
public void onClick(View v)
{
calculation(5);
}
}
);
clearButton.setOnClickListener
(new Button.OnClickListener()
{
public void onClick(View v)
{
calculation(6);
}
}
);
}
//function to calculate
public void calculation(int input)
{
number = input;
//see which operator was clicked
switch (number)
{
case 1:
operator = 1;
hasChanged = true;
display = "";
showDisplay("+");
break;
case 2:
operator = 2;
hasChanged = true;
display = "";
showDisplay("-");
break;
case 3:
operator = 3;
hasChanged = true;
display = "";
showDisplay("*");
break;
case 4:
operator = 4;
hasChanged = true;
display = "";
showDisplay("/");
break;
case 5:
number2 = Double.parseDouble(display2);
if(number2 == 0)
{
custErrMsg();
}
else
{
operator();
displayAnswer(answer);
hasChanged = true;
}
break;
case 6:
clear();
break;
default:
clear();
break;
}
}
private void operator()
{
if (operator != 0)
{
if (operator == 1)
{
answer = number1 + number2;
}
else if (operator == 2)
{
answer = number1 - number2;
}
else if (operator == 3)
{
answer = number1 * number2;
}
else if (operator == 4)
{
answer = number1 / (number2);
}
}
}
private void displayCalc(String curValue)
{
String curNum = curValue;
if (!hasChanged)
{
if (display == null)
{
//display number if reset
inputString2 = curNum;
display = inputString2;
showDisplay(display);
}
else
{
//display previous input + new input
inputString2 = inputString2 + curNum;
display = display + curNum;
showDisplay(display);
}
}
else
{
displayNum2(curNum);
}
}
private void displayNum2 (String curValue2)
{
String curNum2;
curNum2 = curValue2;
if (!flag)
{
//display number if reset
inputString3 = curNum2;
display2 = inputString3;
number1 = Double.parseDouble(inputString2);
flag = true;
}
else
{
//display previous input + new input
inputString3 = curNum2;
display2 = display2 + curNum2;
}
showDisplay(inputString3);
}
private void displayAnswer(double curAnswer)
{
String finAnswer = String.valueOf(curAnswer);
TextView textView1 = (TextView) findViewById(R.id.textView1);
textView1.setBackgroundColor(0xffffffff);
textView1.setText(finAnswer);
}
private void showDisplay(String output)
{
inputLabel = output;
TextView textView1 = (TextView) findViewById(R.id.textView1);
textView1.setBackgroundColor(0xffffffff);
if (operator != 0)
{
curDisplay = textView1.getText().toString();
textView1.setText(curDisplay + inputLabel);
}
else
{
textView1.setText(inputLabel);
}
}

Categories

Resources