这是我的代码:
//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);
}
}
我的inFile采用这种格式(姓名,社会安全号码,然后是4个等级):
SMITH 111112222 60.5 90.0 75.8 86.0
我已经初始化了变量,所以这不是问题。 name部分的总体目标是逐个字符地读取文件,并将每个char保存到最大大小为10的数组中(即只保存名称的前10个字母)。然后我想打印那个数组。
输出是: 打印SMITH 10次,然后打印SSN 10次,然后不是擦除SSN,而是覆盖前4个字符并用等级替换它们
60.512222
并做了10次,依此类推。我不知道为什么会这样或如何解决它。有人可以帮忙吗?
PS。这是我在此的头一篇博文。请告诉我,如果我没有有效发布
答案 0 :(得分:1)
尝试这样的事情(内联说明):
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();
答案 1 :(得分:0)
这是一个应该起作用的例子
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());
}
答案 2 :(得分:-1)
您需要在循环的每次迭代中重新初始化数组,因为它保留了以前的值:
name = new char[10];