I haven” t przetestował to - ale powinien dać ci ogólny pogląd kierunek, który musisz wziąć.
Najpierw musimy uzyskać tekst:
String input = tv1.getText().toString();
Następnie podzieliliśmy go na każdej linii:
String[] lines = input.split("\n");
Teraz musimy obliczyć wartość:
int total = Integer.parseInt(lines[0].trim()); //We know this is a number.
for(int i = 1; i < lines.length(); i++) {
total = calculate(lines[i].trim(), total);
}
Obliczona metoda powinna wyglądać tak, zakładając, że znamy pierwszą Char
linii jest operatorem:
private int calculate(String input, int total) {
switch(input.charAt(0))
case '+':
return total + Integer.parseInt(input.substring(1, input.length());
case '-':
return total - Integer.parseInt(input.substring(1, input.length());
case '*':
return total * Integer.parseInt(input.substring(1, input.length());
case '/':
return total/Integer.parseInt(input.substring(1, input.length());
}
EDIT
Więc powyżej podano w komentarzu poniżej robi „od lewej do prawej” kalkulacja, ignorując normalnej kolejności (+ i/before + i -).
Poniższa robi obliczania właściwą drogę:
String input = tv1.getText().toString();
input = input.replace("\n", "");
input = input.replace(" ", "");
int total = getValue(input);
Sposób getValue
jest metoda rekurencyjna i powinno to wyglądać tak:
private int getValue(String line) {
int value = 0;
if(line.contains("+")) {
String[] lines = line.split("\\+");
value += getValue(lines[0]);
for(int i = 1; i < lines.length; i++)
value += getValue(lines[i]);
return value;
}
if(line.contains("-")) {
String[] lines = line.split("\\-");
value += getValue(lines[0]);
for(int i = 1; i < lines.length; i++)
value -= getValue(lines[i]);
return value;
}
if(line.contains("*")) {
String[] lines = line.split("\\*");
value += getValue(lines[0]);
for(int i = 1; i < lines.length; i++)
value *= getValue(lines[i]);
return value;
}
if(line.contains("/")) {
String[] lines = line.split("\\/");
value += getValue(lines[0]);
for(int i = 1; i < lines.length; i++)
value /= getValue(lines[i]);
return value;
}
return Integer.parseInt(line);
}
Szczególne przypadki, że metoda rekurencyjna nie obsługuje :
- Jeśli pierwsza liczba jest ujemna, np. -3 + 5 * 8.
- Podwójne operatory, np. 3 * -6 lub 5/-4.
Również rzeczywistości używamy Integers
może dać jakieś „dziwne” wyniki w niektórych przypadkach, jak na przykład 5/3 = 1.
Chcesz pokazać wynik dodawania tych numerów ..? – Mudassir
jaki jest problem? – freshDroid
moje pytanie brzmi, mam wartość 5 + 9 w jednym widoku tekstowym, jak już wspomniałem., Więc jak uzyskać tę wartość, jak tv.getText(). ToString(); –