我是Android编程的新手,我试图将datepicker中的所有char元素加起来,但没有成功。
这是代码:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final TextView tv = (TextView)findViewById(R.id.textView1);
DatePicker dp = (DatePicker)findViewById(R.id.datePicker1);
final int day = dp.getDayOfMonth();
final int month = dp.getMonth();
final int year = dp.getYear();
Button b = (Button)findViewById(R.id.button1);
b.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int num = 0;
String sdate = String.valueOf(month) + String.valueOf(day) + String.valueOf(year);
char[] c = sdate.toCharArray();
for(int i=0; i<c.length;i++)
{
num+=Integer.valueOf(c[i]);
}
tv.setText(String.valueOf(num));
}
});
}
输出为: 355。
真正的金额必须 20 ,我想这样总结17/06/2013, 所以示例1 + 7 + 0 + 6 + 2 + 0 + 1 + 3 = 20
答案 0 :(得分:3)
for(int i=0; i<c.length;i++) {
num+=Character.getNumericValue(c[i]);
}
答案 1 :(得分:1)
从Integer.valueOf()更改为Character.valueOf()Integer.valueOf(int)取整数,您的char被转换为int并给出ASCII值。
答案 2 :(得分:1)
这将有效
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final TextView tv = (TextView)findViewById(R.id.textView1);
DatePicker dp = (DatePicker)findViewById(R.id.datePicker1);
final int day = dp.getDayOfMonth();
final int month = dp.getMonth();
final int year = dp.getYear();
Button b = (Button)findViewById(R.id.button1);
b.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int num = 0;
String sdate = String.valueOf(month) + String.valueOf(day) + String.valueOf(year);
int[] ee=new int[sdate.length()];
String[] dd=new String[sdate.length()];
for(int i=0;i<sdate.length();i++){
dd[i]=sdate.substring(i,i+1);
ee[i]=Integer.parseInt(dd[i]);
num+=ee[i];
}
tv.setText(String.valueOf(num));
}
});
}