gpt4 book ai didi

java - java中使用四种方法统计并显示文件中的行数、单词数、字符数

转载 作者:行者123 更新时间:2023-12-01 12:32:40 24 4
gpt4 key购买 nike

这是我第一次在程序中使用多种方法,而且我也从未尝试过计算文件中的行数、单词和字母。因此,我阅读了三本 Java 书籍的文件部分,然后查看了此处论坛上的问题并进行了尝试。我认为我在变量名上做错了,因为我不知道将它们放入多方法等中的规则。如果你可以说这样的事情是明显错误的,因为你必须这样做,那就是有帮助。我无法使用调试器,因为我无法编译它。不管怎样,感谢您看到这里。

import java.util.Scanner;
import java.io.*;

/**
* A program to count the number of lines, words and characters in a text file.
*
* @author
* @version 2014
*/
public class WordCount
{
public static void main(String[] args) throws FileNotFoundException
{
// get the filename
Scanner keyboard = new Scanner(System.in);

System.out.print("Enter the name of the file: ");
String filename = keyboard.nextLine();

File file = new File(filename);
Scanner inputFile = new Scanner(file);

lines(filename);
words(filename);
characters(filename);
}

/**
* Count the number of lines in a file, and print out the result.
*
*/
public static void lines(String filename) throws FileNotFoundException
{
Scanner inputFile = new Scanner(file);
int lines = 0;

while (inputFile.hasNextLine())
{
lines++;
file.nextLine();
}
return lines;

inputFile.close();
}

/**
* Count the number of words in a file, and print out the result.
*
*/
public static void words(String filename) throws FileNotFoundException
{
Scanner inputFile = new Scanner(file);
int words = 0;

while (input.hasNextLine())
{
String word = input.next();
words++;
}
return words;

inputFile.close();
}

/**
* Count the number of characters in a file, and print out the result.
*
*/
public static void characters(String filename) throws FileNotFoundException
{
Scanner inputFile = new Scanner(file);
int characters = 0;

while (inputFile.hasNextLine())
{
String line = inputFile.nextLine();
for(int i = 0; i < line.length(); i++)
{ characters = line.charAt(i);
if (character != 32)
{
characters++;
}
}
}
return characters;
inputFile.close();

System.out.println("The number of lines is: " + lines);
System.out.println("The number of words is: " + words);
System.out.println("The number of characters is: " + characters);
System.out.println();
}

}

最佳答案

更改以下内容

public static int lines(String filename)  throws FileNotFoundException 
//change the return type to int instead of void
{
Scanner inputFile = new Scanner(filename); //filename instead of file
int lines = 0;

while (inputFile.hasNextLine())
{
lines++;
inputFile.nextLine(); // ---do----
}
inputFile.close(); // after return it will become unreachable
return lines;
}

同样适用于其他方法

关于java - java中使用四种方法统计并显示文件中的行数、单词数、字符数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25821845/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com