![](/img/trans.png)
[英]JAVA- Read .txt file with mix of strings & integers, store strings in an array and integers in a 2D array
[英]JAVA- Read integers from txt file and compute integers
我需要以下代碼的幫助。 我想做的是編寫一個程序,該程序讀取文件並計算平均成績並將其打印出來。 我嘗試了幾種方法,例如將文本文件解析為並行數組,但是遇到了在成績末尾使用%字符的問題。 下面的程序也打算將整數相加,但輸出為“未找到數字”。
這是文本文件的片段(整個文件是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();
}
}
任何幫助將非常感激!
這是固定代碼。 而不是使用分割輸入
" "
你應該使用
","
這樣,當您解析拆分的字符串時,可以使用substring方法並解析輸入的數字部分。
例如,給定字符串
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);
}
您可以通過以下方式更改代碼:
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.