gpt4 book ai didi

java - 读取文件然后将字符串转换为 ascii 以制作频率计数器 java

转载 作者:行者123 更新时间:2023-11-30 11:13:51 24 4
gpt4 key购买 nike

你好,这段代码我正在尝试读取一个文件。读取文件后,我试图获取文件中每个字符的ascii值,然后制作大写字符、小写字符和数字的频率计数器

使用我的代码,我尝试逐行读取文件并将它们相应地放入每个数组中。然后我可以将该数组用作频率计数器,看看有多少个大写字符、小写字符和数字。

import java.io.*;

public class Counting
{
char[] upper;
char[] lower;
int[] num;
int u1 = 0;
int l1= 0;
int n1 = 0;
File inFile;

public void ReadFile( String nfile ) throws IOException
{
inFile = new File( nfile );
BufferedReader reader = new BufferedReader( new FileReader( inFile ) );
//... Loop as long as there are input lines.
String speech = null;
//char[] charArray = null;

while ( ( speech = reader.readLine() ) != null)
{
int slength = speech.length();

//charArray = speech.toCharArray();



AddToArrays(speech, slength);

}

//... Close reader and writer.
reader.close(); // Close to unlock.
}

public void AddToArrays(String c, int l)
{
/*for(int i = 0; i < l; i++)
{
if( (int) c[u1] > 64 && (int) c[u1] < 91)
{
upper[u1] = c[i];
u1++;
}
if( (int) c[l1] > 96 && (int) c[l1] < 123)
{
lower[l1] = c[i];
l1++;
}
if( (int) c[n1] > 47 && (int) c[n1] < 58)
{
num[l1] = c[i];
n1++;
}
}*/
for(int i = 0; i < l ; i++)
{
char character = c.charAt(i);
int ascii = (int) character;

if( ascii > 64 && ascii < 91)
{
upper[u1] = character;
u1++;
}
if( ascii > 96 && ascii < 123)
{
lower[l1] = character;
l1++;
}
if( ascii > 47 && ascii < 58)
{
lower[n1] = character;
n1++;
}
}

}

public void DisplayResults(int u, int l, int n)
{
System.out.println("Upper characters: " + u);
System.out.println("lower characters: " + l);
System.out.println("Numbers: " + n);
}

public static void main( String[] args )
{
try
{
Counting rFile = new Counting();
rFile.ReadFile( "Speech.txt" );
rFile.DisplayResults( rFile.u1, rFile.l1, rFile.n1 );

}
catch ( IOException e )
{
System.out.println( e.getMessage() );
}

}

}

我收到以下错误:

线程“main”中的异常 java.lang.NullPointerException

在 Counting.AddToArrays(Counting.java:64)

在 Counting.ReadFile(Counting.java:29)

在 Counting.main(Counting.java:93)

我最近开始进行 java 编程。

如果有人能帮忙,谢谢。

最佳答案

你只是在声明你的数组,并没有在你的代码中初始化它们的地方:

char[] upper;
char[] lower;

因此,当您尝试访问这些数组中的元素时,您将得到 NullPointerException:

        upper[u1] = character;

lower[l1] = character;

你需要在使用前初始化这些数组:

upper = new char[desiredLength];
lower = new char[desiredLength];

关于java - 读取文件然后将字符串转换为 ascii 以制作频率计数器 java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26226759/

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