3

这是我的代码:

    //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

我已经初始化了变量,所以这不是问题。名称部分的总体目标是逐字符读取文件,并将每个字符保存到最大大小为 10 的数组中(即仅保存名称的前 10 个字母)。然后我想打印那个数组。

输出是:打印 SMITH 10 次,然后 SSN 10 次,然后不是擦除 SSN,而是覆盖前 4 个字符并用等级替换它们

60.512222

并这样做了 10 次,依此类推。我不知道它为什么这样做或如何解决它。有人可以帮忙吗?

附言。这是我在此的头一篇博文。请告诉我我是否没有有效地发帖

4

3 回答 3

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();
于 2012-12-01T19:27:17.277 回答
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());
        }
于 2012-12-01T19:02:10.387 回答
-1

您需要在循环的每次迭代中重新初始化您的数组,因为它保留了以前的值:

name = new char[10];
于 2012-12-01T19:03:00.280 回答