我在may程序中有三个方法,创建文件并输入它的字符串然后将文件中的每个字符转换为大写字母,如何计算文件中字符串中每个字符的重复次数,例如:A = 2 C = 1 S = 4
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import javax.swing.*;
public class run {
public static void main(String[] args) {
// TODO Auto-generated method stub
create();
write();
read();
}
//----------------------------------------------------------
public static char []a={'S','A','R','D','E','O','P'};
static void create()
{
File file=new File("E://ss.txt");
try
{
if(file.createNewFile())
System.out .print("file is new" +" \n" );
else
System.out .print("file is exit"+" \n");
}
catch(IOException e)
{
e.printStackTrace();
}
}
static void write()
{
try
{
FileOutputStream fos = new FileOutputStream("ss.txt") ;
String s=JOptionPane.showInputDialog(null,"write to file");
OutputStreamWriter osw=new OutputStreamWrite`enter code here`r(fos);
Writer r=new BufferedWriter(osw);
r.write(s);
r.close();
}
catch(IOException e)
{
e.printStackTrace();
}
}
static void read()
{
try
{
String c="";
FileInputStream fos = new FileInputStream("ss.txt") ;
System.out.print(fos.available());
int content;
while((content=fos.read())!=-1)
{
c=c+(Character.toString((char)content));
}
System.out.println(c.toUpperCase());
//must be calculate the repeated char
int counter = 0;
for( int i=0; i<c.length(); i++ ) {
if( c.charAt(i) == a[i] ) {
counter++;
}
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
答案 0 :(得分:-2)
可以采用一种非常简单的方法:
现在每当你获取一个字符时,为所有字母创建一个int Array X [26],获取其ASCII值,减去65(A的ASCII值)并将该位置增加1。
x [char.ASCII - 65] ++
请记住将所有数组元素初始化为0。