-1

I have a text file with words and numbers and I need to write a class that creates a new file identical to the first except it shows the average.

I just need code that identifies the integers and finds the average of them.

The file reads like:

blah blah 4 blah blah 2 3 blah 3 blah blah blah blah etc...

but on the new file the average will be on the bottom.

My code so far:

private File inFile;
private Scanner input;
private File outFile;
private PrintWriter output;

public fileCloner(String inFilename, String outFilename)
{        
    inFile = new File(inFilename);                        
    outFile = new File(outFilename);

    makeLinks();
    writeFiles();
    closeLinks();

public void makeLinks() throws FileNotFoundException
{          
    input = new Scanner(inFile);
    output = new PrintWriter(outFile);
}    

public void writeFiles()
{       
    while (input.hasNext()) 
        {                     
            String line = input.nextLine();                        
            output.println(line);                    
        }


    output.println("\n");        
    output.println("The average is" + );  


}


public void closeLinks()
{   
    input.close();               
    output.close();        
}

Any help is appreciated, thanks in advance.

crakajak
  • 7
  • 1
  • 1
    Welcome to Stack Overflow. This is not a homework completion service. Your instructor gave you the assignment, not us, and you're going to need to do your own work. If we do it for you, you don't learn anything. If you can't get started, ask your teacher for help; they're being paid to teach you. Good luck. – Ken White Mar 12 '18 at 19:29

2 Answers2

0

To figure out whether or not a string contains an int: Look Here.

To get an average, add all integer values and divide by the number of values you added.

gigadude7
  • 20
  • 4
0

Just sum up all the integers and divide them by the amount there are. The catch is to check if it is a number or not.

int sum = 0;
int amt = 0;
while(input.hasNext()) {
    String x = input.next();
        try{
            int num = Integer.parseInt(x);
            sum += num;
            amt++;
            } catch (NumberFormatException e) {}
        }
        double average = (double)sum/(double)amt;