作者热门文章
- mongodb - 在 MongoDB mapreduce 中,如何展平值对象?
- javascript - 对象传播与 Object.assign
- html - 输入类型 ="submit"Vs 按钮标签它们可以互换吗?
- sql - 使用 MongoDB 而不是 MS SQL Server 的优缺点
如果我以这种方式在 textview 中设置了文本,这不是问题:
tv.setText("" + ANS[i]);
这只是从这种方式获得。
String a = tv.getText().toString();
int A = Integer.parseInt(a);
但是如果在 textView 中设置值。
tv1.setText(" " + X[i] + "\n" + "+" + " " + Y[i]);
是这样的
5
+9
我有问题,这个值如何获取。
最佳答案
我没有对此进行测试 - 但它应该能让您大致了解您需要采取的方向。
为此,我将假设关于 TextView
的文本的一些事情:
TextView
由 "\n"
分隔的行组成。TextView
中可以有可变数量的行,其中都包含 one 运算符和 one 数字。Char
。首先我们得到文本:
String input = tv1.getText().toString();
然后我们将其拆分为每一行:
String[] lines = input.split( "\n" );
现在我们需要计算总值:
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 );
}
方法calculate应该是这样的,假设我们知道一行的第一个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() );
}
编辑
所以上面在下面的评论中说明了“从左到右”的计算,忽略了正常的顺序(+和/在+和-之前)。
以下是正确的计算方式:
String input = tv1.getText().toString();
input = input.replace( "\n", "" );
input = input.replace( " ", "" );
int total = getValue( input );
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 );
}
递归方法无法处理的特殊情况:
此外,我们使用 Integers
在某些情况下可能会产生一些“奇怪”的结果,例如5/3 = 1。
关于android - 如何从 TextView 中获取文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8517730/
我是一名优秀的程序员,十分优秀!