JAVA- 从 txt 文件中读取整数并计算整数
JAVA- Read integers from txt file and compute integers
我需要一些关于下面代码的帮助。
我想做的是编写一个程序来读取文件并计算平均成绩并将其打印出来。我已经尝试了几种方法,比如将文本文件解析为并行数组,但我 运行 遇到了在成绩末尾使用 % 字符的问题。下面的程序也是为了将整数相加,但输出是 "No numbers found."
这是文本文件的一个片段(整个文件是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();
}
}
如有任何帮助,我们将不胜感激!
您可以通过以下方式更改您的代码:
Matcher m;
int total = 0;
final String PATTERN = "(?<=,)\d+(?=%)";
int count=0;
while (scan.hasNextLine()) { //Note change
String currentLine = scan.nextLine();
//split into words
m = Pattern.compile(PATTERN).matcher(currentLine);
while(m.find())
{
int num = Integer.parseInt(m.group());
total += num;
count++;
}
}
System.out.println("Total: " + total);
if(count>0)
System.out.println("Average: " + total/count + "%");
对于你的输入,输出是
Total: 450
Average: 75%
说明:
我正在使用以下正则表达式 (?<=,)\d+(?=%)
n 从每行中提取 ,
和 %
字符之间的数字。
正则表达式用法: https://regex101.com/r/t4yLzG/1
这是固定代码。而不是使用
拆分输入
" "
你应该使用
拆分它
","
这样,当您解析拆分字符串时,您可以使用子字符串方法并解析输入的数字部分。
例如,给定字符串
Arthur Albert,74%
我的代码会将其拆分为 Arthur ALbert
和 74%
。
然后我可以使用substring方法并解析74%的前两个字符,这将得到74.
我编写代码的方式使其可以处理 0 到 999 之间的任何数字,并在我添加了您还没有的内容时添加了注释。如果您还有任何问题,请不要害怕提问。
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
int successful = 0; // I did this to keep track of the number of times
//a grade is found so I can divide the sum by the number to get the average
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) {
System.out.println(str);
try {
int num = 0;
//Checks if a grade is between 0 and 9, inclusive
if(str.charAt(1) == '%') {
num = Integer.parseInt(str.substring(0,1));
successful++;
total += num;
foundInts = true;
System.out.println("Found: " + num);
}
//Checks if a grade is between 10 and 99, inclusive
else if(str.charAt(2) == '%') {
num = Integer.parseInt(str.substring(0,2));
successful++;
total += num;
foundInts = true;
System.out.println("Found: " + num);
}
//Checks if a grade is 100 or above, inclusive(obviously not above 999)
else if(str.charAt(3) == '%') {
num = Integer.parseInt(str.substring(0,3));
successful++;
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/successful);
// close the scanner
scan.close();
}
正则表达式: ^(?<name>[^,]+),(?<score>[^%]+)
详情:
^
声明行首的位置
(?<>)
命名捕获组
[^]
匹配列表中不存在的单个字符
+
匹配一次到无限次
Java代码:
import java.util.regex.Pattern;
import java.util.regex.Matcher;
final static String filename = "C:\text.txt";
public static void main(String[] args) throws IOException
{
String text = new Scanner(new File(filename)).useDelimiter("\A").next();
final Matcher matches = Pattern.compile("^(?<name>[^,]+),(?<score>[^%]+)").matcher(text);
int sum = 0;
int count = 0;
while (matches.find()) {
sum += Integer.parseInt(matches.group("score"));
count++;
}
System.out.println(String.format("Average: %s%%", sum / count));
}
输出:
Avarege: 74%
如果您有少量行符合您指定的格式,您可以试试这个 (IMO) 不错的功能解决方案:
double avg = Files.readAllLines(new File(filename).toPath())
.stream()
.map(s -> s.trim().split(",")[1]) // get the percentage
.map(s -> s.substring(0, s.length() - 1)) // strip off the '%' char at the end
.mapToInt(Integer::valueOf)
.average()
.orElseThrow(() -> new RuntimeException("Empty integer stream!"));
System.out.format("Average is %.2f", avg);
您的 split
方法是错误的,您没有使用任何 Pattern
和 Matcher
来获取 int 值。这是一个工作示例:
private final static String filename = "marks.txt";
public static void main(String[] args) {
// Init an int to store the values.
int total = 0;
// try-for method!
try (BufferedReader reader = Files.newBufferedReader(Paths.get(filename))) {
// Read line by line until there is no line to read.
String line = null;
while ((line = reader.readLine()) != null) {
// Get the numbers only uisng regex
int getNumber = Integer.parseInt(
line.replaceAll("[^0-9]", "").trim());
// Add up the total.
total += getNumber;
}
} catch (IOException e) {
System.out.println("File not found.");
e.printStackTrace();
}
// Print the total only, you know how to do the avg.
System.out.println(total);
}
我需要一些关于下面代码的帮助。 我想做的是编写一个程序来读取文件并计算平均成绩并将其打印出来。我已经尝试了几种方法,比如将文本文件解析为并行数组,但我 运行 遇到了在成绩末尾使用 % 字符的问题。下面的程序也是为了将整数相加,但输出是 "No numbers found."
这是文本文件的一个片段(整个文件是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();
}
}
如有任何帮助,我们将不胜感激!
您可以通过以下方式更改您的代码:
Matcher m;
int total = 0;
final String PATTERN = "(?<=,)\d+(?=%)";
int count=0;
while (scan.hasNextLine()) { //Note change
String currentLine = scan.nextLine();
//split into words
m = Pattern.compile(PATTERN).matcher(currentLine);
while(m.find())
{
int num = Integer.parseInt(m.group());
total += num;
count++;
}
}
System.out.println("Total: " + total);
if(count>0)
System.out.println("Average: " + total/count + "%");
对于你的输入,输出是
Total: 450
Average: 75%
说明:
我正在使用以下正则表达式 (?<=,)\d+(?=%)
n 从每行中提取 ,
和 %
字符之间的数字。
正则表达式用法: https://regex101.com/r/t4yLzG/1
这是固定代码。而不是使用
拆分输入" "
你应该使用
拆分它","
这样,当您解析拆分字符串时,您可以使用子字符串方法并解析输入的数字部分。
例如,给定字符串
Arthur Albert,74%
我的代码会将其拆分为 Arthur ALbert
和 74%
。
然后我可以使用substring方法并解析74%的前两个字符,这将得到74.
我编写代码的方式使其可以处理 0 到 999 之间的任何数字,并在我添加了您还没有的内容时添加了注释。如果您还有任何问题,请不要害怕提问。
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
int successful = 0; // I did this to keep track of the number of times
//a grade is found so I can divide the sum by the number to get the average
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) {
System.out.println(str);
try {
int num = 0;
//Checks if a grade is between 0 and 9, inclusive
if(str.charAt(1) == '%') {
num = Integer.parseInt(str.substring(0,1));
successful++;
total += num;
foundInts = true;
System.out.println("Found: " + num);
}
//Checks if a grade is between 10 and 99, inclusive
else if(str.charAt(2) == '%') {
num = Integer.parseInt(str.substring(0,2));
successful++;
total += num;
foundInts = true;
System.out.println("Found: " + num);
}
//Checks if a grade is 100 or above, inclusive(obviously not above 999)
else if(str.charAt(3) == '%') {
num = Integer.parseInt(str.substring(0,3));
successful++;
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/successful);
// close the scanner
scan.close();
}
正则表达式: ^(?<name>[^,]+),(?<score>[^%]+)
详情:
^
声明行首的位置(?<>)
命名捕获组[^]
匹配列表中不存在的单个字符+
匹配一次到无限次
Java代码:
import java.util.regex.Pattern;
import java.util.regex.Matcher;
final static String filename = "C:\text.txt";
public static void main(String[] args) throws IOException
{
String text = new Scanner(new File(filename)).useDelimiter("\A").next();
final Matcher matches = Pattern.compile("^(?<name>[^,]+),(?<score>[^%]+)").matcher(text);
int sum = 0;
int count = 0;
while (matches.find()) {
sum += Integer.parseInt(matches.group("score"));
count++;
}
System.out.println(String.format("Average: %s%%", sum / count));
}
输出:
Avarege: 74%
如果您有少量行符合您指定的格式,您可以试试这个 (IMO) 不错的功能解决方案:
double avg = Files.readAllLines(new File(filename).toPath())
.stream()
.map(s -> s.trim().split(",")[1]) // get the percentage
.map(s -> s.substring(0, s.length() - 1)) // strip off the '%' char at the end
.mapToInt(Integer::valueOf)
.average()
.orElseThrow(() -> new RuntimeException("Empty integer stream!"));
System.out.format("Average is %.2f", avg);
您的 split
方法是错误的,您没有使用任何 Pattern
和 Matcher
来获取 int 值。这是一个工作示例:
private final static String filename = "marks.txt";
public static void main(String[] args) {
// Init an int to store the values.
int total = 0;
// try-for method!
try (BufferedReader reader = Files.newBufferedReader(Paths.get(filename))) {
// Read line by line until there is no line to read.
String line = null;
while ((line = reader.readLine()) != null) {
// Get the numbers only uisng regex
int getNumber = Integer.parseInt(
line.replaceAll("[^0-9]", "").trim());
// Add up the total.
total += getNumber;
}
} catch (IOException e) {
System.out.println("File not found.");
e.printStackTrace();
}
// Print the total only, you know how to do the avg.
System.out.println(total);
}