如果我以这种方式在textview中设置文本,这不是问题:
tv.setText("" + ANS[i]);
Run Code Online (Sandbox Code Playgroud)
这简直就是这样.
String a = tv.getText().toString();
int A = Integer.parseInt(a);
Run Code Online (Sandbox Code Playgroud)
但是在textView中设置值的情况下.
tv1.setText(" " + X[i] + "\n" + "+" + " " + Y[i]);
Run Code Online (Sandbox Code Playgroud)
这是这样的
5
+9
Run Code Online (Sandbox Code Playgroud)
我有问题,这个值怎么弄.
kas*_*rch 48
我没有测试过这个 - 但它应该让你对你需要采取的方向有一个大概的了解.
为了实现这个目的,我将假设一些关于以下内容的文章TextView:
TextView由带分隔行"\n".TextView其中所有行都包括一个运算符和一个数字.Char行.首先我们得到文字:
String input = tv1.getText().toString();
Run Code Online (Sandbox Code Playgroud)
然后我们为每一行拆分它:
String[] lines = input.split( "\n" );
Run Code Online (Sandbox Code Playgroud)
现在我们需要计算总价值:
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 );
}
Run Code Online (Sandbox Code Playgroud)
方法计算应该如下所示,假设我们知道第一Char行是运算符:
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() );
}
Run Code Online (Sandbox Code Playgroud)
编辑
因此,以下评论中所述的上述"从左到右"计算,忽略正常顺序(+和/前+和 - ).
以下以正确的方式进行计算:
String input = tv1.getText().toString();
input = input.replace( "\n", "" );
input = input.replace( " ", "" );
int total = getValue( input );
Run Code Online (Sandbox Code Playgroud)
该方法getValue是一个递归方法,它应该如下所示:
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 );
}
Run Code Online (Sandbox Code Playgroud)
递归方法无法处理的特殊情况:
此外,我们正在使用的事实Integers可能会在某些情况下给出一些"奇数"结果,例如5/3 = 1.
| 归档时间: |
|
| 查看次数: |
139788 次 |
| 最近记录: |