Java:我想逐字读取文件,并将每个字符保存到一个最大大小为10的数组中
这是我的代码:Java:我想逐字读取文件,并将每个字符保存到一个最大大小为10的数组中,java,filereader,Java,Filereader,这是我的代码: //array way char [] name = new char[10]; while(input.hasNextLine()){ firstName = input.next(); for(int j = 0; j < name.length(); j++){ name [j] = name.charAt(j); } for(int i = 0; i
//array way
char [] name = new char[10];
while(input.hasNextLine()){
firstName = input.next();
for(int j = 0; j < name.length(); j++){
name [j] = name.charAt(j);
}
for(int i = 0; i < name.length; i++){
System.out.println(name);
}
}
我已经初始化了变量,所以这不是问题所在。名称部分的总体目标是逐字符读取文件,并将每个字符保存到最大大小为10的数组中(即仅保存名称的前10个字母)。然后我想打印那个数组
输出为:
将SMITH打印10次,然后将SSN打印10次,然后覆盖前4个字符并用分数替换,而不是擦除SSN
60.512222
这样做了10次,以此类推。我不知道它为什么会这样或如何修复它。有人能帮我吗
这是我在这里的第一篇文章。请告诉我,如果我没有有效地发帖,下面是一个应该有效的例子
try {
FileInputStream fstream = new FileInputStream("example.txt");
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
char[] name = new char[10];
while ((strLine = br.readLine()) != null) {
//save first 10 chars to name
for (int i = 0; i < name.length; i++) {
name[i]=strLine.charAt(i);
}
//print the current data in name
System.out.println(name.toString());
}
in.close();
} catch (Exception e) {
System.err.println("Error: " + e.getMessage());
}
试试看{
FileInputStream fstream=新的FileInputStream(“example.txt”);
DataInputStream in=新的DataInputStream(fstream);
BufferedReader br=新的BufferedReader(新的InputStreamReader(in));
弦斯特林;
char[]name=新字符[10];
而((strLine=br.readLine())!=null){
//将前10个字符保存到name
for(int i=0;i
您需要在循环的每个i插入上重新初始化数组,因为它保留了以前的值:
name = new char[10];
尝试这样的方法(解释内联):
扫描仪输入=新扫描仪(System.in);
while(input.hasNextLine()){
//所有变量在循环中都声明为局部变量
char[]name=新字符[10];
//读名字
String firstName=input.next();
//创建字符数组
对于(int j=0;j
我很确定这不会被编译。我不认为char数组有charAt
方法。更新后可以反映这一点。问题是一样的,哥们,这简直是个奇迹。谢谢你的intext评论,这些也是非常宝贵的。我惊讶地发现,我得到这么多回应的速度有多快。谢谢大家的帮助
name = new char[10];
Scanner input = new Scanner(System.in);
while(input.hasNextLine()){
//all variables are declared as local in the loop
char [] name = new char[10];
//read the name
String firstName = input.next();
//create the char array
for(int j = 0; j < firstName.length(); j++){
name [j] = firstName.charAt(j);
}
//print the char array(each char in new line)
for(int i = 0; i < name.length; i++){
System.out.println(name);
}
//read and print ssn
long ssn = input.nextLong();
System.out.println(ssn);
//read and print grades
double[] grades = new double[4];
grades[0]= input.nextDouble();
System.out.println(grades[0]);
grades[1]= input.nextDouble();
System.out.println(grades[1]);
grades[2]= input.nextDouble();
System.out.println(grades[2]);
grades[3]= input.nextDouble();
System.out.println(grades[3]);
//ignore the new line char
input.nextLine();
}
//close your input stream
input.close();