This question already has an answer here:
android number format exception
(1 answer)
Closed 7 years ago.
This is my calculator app, I know that NumberFormat are caused when we try convert string to numerical type.I have also surrounded them by TRY/CATCH but i cant seem to get them as INT values. Here in my app, I'm getting the strings in the textview and trying to perform operations on them.
Can anyone suggest an alternative approach for the problem?
Here's the code:
public class MainActivity extends AppCompatActivity {
private static String TAG = MainActivity.class.getSimpleName();
private static String GAT = "Tag";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
ArrayList<String> arrayList = new ArrayList<String>();
String stringOne = " ";
String stringTwo = " ";
public void onClick1(View view) {
//Getting Input from TextView
TextView inputText = (TextView) findViewById(R.id.inputTextView);
Button button = (Button) view;
//Store as String from button press
stringOne = (String) button.getText().toString();
Log.d(TAG, stringOne);
//For entering multiple values
if (!stringOne.contains("+") && !stringOne.contains("-") && !stringOne.contains("/") && !stringOne.contains("*")) {
//Concat if it has multiple digits to original string
stringTwo = stringTwo + stringOne;
Log.d(TAG, stringTwo);
//Remove the last string and place as StringTwo
if (arrayList.size() > 0) {
//Get last position in the array
arrayList.remove((arrayList.size() - 1));
}
arrayList.add(stringTwo);
} else {
//For operators add two times because we removed the previous index
arrayList.add(stringOne);
arrayList.add(stringOne);
//Clear
stringTwo = " ";
Toast.makeText(this, stringOne, Toast.LENGTH_LONG).show();
Log.d(TAG, stringOne);
// Log.d("Veer",stringTwo);
}
//Add to TextView
inputText.setText(inputText.getText().toString()+stringOne);
//inputText.setText(arrayList.toString());
}
public void calculate(View view) {
TextView outputText = (TextView) findViewById(R.id.outputTextView);
int result = 0;
int list = arrayList.size();
while (list != 1) {
if (list > 3) {
//Considering the equation to be like 4+5*5-2/4, Get the third operator, if * and /, then multiply
if (arrayList.get(3).contains("*") || arrayList.get(3).contains("/")) {
if (arrayList.get(3).contains("*")) {
result = Integer.parseInt(arrayList.get(2)) * Integer.parseInt(arrayList.get(4));
} else if (arrayList.get(3).contains("/")) {
result = Integer.parseInt(arrayList.get(2)) / Integer.parseInt(arrayList.get(4));
}
arrayList.remove(2);
arrayList.remove(2);
arrayList.remove(2);
arrayList.add(2, Integer.toString(result));
list = arrayList.size();
} else {
//Vice versa, here for + and - ,replace 1st and 2nd digit
if (arrayList.get(1).contains("+")) {
result = Integer.parseInt(arrayList.get(0)) + Integer.parseInt(arrayList.get(2));
}
if (arrayList.get(1).contains("-")) {
result = Integer.parseInt(arrayList.get(0)) - Integer.parseInt(arrayList.get(2));
}
if (arrayList.get(1).contains("*")) {
result = Integer.parseInt(arrayList.get(0)) * Integer.parseInt(arrayList.get(2));
}
if (arrayList.get(1).contains("/")) {
result = Integer.parseInt(arrayList.get(0)) / Integer.parseInt(arrayList.get(2));
}
arrayList.remove(0);
arrayList.remove(0);
arrayList.remove(0);
arrayList.add(0, Integer.toString(result));
list = arrayList.size();
}
}
else
{
//If size is 3
if (arrayList.get(1).contains("+")) {
result = Integer.parseInt(arrayList.get(0)) + Integer.parseInt(arrayList.get(2));
}
if (arrayList.get(1).contains("-")) {
result = Integer.parseInt(arrayList.get(0)) - Integer.parseInt(arrayList.get(2));
}
if (arrayList.get(1).contains("*")) {
result = Integer.parseInt(arrayList.get(0)) * Integer.parseInt(arrayList.get(2));
}
if (arrayList.get(1).contains("/")) {
result = Integer.parseInt(arrayList.get(0)) / Integer.parseInt(arrayList.get(2));
}
arrayList.remove(0);
arrayList.remove(0);
arrayList.remove(0);
arrayList.add(0, Integer.toString(result));
list = arrayList.size();
}
}
outputText.setText(Integer.toString(result));
}
public void clearView(View view) {
TextView input = (TextView)findViewById(R.id.inputTextView);
TextView output = (TextView)findViewById(R.id.outputTextView);
stringOne = "";
stringTwo = "";
input.setText("");
output.setText("");
arrayList.clear();
}
}
You need to catch exception whenever you convert string to numerical type. If it throw an exception then you return. And if no exception, you continue to perform operations on them.
String text = "";
int num;
try {
num = Integer.parseInt(text);
// text is a number");
} catch (NumberFormatException e) {
Toast.makeText(MainActivity.this, "Can not parse string to int: " + text,Toast.LENGTH_LONG).show();
// text is not a number";
// Show Log or make a Toast here to easy see when String is not Int format. After that find the reason why text is not int format
}
Hope this help
float num1 = 0;
float num2 = 0;
float result = 0;
num1 = Float.parseFloat(etNum1.getText().toString());
num2 = Float.parseFloat(etNum2.getText().toString());
result = num1 * num2 ;
Log.e("Result",""+result);
Hope it helps.
Related
This question already has answers here:
Convert String to operator(+*/-) in java
(5 answers)
Closed 4 years ago.
How I convert String containing Mathematic arithmetic operation's like "10 + 20 - 25", I am getting String from EditText,I want to convert get the Result of operation.
Here is my code to resolve your problem:
public class ExecuteHandler {
private static Character[] OPERATORS = { '/', '*', '+', '-' };
private static final String REGEXOPERATORS = "[/+,-,/*,//,-]";
private static final String REGEXDIGITS = "(\\d+)";
private ArrayList<Character> operators = new ArrayList<>();
private ArrayList<Integer> digits = new ArrayList<>();
public String execute(String math) {
StringBuilder result = new StringBuilder();
try {
getDigits(math);
getOperators(math);
getNextOperator(operators);
for (Integer digit : digits) {
result.append(String.valueOf(digit));
}
} catch (ArithmeticException | IndexOutOfBoundsException e) {
return "ERROR";
}
return result.toString().isEmpty() ? "ERROR" : result.toString();
}
public void clear() {
operators.clear();
digits.clear();
}
private void getNextOperator(ArrayList<Character> operators) {
for (Character op : OPERATORS) {
for (int i = 0; i < operators.size(); i++) {
if (operators.get(i) == '/') {
operators.remove(i);
digits.set(i, (digits.get(i) / digits.get(i + 1)));
digits.remove(i + 1);
i -= 1;
}
}
for (int i = 0; i < operators.size(); i++) {
if (operators.get(i) == '*') {
operators.remove(i);
digits.set(i, (digits.get(i) * digits.get(i + 1)));
digits.remove(i + 1);
i -= 1;
}
}
for (int i = 0; i < operators.size(); i++) {
if (operators.get(i) == '+') {
operators.remove(i);
digits.set(i, (digits.get(i) + digits.get(i + 1)));
digits.remove(i + 1);
i -= 1;
}
}
for (int i = 0; i < operators.size(); i++) {
if (operators.get(i) == '-') {
operators.remove(i);
digits.set(i, (digits.get(i) - digits.get(i + 1)));
digits.remove(i + 1);
i -= 1;
}
}
}
}
private void getDigits(String math) {
Pattern r = Pattern.compile(REGEXDIGITS);
Matcher m = r.matcher(math);
while (m.find()) {
int t = Integer.parseInt(math.substring(m.start(), m.end()));
digits.add(t);
}
}
private void getOperators(String math) {
Pattern r = Pattern.compile(REGEXOPERATORS);
Matcher m = r.matcher(math);
while (m.find()) {
operators.add(math.charAt(m.start()));
}
}
}
Call method execute with input is string like "10 + 20 - 25:", the result will be a string of value (if success) or ERROR (if any syntax error).
I have created a list view in which I have a product name, price and quantity for each list item. I want to get the sum of total quantity, but I am not able to do so.
How can I do it?
The code I have used using product list: adapter code
private void setTotalQuantity(TextView textview)
{
for(int i = 0 ; i< dataSet.size();i++)
{
totalquantity = totalquantity+Integer.parseInt(dataSet.get(i).getProductQuantity());
totalbill = totalbill+Integer.parseInt(dataSet.get(i).getProductPrice()) * Integer.parseInt(dataSet.get(i).getProductQuantity());
}
}
// add or subtraction button
private void subtractQuantity(final ImageView imageView, final TextView textView) {
String qty = textView.getText().toString();
if (Integer.parseInt(qty) == 0)
{
imageView.setClickable(false);
} else {
imageView.setClickable(true);
qty = Integer.parseInt(qty) - 1 + "";
textView.setText(qty);
data.setProductQuantity(qty);
setTotalQuantity(txtQtyAll);
}
}
private void AddQuantity(final ImageView add, final TextView textView, final ImageView minus) {
String qty = textView.getText().toString();
qty = Integer.parseInt(qty) + 1 + "";
textView.setText(qty);
data.setProductQuantity(qty);
setTotalQuantity(txtQtyAll);
if(Integer.parseInt(qty) >0)
{
minus.setClickable(true);
}
}
getting null pointer exception
http://prntscr.com/ecau0x
// updated code
private void subtractQuantity(final ImageView imageView, final TextView textView) {
String qty = textView.getText().toString();
if (Integer.parseInt(qty) == 0)
{
imageView.setClickable(false);
} else {
imageView.setClickable(true);
qty = Integer.parseInt(qty) - 1 + "";
textView.setText(qty);
data.setProductQuantity(qty);
setTotalQuantity(txtQtyAll);
}
}
and
public AdapterProductListing(List<ProductModel> dataModels, Context context, TextView quantity) {
this.dataSet = dataModels;
this.mContext = context;
this.txtQtyAll = quantity;
}
txtQtyAll is the textview which I got from activity
try this
int totalQuantity=0;
for(int i = 0 ; i<products.size();i++)
totalQuantity+=Integer.valueOf(products.get(i).getQuantity());
}
It would be easier if you showed all the code that's involved. Are you trying to get the total price of all products?
Assuming you initialized "int total" already and the method getProductPrice() is ok, you can do this:
total += Integer.parseInt(products.get(i).getProductPrice());
Check your error logs as well. Hope this helps.
for(int i = 0 ; i<products.size();i++)
{
totalprice = totalprice+Integer.parseInt(products.get(i).getProductPrice());
totalquantity = totalquantity+Integer.parseInt(products.get(i).getProductQuantity());
totalbill = totalbill+Integer.parseInt(products.get(i).getProductPrice() * products.get(i).getProductQuantity());
}
try this
I populates cart items into the list using cursor adapter. My ListView item has
Price TextView
Product Name TextView
Count TextView
Increment Button
Decrement Buttton
When I click the increment / decrement button the value is incremented/ decremented in a certain condition of AFTER TOUCHING THE LISTVIEW ROW,otherwise the count is not changed.
In some case, if I click the 1st row increment button ,item count is incremented in 2nd row.
NOTE:
1. I am populating List using Cursor Adapter.
2. Using Increment & Decrement clicklistener in activity class.
Here is my code:
cartList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(final AdapterView<?> parent, View itemView, final int position, final long rowId) {
txt_cartProduct = (TextView) itemView.findViewById(R.id.cartProduct);
txt_cartQuantity = (TextView) itemView.findViewById(R.id.cartQuantity);
txt_cartPrice = (TextView) itemView.findViewById(R.id.cartPrice);
txt_cartPriceDum = (TextView) itemView.findViewById(R.id.cartPriceDum);
txt_cartCount = (TextView) itemView.findViewById(R.id.cartCount);
img_ivDecrease = (ImageView) itemView.findViewById(R.id.ivDecrease);
img_ivIncrease = (ImageView) itemView.findViewById(R.id.ivIncrease);
but_addTowish = (Button) itemView.findViewById(R.id.addTowish);
but_remove = (Button) itemView.findViewById(R.id.remove);
img_ivIncrease.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
strPrice = txt_cartPrice.getText().toString();
price = Integer.parseInt(strPrice);
int counter = 0;
try {
counter = Integer.parseInt(txt_cartCount.getText().toString());
} catch (NumberFormatException e) {
e.printStackTrace();
}
counter++;
if (counter > 0) {
txt_cartCount.setText(Integer.toString(counter));
txt_cartPrice.setVisibility(View.GONE);
txt_cartPriceDum.setVisibility(View.VISIBLE);
quantity = txt_cartCount.getText().toString();
total = (Integer.parseInt(quantity)) * (price);
netA = String.valueOf(total);
sum += price;
if (sum == 0) {
netAmount = Integer.parseInt(txt_cartPriceDum.getText().toString());
}
netAmount = sum;
Log.e("Sum is", String.valueOf(sum));
txt_cartPriceDum.setText(String.valueOf(total));
cartCount = Integer.parseInt(quantity);
Toast.makeText(context, "netAmount" + netAmount + "\n" + "Total" + total, Toast.LENGTH_SHORT).show();
if (counter == 1) {
cartPrice = price;
cartSum = sum;
}
if (counter == 0) {
cartPrice = 0;
cartSum = 0;
cartCount = 0;
Toast.makeText(context, "Minimum Item is 1", Toast.LENGTH_SHORT).show();
}
int count_check = 1;
if (count_check >= position) {
count_check++;
} else if (count_check == 0) {
Toast.makeText(context, "Minimum Item is 1", Toast.LENGTH_SHORT).show();
}
}
}
});
img_ivDecrease.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
strPrice = txt_cartPrice.getText().toString();
price = Integer.parseInt(strPrice);
int counter = 0;
try {
counter = Integer.parseInt(txt_cartCount.getText().toString());
} catch (NumberFormatException e) {
e.printStackTrace();
}
counter--;
if (counter > 0) {
txt_cartCount.setText(Integer.toString(counter));
txt_cartPrice.setVisibility(View.GONE);
txt_cartPriceDum.setVisibility(View.VISIBLE);
quantity = txt_cartCount.getText().toString();
total = (Integer.parseInt(quantity)) * (price);
netA = String.valueOf(total);
sum -= price;
if (sum == 0) {
netAmount = Integer.parseInt(txt_cartPriceDum.getText().toString());
}
Log.e("Sum - is", String.valueOf(sum));
txt_cartPriceDum.setText(String.valueOf(total));
cartCount = Integer.parseInt(quantity);
Toast.makeText(context, "netAmount" + netAmount + "\n" + "Total" + total, Toast.LENGTH_SHORT).show();
if (counter == 1) {
cartPrice = price;
cartSum = sum;
}
if (counter == 0) {
cartPrice = 0;
cartSum = 0;
cartCount = 0;
}
}
}
});
}
});
You can use setTag() and getTag() methods for saving the counter value in each list item.
Refer this answer for more details.
I'm trying to tell if an android int is null by using If/Else
public void onClick(View v) {
EditText min = (EditText) findViewById(R.id.EditText01);
EditText max = (EditText) findViewById(R.id.maxnum);
EditText res = (EditText) findViewById(R.id.res);
int myMin = Integer.parseInt(min.getText().toString());
int myMax = Integer.parseInt(max.getText().toString());
String minString = String.valueOf(myMin);
String maxString = String.valueOf(myMax);
int f = (int) ((Math.random()*(myMax-myMin+1))+myMin);
if (minString.equals(""))
{
// Do Nothing
}
if (maxString.equals(""))
{
// Do Nothing
}
res.setText(String.valueOf(f));
There are no any errors, but when I'm running the app its crashing when im pressing the button.
I'm also trying to use null instead of "":
if (minString.equals(null))
{
// Do Nothing
}
if (maxString.equals(null))
{
// Do Nothing
}
And i have a crash.
Please help me!!!
public boolean equals (Object object)
Compares the specified object to this string and returns true if they are equal. The object must be an instance of string with the same characters in the same order.
So its returning error so if you want to check if its null then use == operator on the object.
if (maxString == null )
Use
int myMin = 0;
int myMax = 0;
if(min.getText().toString()!="")
myMin = Integer.parseInt(min.getText().toString());
if(max.getText().toString()!="")
myMax = Integer.parseInt(max.getText().toString());
String minString = String.valueOf(myMin);
String maxString = String.valueOf(myMax);
int f = (int) ((Math.random()*(myMax-myMin+1))+myMin);
if (minString.equals(""))
{
// Do Nothing
}
if (maxString.equals(""))
{
// Do Nothing
}
do if (maxString == null )
{
// do something
}
int variables can't be null
If a null is to be converted to int, then it is the converter which decides whether to set 0, throw exception, or set another value (like Integer.MIN_VALUE)
So if you convert int to string again you cannot get null value.
check = input.getText().toString();
try {
if (!check.equals("null")) {
int max = Integer.parseInt(input.getText().toString());
int constant1 = 1;
int constant2 = 1;
int nextNumber = 0;
int count = 0;
String fibResult = "";
for (int i = 0; i <= max; i++) {
fibResult += "F" + count + "=" + nextNumber + "\n";
constant1 = constant2;
constant2 = nextNumber;
nextNumber = constant1 + constant2;
count++;
}
dspResults.setText("\n" + fibResult);
} else {
dspResults.setVisibility(View.VISIBLE);
dspResults.setText("Invalid");
dspResults.setText(Gravity.CENTER);
dspResults.setTextColor(Color.DKGRAY);
}
} catch (IllegalArgumentException e) {
e.printStackTrace();
}
public void onClick(View v) {
EditText min = (EditText) findViewById(R.id.EditText01);
EditText max = (EditText) findViewById(R.id.maxnum);
EditText res = (EditText) findViewById(R.id.res);
int myMin = Integer.parseInt(min.getText().toString());
int myMax = Integer.parseInt(max.getText().toString());
String minString = String.valueOf(myMin);
String maxString = String.valueOf(myMax);
int f = (int) ((Math.random()*(myMax-myMin+1))+myMin);
{
if (minString.equals(""))
{
// Do Nothing
res.setText(String.valueOf(f));
return false;
}
else if (maxString.equals(""))
{
// Do Nothing
res.setText(String.valueOf(f));
return false;
}
else
res.setText(String.valueOf(f));
return true ;
}
The program draws two digits, and the sign. IF statement checks to see if it has been drawn + / -. If it draws + add, if - is subtraction.
Draw works.
Then the user is given the result of the task. And here is the problem.
If you give a result which is in the "result". Function if something does. If you entered an incorrect answer is displayed Toast: Try Again.
The problem is that sometimes as to give a good result is is displayed Try Again.
How to eliminate this problem? Might different check?
Code:
private String sign;
private int numberOne, numberTwo, result = 0;
private int charsEntered = 0;
private EditText et;
private Button ok;
String[] CHAR = { "+", "-" };
Random intGen = new Random();
CaptchaInterface.OnCorrectListener mCorrectListener;
public void setOnCorrectListener(CaptchaInterface.OnCorrectListener listener) {
mCorrectListener = listener;
}
public EasyMathCaptcha(Context context) {
super(context);
getWindow().requestFeature(Window.FEATURE_NO_TITLE);
}
public static int randomOne() {
Random generator = new Random();
int x = generator.nextInt(10);
return x;
}
public static int randomTwo() {
Random generator = new Random();
int x = generator.nextInt(10);
return x;
}
public void onCreate(Bundle icicle) {
setContentView(R.layout.all_math_captcha);
sign = (CHAR[Math.abs(intGen.nextInt() % 2)]);
numberOne = randomOne();
numberTwo = randomTwo();
TextView display = (TextView) findViewById(R.id.tvRandomTask);
display.setText(numberOne + " " + sign + " " + numberTwo);
if ((CHAR[Math.abs(intGen.nextInt() % 2)]).equals("+")) {
result = (numberOne + numberTwo);
} else if ((CHAR[Math.abs(intGen.nextInt() % 2)]).equals("-")) {
result = (numberOne - numberTwo);
}
et = (EditText) findViewById(R.id.etTask);
ok = (Button) findViewById(R.id.btAgree);
ok.setOnClickListener(this);
}
public void onClick(View arg0) {
// TODO Auto-generated method stub
try {
charsEntered = Integer.parseInt(et.getText().toString());
} catch (NumberFormatException nfe) {
Toast.makeText(et.getContext(), "That's not a number!",
Toast.LENGTH_SHORT).show();
}
if (charsEntered == result) {
if (mCorrectListener != null)
mCorrectListener.onCorrect();
dismiss();
} else if (charsEntered != result) {
Toast.makeText(et.getContext(), "Try again!", Toast.LENGTH_SHORT)
.show();
}
}
}
The error is in the following code:
if ((CHAR[Math.abs(intGen.nextInt() % 2)]).equals("+")) {
result = (numberOne + numberTwo);
} else if ((CHAR[Math.abs(intGen.nextInt() % 2)]).equals("-")) {
result = (numberOne - numberTwo);
}
You are using the random number generator which can give you results different than what it gave the first time.
Change it to:
if (sign.equals("+")) {
result = (numberOne + numberTwo);
} else if (sign.equals("-")) {
result = (numberOne - numberTwo);
}