Answer the question
In order to leave comments, you need to log in
I get an error when I try to get a number from a string?
Hello, I am writing a calculator and I have such a problem. When I write -2 minus 2, I should output -4, but for some reason an error occurs. I just can’t understand why, I tried to remove the minus, but still.
Here is the layout
The main numbers are large this is the TextView in mainactivity.java it is written to the display variable
When the equals button is clicked the method is called
// do result of two numbers
public void onEqual (View v) {
display.setText(makeResult()); // set TextView result of computation
}
// make result of two numbers
private String makeResult () {
double one; // one number
double two; // two number
double result; // result of two numbers
String dis = display.getText().toString(); // take text from TextView for more comfortable(manipulation)
one = Double.parseDouble(dis.substring(0, dis.indexOf(operator) - 1)); // берём первое число от начала строки до оператора(оператор не берём)
two = Double.parseDouble(dis.substring(dis.indexOf(operator) + 2, dis.length())); // берём второе число после оператора и до конца строки
switch (operator) {
case "+":
result = one + two;
break;
case "-":
result = one - two;
break;
case "/":
result = one / two;
break;
case "x":
result = one * two;
break;
default:
result = 0;
}
operator = "";
return new DecimalFormat("#.##########").format(result); // do format of result ( 5.0 -> 5 )
}
Answer the question
In order to leave comments, you need to log in
So why does an error occur, why does he not want to eat a number with a negative sign and make a minus with it with the second number? (-2 - 2) will return the application crash
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question