EDITED Я написал программу для чтения в файлах и подсчета строк, слов и номеров символов. Он принимает аргументы командной строки, если они есть, иначе попросите пользователя ввести имена файлов. Но когда я пытаюсь запустить его, это происходит навсегда; он все-таки успешно работает. Я не знаю, почему это делается. Может ли кто-нибудь помочь? Благодаря! Вот мой код:Почему мой проект java работает так медленно?
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class project2 {
static int lines = 0, words = 0, bytes = 0,
totalLines = 0, totalWords = 0, totalBytes = 0;
static String[] filename;
static int i = 0;
static BufferedReader inFile = null;
//static File currentFile = new File(filename[i]);
public static void main(String[] args) throws IOException {
if (args.length > 0) { // if there are arguments on commandline
for (int j = 0; j < args.length; j++) {
filename[i] = args[j];
}
} else { // prompt user to input file names
BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
String userInput = input.readLine(); // read the user inputs as a string
System.out.println("Please enter one or more file names, comma-separated: ");
userInput = userInput.replaceAll(" ", ""); // delete all the whitespaces
filename = userInput.split(",", -1); // split the line into sub-strings by comma
}
System.out.println("This program determines the quantity of lines, "
+ "words, and bytes in a file or files that you specify.");
System.out.println("%n");
for (i = 0; i < filename.length; i++) {
Count();
totalLines = totalLines + lines;
totalWords = totalWords + words;
totalBytes = totalBytes + bytes;
}
System.out.format("%10s%10s%10%n", "Lines", "Words", "Bytes");
System.out.format("%10s%10s%10%n", "--------", "--------", "--------");
Print();
for (i = 0; i < filename.length; i++) {
inFile.close();
}
//return;
}
public static void Count() throws IOException {
inFile = new BufferedReader(new FileReader(filename[i]));
String currentLine = inFile.readLine();
while (currentLine != null) {
lines++;
String[] WORDS = currentLine.split(" "); // split the string into sub-string by whitespace
// to separate each words and store them into an array
words = words + WORDS.length;
for (String word : WORDS) {
bytes = bytes + word.length();
}
currentLine = inFile.readLine();
}
}
public static void Print() {
for (i = 0; i < filename.length; i++) {
System.out.format("%10d%10d%10d%-15s%n", lines,
words, bytes, filename[i]);
}
if (filename.length < 2) { // if there's only one file, do not print out anything else
} else {
for (int j = 0; j < 45; j++) {
System.out.print("-");
}
System.out.format("%10d%10d%10d%-15s", totalLines, totalWords, totalBytes, "Totals");
}
}
Попробуйте отладить код и посмотреть, что он делает, вы, вероятно, будете удивлены ... – alfasin
'while (line! = Null)' - бесконечный цикл. И ваша логика в любом случае испорчена: вы хотите прочитать файл три раза? Зачем? Прочитайте его один раз и получите количество слов и символов для каждой строки чтения. – Tom
@ Почему это бесконечный цикл? Я думал, что он читает до конца строки? –