很抱歉问了这么一个简单的问题,但是如何在生成然后发送到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();
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));
int i=(int)Math.random() * 100000000 ;
int rem= i%10000;
int i=i/10000;
text.setText(String.valueOf(i+" " +rem));