Android basic math in textview - android

I am trying to add two numbers and display them in the textview using this code. The problem here is that it doesn't add the numbers, it just displays the entire string.
CharSequence fnum, snum, symbol;
final TextView CalTextBox = (TextView) findViewById(R.id.MainTextview);
symbol = "+"; // addition selected
fnum = CalTextBox.getText(); // store number into fnum
snum = CalTextBox.getText(); //new number will be added in the code and be stored into snum
CalTextBox.setText(""); // delete whats in the text box
CalTextBox.setText(snum + "" + symbol + "" + fnum); // add two numbers

Well, the '+' operator performs concatenation if used on strings (like in this case). To perform a math operation, you have to convert them to numbers first. I think you can use this:
// Convert the 2 String to integer values
int first = Integer.valueOf(fnum);
int second = Integer.valueOf(snum);
// Compute the sum
int sum = first + second;
// Create the String you can use to display in the TextView
String textToDisplay = String.valueOf(sum);

snum = "2";
fnum = "3";
symbol = "+";
snum + "" + symbol + "" + fnum = "2+3"
Instead you should convert String into integer or double and make appropriate controls such as null or empty, or non-numeric then,
int result = Integer.parseInt(snum) + Integer.parseInt(fnum);
CalTextBox.setText("" + result);

For mathematical operations is best to use int, long or double variable types. Instead of CharSequence use for example int.
to get integer (int) from String (text) use:
int fnum, snum, symbol;
int fnum = Integer.parseInt("10"); or
fnum = Integer.parseInt(CalTextBox.getText());
CalTextBox.setText("" + (snum + symbol + fnum));

Related

string to int,causing app to stop

final EditText ed7 = (EditText)findViewById(R.id.Recycleweight);
final EditText ed8 = (EditText)findViewById(R.id.Nonweight);
final EditText ed11 = (EditText)findViewById(R.id.totalweight);
recy_wt=ed7.getText().toString();
nonrec_wt=ed8.getText().toString();
total_wt=ed11.getText().toString();
int rec = Integer.parseInt(recy_wt);
int nrec = Integer.parseInt(nonrec_wt);
ed11.setText(String.valueOf(rec + nrec));
The input I am giving is,ed7=10kg and ed8=20kg,and it will be displayed in ed11
as 30kg,but the app is unfortunately stopping.
If I am not writing 'kg',it is correctly displaying the totalwt.
But I want to display 'kg' in the answer.
There is already a solution here (can't flag as duplicate)
Find and extract a number from a string
Extract the digit part from the string and then parse it to an integer
Try this out
String regexp = "/^[0-9]+kg$/g"; //It accepts only '<number><kg>' format
int weight = 0;
if (recy_wt.matches(regexp) && nonrec_wt.matches(regex)) {
//It's valid input
Scanner scan = new Scanner(recy_wt);
weight = Integer.parseInt(scan.findInLine("\\d+(\\.\\d+)?"));
Scanner scan = new Scanner(nonrec_wt);
weight += Integer.parseInt(scan.findInLine("\\d+(\\.\\d+)?"));
}
ed11.setText(String.valueOf(weight + "Kg"));
If the only possible unit is kg, then try like this
final EditText ed7 = (EditText)findViewById(R.id.Recycleweight);
final EditText ed8 = (EditText)findViewById(R.id.Nonweight);
final EditText ed11 = (EditText)findViewById(R.id.totalweight);
int weight = 0;
recy_wt=ed7.getText().toString();
nonrec_wt=ed8.getText().toString();
recy_wt = recy_wt.replace("kg","");
nonrec_wt = nonrec_wt.replace("kg","");
weight += Integer.parseInt(recy_wt) + Integer.parseInt(nonrec_wt);
ed11.setText(weight + "kg");
This will work:-
recy_wt=ed7.getText().toString();
nonrec_wt=ed8.getText().toString();
String n=recy_wt.replace("kg","");
String n1=nonrec_wt.replace("kg","");
weight += Integer.parseInt(n) + Integer.parseInt(n1);
ed11.setText(weight + "kg");
storing the replaced one in a string and then converting to int will help.

I have 4 textviews which take their values from spinner. If TextView 3 and 4 are blank then I need to copy values from position 1 & 2

I have 4 textviews which take their values from dropdown list (spinner) selected at previous screen.
There can be either 2 or 4 numbers/letters as result of this selection.
The first position will always be a number and the second position will always be a letter. The third position can be a number or blank and the fourth position can be a letter or blank.
If position 3 and position 4 are blank then I need to make them equal to positions 1 & 2 respectively.
String myGrade = intent.getStringExtra("parameter_name_grade");
// above takes value of 'myGrade' from spinner selection at previous screen
String mDisplayGradeNumberEff = (" " + myGrade.charAt(0));
TextView displayGradeNumberEff = (TextView) findViewById(R.id.gradeNumberEffTV);
displayGradeNumberEff.setText(mDisplayGradeNumberEff);
String mDisplayGradeLetterEff = (" " + myGrade.charAt(1));
TextView displayGradeLetterEff = (TextView) findViewById(R.id.gradeLetterEffTV);
displayGradeLetterEff.setText(mDisplayGradeLetterEff);
// above works correctly
// from here down only works when a character is present in both positions
// if positions 3(2) and 4(3) are empty app stops running.
String mDisplayGradeNumberDia = (" " + myGrade.charAt(2));
if (mDisplayGradeNumberDia.isEmpty()) {
mDisplayGradeNumberDia = mDisplayGradeNumberEff;
}
TextView displayGradeNumberDia = (TextView) findViewById(R.id.gradeNumberDiaTV);
displayGradeNumberDia.setText(mDisplayGradeNumberDia);
String mDisplayGradeLetterDia = (" " + myGrade.charAt(3));
if (mDisplayGradeLetterDia.isEmpty()) {
mDisplayGradeLetterDia = mDisplayGradeLetterEff;
}
TextView displayGradeLetterDia = (TextView) findViewById(R.id.gradeLetterDiaTV);
displayGradeLetterDia.setText(mDisplayGradeLetterDia);
}
I Guess you have a array out of bounds exception, please provide Logcat....
Check if "myGrade" has 3/4 Characters, if it does not you can't read them with charAt(3)...
You can check the length of the String with "myGrade.length()"
When I asked this question I was fairly new to the site and didn't understand that I should post back the solution for future reference. Solution below worked so thanks to rocket for your help and sorry for the delay!
int myGradeLength = mGrade.length();
if (myGradeLength != 4) {
mDisplayGradeNumberEff = ("" + mGrade.charAt(0));
mDisplayGradeLetterEff = ("" + mGrade.charAt(1));
mDisplayGradeNumberDia = ("" + mGrade.charAt(0));
mDisplayGradeLetterDia = ("" + mGrade.charAt(1));
} else {
mDisplayGradeNumberEff = ("" + mGrade.charAt(0));
mDisplayGradeLetterEff = ("" + mGrade.charAt(1));
mDisplayGradeNumberDia = ("" + mGrade.charAt(2));
mDisplayGradeLetterDia = ("" + mGrade.charAt(3));
}

How can I effectively replace one or more characters

I have a String separated by commas as follows
1,2,4,6,8,11,14,15,16,17,18
This string is generated upon user input. Suppose the user wants to remove any of the numbers, I have to rebuild the string without the specified number.
If the current string is:
1,2,4,6,8,11,14,15,16,17,18
User intents to remove 1, the final string has to be:
2,4,6,8,11,14,15,16,17,18
I tried to achieve this using the following code:
//String num will be the number to be removed
old = tv.getText().toString(); //old string
newString = old.replace(num+",",""); //will be the new string
This might be working sometimes but it is sure that it won't work for the above example I have shown, if I try to remove the 1, it also removes the last part of 11, because there also exists 1.
well you can use this. Its the most simplest approach i can think of:
//String num will be the number to be removed
old=","+tv.getText().toString()+",";//old string commas added to remove trailing entries
newString=old.replace(","+num+",",",");// will be the new string
newString=newString.substring(1,newString.length()-1); // removing the extra commas added
This would work for what you want to do. I have added a comma at the start and end of your string so that you can also remove the first and last entries too.
You can split the string first and check for the number where you append those value that is not equivalent to the number that will get deleted;
sample:
String formated = "1,2,4,6,8,11,14,15,16,17,18";
String []s = formated.split(",");
StringBuilder newS = new StringBuilder();
for(String s2 : s)
{
if(!s2.equals("1"))
newS.append(s2 + ",");
}
if(newS.length() >= 1)
newS.deleteCharAt(newS.length() - 1);
System.out.println(newS);
result:
2,4,6,8,11,14,15,16,17,18
static public String removeItemFromCommaDelimitedString(String str, String item)
{
StringBuilder builder = new StringBuilder();
int count = 0;
String [] splits = str.split(",");
for (String s : splits)
{
if (item.equals(s) == false)
{
if (count != 0)
{
builder.append(',');
}
builder.append(s);
count++;
}
}
return builder.toString();
}
String old = "1,2,4,6,8,11,14,15,16,17,18";
int num = 11;
String toRemove = "," + num + "," ;
String oldString = "," + old + ",";
int index = oldString.indexOf(toRemove);
System.out.println(index);
String newString = null;
if(index > old.length() - toRemove.length() + 1){
newString = old.substring(0, index - 1);
}else{
newString = old.substring(0, index) + old.substring(index + toRemove.length() -1 , old.length());
}
System.out.println(newString);

Delete characters in string until /r/n

I have long string that at some part has
some text + "PHOTO;ENCODING=BASE64;TYPE=JPEG:" + some characters that generate randomly + /r/n...
I am wondering how can I delete part from
"PHOTO;ENCODING=BASE64;TYPE=JPEG:" untill /r/n
so I will be left only with
some text + /r/n ?
my code so far:
if (string.contains("PHOTO;ENCODING=BASE64;TYPE=JPEG:") {
string = string.replace("PHOTO;ENCODING=BASE64;TYPE=JPEG:", "");
}
but this obviously would not replace my random generated chars, only "PHOTO;ENCODING=BASE64;TYPE=JPEG:".
How do I "loop through" string from "PHOTO;ENCODING=BASE64;TYPE=JPEG:" untill /r/n ?
final String input = "some text + PHOTO;ENCODING=BASE64;TYPE=JPEG: + some characters that generate randomly + /r/n"
final int index = input.indexOf("PHOTO;ENCODING=BASE64;TYPE=JPEG:");
if (index != -1)
{
final String result = input.subString(0, index) + System.getProperty("line.separator")
}
why dont you try following
1) Get the index of "PHOTO;ENCODING=BASE64;TYPE=JPEG:". and call it idx
2)If idx != -1 then take substring of original string using str.subString(0,idx) and call it newStr
3)return newStr+(str.endsWith("\r\n")?"\r\n":"")

Simple If Statement

I am trying to pass two variables from one screen to another. From the previous screeen you click a button, 1 or 2 and it passes that value on. It also passes the value 2 as the correct value. I know they are both working as I output each variable on the next screen. Here is the code. It always outputs wrong though.
Intent i = getIntent();
Bundle b = i.getExtras();
String newText = b.getString("PICKED");
String correct = b.getString("CORRECT");
TextView titles = (TextView)findViewById(R.id.TextView01);
if(newText == correct){
titles.setText("Correct" + newText + " " + correct + "");
}
else{
titles.setText("Wrong" + newText + " " + correct + "");
}
because you are not comparing the string. you are comparing if both are pointing to same object.
to compare string use
if(nexText.equals(correct))
if(newText == correct)
This will always be false. To compare the contents of two Strings character by character, use the .equals method:
if( newText.equals(correct) )
Using == on objects in Java means you are comparing the values of the memory address stored in these pointers/references. Since they are different String objects, they will never have the same address.
You don't compare Strings this way, rewrite code this way to get things done:
Intent i = getIntent();
Bundle b = i.getExtras();
String newText = b.getString("PICKED");
String correct = b.getString("CORRECT");
TextView titles = (TextView)findViewById(R.id.TextView01);
if(newText.equals(correct)){
titles.setText("Correct" + newText + " " + correct + "");
}
else{
titles.setText("Wrong" + newText + " " + correct + "");
}

Categories

Resources