Home » Java » Using split and reading both ints and strings from one line in a file but it doesnt print anything

Using split and reading both ints and strings from one line in a file but it doesnt print anything

Posted by: admin June 14, 2018 Leave a comment

Questions:

The problem is to read a string and int from a text file separated by one space. (e.g. “3.3 Jack”). I tried using the split method as well and it appears to not be printing anything. Just a beginner!

package com.company;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;


public class Main {

    public static void main(String[] args) throws FileNotFoundException {

        Scanner reader = new Scanner(new File("data.txt"));

        double[] grades = new double[6];
        String[] names = new String[6];
        String s = reader.nextLine();
        String[] split = s.split(" ");

        int sum= 0;
        int counter= 0;
        int avg= 0;
            while(reader.hasNext()) {
                for (int i = 0; i <= grades.length; i++) {
                    grades[i] = Double.valueOf(split[0]);
                    names[i]= split[1];
                    sum+=grades[i];
                    counter++;
                    avg= sum/counter;

                }
                System.out.println(avg);
            }

    }
}
Answers: