对不起,对于这样一个简单的问题,但是如何在正在生成的随机数字之间放置一个空格然后发送给setText?用setText在数字之间加一个空格
现在显示########,但我想它显示为#### ####
text = (TextView) findViewById(R.id.tv_randnumber);
text.setText(String.valueOf((int) (Math.random() * 100000000)));
对不起,对于这样一个简单的问题,但是如何在正在生成的随机数字之间放置一个空格然后发送给setText?用setText在数字之间加一个空格
现在显示########,但我想它显示为#### ####
text = (TextView) findViewById(R.id.tv_randnumber);
text.setText(String.valueOf((int) (Math.random() * 100000000)));
我的建议是:
text = (TextView) findViewById(R.id.tv_randnumber);
String random = String.valueOf((int) (Math.random() * 100000000));
String one = random.substring(0, 4);
String two = random.substring(4, 8);
text.setText(one + " " + two);
这必须工作。
这可能是具有百万答对这些问题之一,这里是做到这一点的一种方法:
String string = String.valueOf((int) (Math.random() * 100000000));
string = new StringBuilder(string).insert(4, ' ').toString();
int i=(int)Math.random() * 100000000 ;
int rem= i%10000;
int i=i/10000;
text.setText(String.valueOf(i+" " +rem));
String.format(String, Object...)
是用于访问格式功能的简便方法。第一个参数是一个支持多个标志的“格式字符串”。
用于分组分隔符为大量的标志是,
所以你可以写:
text.setText(String.format("%,d", (int)(Math.random() * 100000000)))
对于所有可用的标志看Formatter
通过这种方式将被使用的语言环境分组(千)分隔符。如果你想自定义此分隔符(例如空格),则需要执行以下操作:
DecimalFormatSymbols dfs = new DecimalFormatSymbols();
dfs.setGroupingSeparator(' ');
DecimalFormat df = new DecimalFormat("###,###", dfs);
text.setText(df.format(Math.random() * 100000000));
Works - text.setText(String.format(“%,d”,(int)(Math.random()* 100000000))) – 2016-03-12 10:41:11
谢谢!很棒! – duggerd 2011-12-17 19:10:33
但有一点需要注意:如果要多次执行此操作(例如在循环中),则可能需要查看更优化的解决方案,以避免过多创建字符串(这里是四个不同的字符串实例用于一个修改)。 – Jave 2011-12-17 19:30:23