You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android中如何将if-else判断的文本值存入数组?

解决方案

方式一:直接在条件分支中给数组赋值

先定义一个String类型数组(示例为存储单个结果的数组,可根据需求调整长度),把原本setText的赋值逻辑替换为数组元素赋值:

// 定义数组,这里以存储单个匹配结果为例
String[] resultArray = new String[1];

if (fifth < 100 && fifth >= 96.5) 
    resultArray[0] = "1.00";
else if (fifth < 97 && fifth >= 92.5) 
    resultArray[0] = "1.25";       
else if (fifth < 93 && fifth >= 88.5) 
    resultArray[0] = "1.50";
else if (fifth < 89 && fifth >= 84.5) 
    resultArray[0] = "1.75";
else if (fifth < 85 && fifth >= 81.5) 
    resultArray[0] = "2.00";
else if (fifth < 82 && fifth >= 78.5) 
    resultArray[0] = "2.25";
else if (fifth < 79 && fifth >= 75.5) 
    resultArray[0] = "2.50";
else if (fifth < 76 && fifth >= 72.5) 
    resultArray[0] = "2.75";
else if (fifth < 73 && fifth >= 69.5) 
    resultArray[0] = "3.00";
else if (fifth < 70 && fifth >= 0) 
    resultArray[0] = "5.00";
else
    resultArray[0] = "NE";

// 如果之后仍需要设置TextView文本,可保留此调用
fivet.setText(resultArray[0]);

方式二:预先存储所有输出值到数组,按条件匹配取值

先把所有可能的输出值存入数组,再通过条件判断找到对应索引的元素,这种方式便于统一维护所有结果:

// 预先定义所有输出值,顺序和条件分支一一对应
String[] gradeValues = {"1.00", "1.25", "1.50", "1.75", "2.00", "2.25", "2.50", "2.75", "3.00", "5.00", "NE"};
String matchedResult = "NE"; // 默认结果

if (fifth < 100 && fifth >= 96.5) 
    matchedResult = gradeValues[0];
else if (fifth < 97 && fifth >= 92.5) 
    matchedResult = gradeValues[1];       
else if (fifth < 93 && fifth >= 88.5) 
    matchedResult = gradeValues[2];
else if (fifth < 89 && fifth >= 84.5) 
    matchedResult = gradeValues[3];
else if (fifth < 85 && fifth >= 81.5) 
    matchedResult = gradeValues[4];
else if (fifth < 82 && fifth >= 78.5) 
    matchedResult = gradeValues[5];
else if (fifth < 79 && fifth >= 75.5) 
    matchedResult = gradeValues[6];
else if (fifth < 76 && fifth >= 72.5) 
    matchedResult = gradeValues[7];
else if (fifth < 73 && fifth >= 69.5) 
    matchedResult = gradeValues[8];
else if (fifth < 70 && fifth >= 0) 
    matchedResult = gradeValues[9];

// 将匹配结果存入数组(示例为单个元素数组,可根据需求扩展)
String[] resultArray = {matchedResult};

// 如需设置TextView文本,可保留此调用
fivet.setText(matchedResult);

补充说明

如果需要批量处理多个fifth值并存储所有结果,只需初始化对应长度的数组,在循环中逐个匹配赋值即可。两种方式可根据你的实际场景选择:方式一逻辑直接,方式二更便于后续修改输出值。

内容的提问来源于stack exchange,提问作者asdf

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.25 20:21:00