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

从文本文件读取数据并存储指定数值的实现方法

解决方案:读取文本文件中的身高体重并全局存储

首先,咱们得先准备好能被整个Activity里其他函数访问的变量——也就是在MainActivity类里定义全局成员变量,这样不管哪个函数需要用身高体重值,都能直接拿到。

第一步:定义全局成员变量

在你的MainActivity类里,所有方法(比如onCreate、点击事件方法)的外面,加上这两个变量:

public class MainActivity extends AppCompatActivity {
    // 定义全局变量存储身高和体重,初始值可以设为0或者其他默认值
    private int userHeight = 0;
    private int userWeight = 0;

    // 下面是你的onCreate方法和其他代码...
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // ... 你的其他初始化代码
    }
}

第二步:解析读取到的文本内容

假设你已经有了读取文本文件内容的代码,拿到完整的文本字符串(比如叫fileContent)之后,咱们需要从里面把身高和体重的数值抠出来。这里给你两种靠谱的方法:

方法一:用字符串截取(适合文本格式固定的情况)

因为你的文本格式是固定的Name: .......... Height: 175 Weight 80,所以可以直接根据关键词定位:

// 假设fileContent是你读取到的文本内容
// 提取身高
int heightStartIndex = fileContent.indexOf("Height: ") + "Height: ".length();
int heightEndIndex = fileContent.indexOf(" Weight");
userHeight = Integer.parseInt(fileContent.substring(heightStartIndex, heightEndIndex).trim());

// 提取体重
int weightStartIndex = fileContent.indexOf("Weight ") + "Weight ".length();
userWeight = Integer.parseInt(fileContent.substring(weightStartIndex).trim());

方法二:用正则表达式(更灵活,适合文本格式有小变动的情况)

如果以后文本格式稍微调整(比如空格多了少了),正则表达式能更稳定地匹配数字:

import java.util.regex.Matcher;
import java.util.regex.Pattern;

// ... 其他代码

// 匹配身高:找Height:后面的数字
Pattern heightPattern = Pattern.compile("Height: (\\d+)");
Matcher heightMatcher = heightPattern.matcher(fileContent);
if (heightMatcher.find()) {
    userHeight = Integer.parseInt(heightMatcher.group(1));
}

// 匹配体重:找Weight后面的数字
Pattern weightPattern = Pattern.compile("Weight (\\d+)");
Matcher weightMatcher = weightPattern.matcher(fileContent);
if (weightMatcher.find()) {
    userWeight = Integer.parseInt(weightMatcher.group(1));
}

第三步:在其他函数里调用

现在不管你在MainActivity的哪个函数里,比如按钮点击事件,都可以直接用userHeight和userWeight这两个变量了:

public void onSomeButtonClick(View view) {
    // 直接使用全局存储的身高体重
    Toast.makeText(this, "身高:" + userHeight + ",体重:" + userWeight, Toast.LENGTH_SHORT).show();
}

注意哦,如果你的需求是跨多个Activity或者重启APP后还能保留这些值,那就要用SharedPreferences、Room数据库或者其他持久化方式啦,上面的方法只是在当前Activity的生命周期内有效~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 11:43:33