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

変数はすでに初期化されているので、問題はありません。名前部分の全体的な目標は、ファイルを1文字ずつ読み取り、各文字を最大サイズ10の配列に保存することです(つまり、名前の最初の10文字のみが保存されます)。次に、その配列を出力します。

出力は次のとおりです。SMITHを10回、次にSSNを10回出力し、SSNを消去する代わりに、最初の4文字を上書きして、グレードに置き換えます。

60.512222

それを10回繰り返します。なぜこれを行うのか、それを修正する方法がわかりません。誰かがplzを助けることができますか?

ps。これが私の最初の投稿です。plzは私が効率的に投稿していないかどうか教えてください

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 に答える