gpt4 book ai didi

java - 在android中将Spinner String值 "20-34"转换为从20到34的整数

转载 作者:行者123 更新时间:2023-12-02 03:11:32 25 4
gpt4 key购买 nike

如何在 android 中将 Spinner 字符串值(例如“20-34”、35-44“等)转换为 20 到 34 的整数、35 到 44 的整数。下面是从 spinner 获取整数值的代码分配分数以便进行数学计算

 public static int age_value(String gender, String ag) {

int b;
b = Integer.parseInt(ag);
if (gender.equals("f")) {
if (20 <= b && b <= 34) {
ageValue = -7;
} else if (35 <= b && b <= 39) {
ageValue = -3;
} else if (40 <= b && b <= 44)
ageValue = 0;
else if (45 <= b && b <= 49)
ageValue = 3;
else if (50 <= b && b <= 54)
ageValue = 6;
else if (55 <= b && b < 59)
ageValue = 8;
else if (60 <= b && b <= 64)
ageValue = 10;
else if (65 <= b && b <= 69)
ageValue = 12;
else if (70 <= b && b <= 74)
ageValue = 14;
else if (75 <= b && b <= 79)
ageValue = 16;

} else if (gender.equals("m")) {
if (20 <= b && b <= 34) {
ageValue = -9;
} else if (35 <= b && b <= 39) {
ageValue = -4;
} else if (40 <= b && b <= 44)
ageValue = 0;
else if (45 <= b && b <= 49)
ageValue = 3;
else if (50 <= b && b <= 54)
ageValue = 6;
else if (55 <= b && b < 59)
ageValue = 8;
else if (60 <= b && b <= 64)
ageValue = 10;
else if (65 <= b && b <= 69)
ageValue = 11;
else if (70 <= b && b <= 74)
ageValue = 12;
else if (75 <= b && b <= 79)
ageValue = 13;

}


return ageValue;


}

下面显示了添加了上述方法的微调器

  int array1 = R.array.gender;
// final String[] gender1 = getResources().getStringArray(R.array.gender);
final ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this.getApplicationContext(), array1, R.layout.simple_spinner_item);
adapter.setDropDownViewResource(R.layout.spinnerdrop);
Gender.setAdapter(adapter);
Gender.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
rowgender = parent.getItemAtPosition(position).toString();


if(rowage!=null && rowgender!=null) {
MainActivity.age_value(rowgender, rowage);
}

Gender.setSelection(position);

}

@Override
public void onNothingSelected(AdapterView<?> parent) {

}

});

但是显示错误

java.lang.NumberFormatException: Invalid int: "20–34"

最佳答案

使用 String split() 方法来做到这一点

String ag = "20-34";
String[] value = ag.split("-");

int b= Integer.parseInt(value[0]);// here value 20
int c= Integer.parseInt(value[1]);// here value 34

然后进行操作

    if (20 <= b && c <= 34) {
ageValue = -7;
} else if
....
....

关于java - 在android中将Spinner String值 "20-34"转换为从20到34的整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40969037/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com