gpt4 book ai didi

Java - 逐字符读取文件并计算行数

转载 作者:行者123 更新时间:2023-12-02 02:08:10 24 4
gpt4 key购买 nike

import java.util.*; 
import java.io.*;
public class Doomday
{
public static void main (String args[]) throws FileNotFoundException
{
Scanner scan = new Scanner(new File(args[0])); //provide file name from outside
int counter =0; //keep track of how many integers in the file
while(scan.hasNextInt())
{
counter++;
scan.nextInt();
}
Scanner scan2 = new Scanner(new File(args[0]));
int a[] = new int[counter];
for(int i=0;i<counter;i++)
{
a[i]=scan2.nextInt(); //fill the array with the integers
}
for(int i=0;i<counter;i++)
{
System.out.print(a[i]);
}

}

}

上面的代码示例通过命令行从文件中读取输入(整数)并将它们存储到数组中。如何修改代码以便它从文件中读取字符?我还希望程序计算文件的行数。

例如,作为输入

+.........-
-+--------.

我想将其存储到二维数组中。如果我知道如何计算字符数和新行数,这将很容易(因为给定行数和字符数 - 并且我的程序中的每一行都有相同的字符数 - 我可以找到我有多少行)

那么如何更改上面的代码以从文件中读取字符并计算程序的行数呢?

您能提供一些代码帮助吗?

谢谢!!

最佳答案

检查此代码。我把它缩短了

读取下一行 Java 有 nextLine() 并检查是否有下一行 Java 有 hasNextLine()

import java.util.*; 
import java.io.*;
public class Dooms
{
public static void main (String args[]) throws FileNotFoundException
{
Scanner scan = new Scanner(new File(args[0])); //provide file name from outside
int counter =0; //keep track of how many lines in the file
while(scan.hasNextLine())
{
String line = new String(scan.nextLine());
System.out.println(line);
counter++;
}

System.out.println("There are "+counter+" lines");
scan.close();

}

}

现在您只需很少的修改就可以轻松地将文件内容存储在二维数组中。

关于Java - 逐字符读取文件并计算行数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50426392/

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