[英]Java: I want to read from a file, character by character, and save each char into an array that has a max size of 10
這是我的代碼:
//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。 這是我在這里的第一篇文章。 請告訴我,如果我沒有有效發布
嘗試這樣的事情(解釋內聯):
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();
這是一個應該工作的例子
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());
}
您需要在循環的每個迭代中重新初始化您的數組,因為它保留了以前的值:
name = new char[10];
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.