我正在尝试创建一个类,该类从一个文件中获取信息并使用它将信息输入到另一个文件中。例如,扫描一行,如果该行等于“蓝色”,则将 B 变量加 1。
我尝试过这个,但每次都出现0。在我正在扫描的文件(ColorResultsLead.txt)中,有三个“蓝色”和一个“红色”。但我得到的只是 0。
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintStream;
import java.util.Objects;
import java.util.Scanner;
public class ColorDescripLeadPercent {
public static void main(String [] args) throws FileNotFoundException {
int P = 0;
int R = 0;
int O = 0;
int Y = 0;
int G = 0;
int B = 0;
int I = 0;
int V = 0;
FileOutputStream file = new FileOutputStream("ColorResultsLead.txt", false);
PrintStream ps = new PrintStream(file);
System.setOut(ps);
Scanner searchDoc = new Scanner(new File("ColorResults.txt"));
while (searchDoc.equals("Pink") || searchDoc.equals( "Red") || searchDoc.equals("Orange") || searchDoc.equals("Yellow") || searchDoc.equals("Green") || searchDoc.equals("Blue") || searchDoc.equals("Indigo") || searchDoc.equals("Violet")) {
if (searchDoc.equals("Pink")) {
P++;
}
if (searchDoc.equals("Red")) {
R++;
}
if (searchDoc.equals("Orange")) {
O++;
}
if (searchDoc.equals("Yellow")) {
Y++;
}
if (searchDoc.equals("Green")) {
G++;
}
if (searchDoc.equals("Blue")) {
B++;
}
if (searchDoc.equals("Indigo")) {
I++;
}
if (searchDoc.equals("Violet")) {
V++;
` }
searchDoc.nextLine();
}
System.out.println(P);
System.out.println(R);
System.out.println(O);
System.out.println(Y);
System.out.println(G);
System.out.println(B);
System.out.println(I);
System.out.println(V);
}
(回答了,太气人了!!)
仅供将来参考和研究,这可以使用流直接完成,但如果您遵循当前的建议,我们可以帮助您使用现有代码:
import java.nio.file.Files;
import java.nio.file.Path;
import java.io.File;
import java.io.PrintWriter;
import java.io.IOException;
import java.io.FileNotFoundException;
import java.util.Map;
import static java.util.stream.Collectors.*;
import java.util.Scanner;
public class ColorDescripLeadPercent {
public static void main(String[] args) throws FileNotFoundException, IOException {
try (Scanner sc = new Scanner(new File("ColorResults.txt"));
PrintWriter out = new PrintWriter(Files.newBufferedWriter(Path.of("ColorResultsLead.txt")))) {
Map<String, Long> colorCounts = sc.tokens().collect(groupingBy(color -> color, counting()));
colorCounts.entrySet().
stream().
forEach(e -> out.print("%s=%d%n".formatted(e.getKey(), e.getValue())));
}
}
}