gpt4 book ai didi

java - 从 .txt 文件中读取字符串,然后将其转换为整数

转载 作者:行者123 更新时间:2023-11-29 08:44:41 25 4
gpt4 key购买 nike

我正在尝试从文本文件中读取一些数据,格式如下:

10
1
s
q

代码如下:

public static void main(String[] args) {

String line = null;

int[] b= new int[10];
int i = 0;

try {
BufferedReader bf = new BufferedReader(new FileReader("C:\\myFile.txt"));

while ((line = bf.readLine()) != null) {

b[i] = Integer.parseInt(line);
i++;

}

} catch (IOException e) {
System.out.println(e.getMessage());

}
}

this b[i] = Integer.parseInt(line); 很容易从文件中读取第一行'10',第二行'1'也是如此,但是对于第三行's'编译器给我以下错误

Exception in thread "main" java.lang.NumberFormatException: For input string: "s"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:580)
at java.lang.Integer.parseInt(Integer.java:615)
at test.Main.main(Main.java:41)

我需要将字符串 's' 和 'H' 转换为整数值,然后存储到我的整数类型数组 b 中。

最佳答案

首先检查字符串是否包含字母或数字

if(line.matches("[a-zA-Z]+"))
int a=(int)line.charAt(0);

else if(line.matches("[0-9]+"))
int a=Integer.parseInt(line);

关于java - 从 .txt 文件中读取字符串,然后将其转换为整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37235838/

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