数组JAVA从txt文件读取整数并计算整数
我需要一些关于下面代码的帮助。 我要做的是编写一个程序,读入文件,计算平均分数,然后打印出来。我尝试过几种方法,比如将文本文件解析为并行数组,但我遇到了将%字符放在成绩末尾的问题。下面的程序也用于将整数相加,但输出为“找不到数字”
这是文本文件的剪辑(整个文件有14行类似的输入):
Arthur Albert,74% Melissa Hay,72% William Jones,85% Rachel Lee,68% Joshua Planner,75% Jennifer Ranger,76%
这就是我到目前为止所做的:
final static String filename = "filesrc.txt";
public static void main(String[] args) throws IOException {
Scanner scan = null;
File f = new File(filename);
try {
scan = new Scanner(f);
} catch (FileNotFoundException e) {
System.out.println("File not found.");
System.exit(0);
}
int total = 0;
boolean foundInts = false; //flag to see if there are any integers
while (scan.hasNextLine()) { //Note change
String currentLine = scan.nextLine();
//split into words
String words[] = currentLine.split(" ");
//For each word in the line
for(String str : words) {
try {
int num = Integer.parseInt(str);
total += num;
foundInts = true;
System.out.println("Found: " + num);
}catch(NumberFormatException nfe) { }; //word is not an integer, do nothing
}
} //end while
if(!foundInts)
System.out.println("No numbers found.");
else
System.out.println("Total: " + total);
// close the scanner
scan.close();
}
}
任何帮助都将不胜感激
# 1 楼答案
正则表达式:^{}
详情:
^
断言行开始处的位置(?<>)
命名的捕获组[^]
匹配列表中不存在的单个字符+
一次和无限次之间的匹配Java代码:
输出:
# 2 楼答案
您可以通过以下方式更改代码:
对于您的输入,输出是
解释:
我使用下面的regex
(?<=,)\\d+(?=%)
n从每一行中提取,
和%
字符之间的数字正则表达式用法:https://regex101.com/r/t4yLzG/1
# 3 楼答案
您的
split
方法是错误的,并且您没有使用任何Pattern
和Matcher
来获取int值。下面是一个工作示例:# 4 楼答案
如果您有少量符合指定格式的行,您可以尝试此(IMO)功能性解决方案:
# 5 楼答案
这是固定密码。而不是使用
你应该使用
这样,在解析拆分字符串时,可以使用substring方法并解析输入的数字部分
例如,给定字符串
我的代码将它分为
Arthur ALbert
和74%
。 然后我可以使用substring方法解析前两个74%的字符,这将给我74%我编写代码的方式使它可以处理0到999之间的任何数字,并在添加您尚未添加的内容时添加了注释。但是,如果你还有任何问题,不要害怕问