How do I fix my try block so I get the average from my txt file?

Related searches

so I am trying to read and find the average of all these integers from a normal .txt file, this is how it looks:

Mary 60
Tom 70
Jack 80
John 90
Sue 100
Bob 95
Gary 85
Emily 75

I have the read part down, but something is wrong with either my while loop or my try block

This is my desired output: The average is 81.0

This is my actual output:

The average is 7.0 The average is 8.0 The average is 10.0 The average is 11.0 The average is 12.0 The average is 11.0 The average is 10.0 The average is 9.0

Can anybody find the error in my logic?

public class Average {//begin class

public static void main(String[] args) {//begin main
    // TODO Auto-generated method stub

    try {//begin try
        File datafile = new File("C:\\Users\\jglez\\Documents\\Data.txt");
        Scanner inputFile = new Scanner(datafile);
        while(inputFile.hasNext()) {
            String name = inputFile.next();
            int grade = inputFile.nextInt();
            double average = grade/8;

            System.out.println("The average is " + average);
        }//end while

    }//end try
    catch(Exception e) {//begin catch
        System.out.println("FileNotFoundException caught");
    }//end catch

}//end main
    }//end class

I tried placing

double average = grade/8; System.out.println("The average is " + average);

outside of my try while loop and before my try block because I think it should work logically like that, but I get the error "grade cannot be resolved to a variable" even though I declared it in my while loop, so I don't know what's the fix?

I appreciate any help, thanks!

My program is not running as i want it to. Does not detect the text file , Also, having a try except with no specific exception is very evil. To expand on my comment, here's how you could restructure your code so that only open is in print("This program will read all the grades from the hw.txt file.") print("Then the program wll calculate the final homework grade(average with the� The file includes information about files that were not repaired by the System File Checker tool. Verify the date and time entries to determine the problem files that were found the last time that you ran the System File Checker tool. Open the Sfcdetails.txt file from your desktop. The Sfcdetails.txt file uses the following format:

Considering files can have any number of records, it is better to count them rather than hard-coding as 8. Make sure integer summation does not overflow otherwise use BigInteger. Division of two ints will result in int result, you have to typecast it into float or double.

Changes to be made, declare countLines to count records in the file and sumOfGrades to hold summation of grades. Once file scan is complete, declare variable average and compute it using sumOfGrades/countLines with typecase to get the result.

try {//begin try
            File datafile = new File("C:\\Users\\jglez\\Documents\\Data.txt");
            Scanner inputFile = new Scanner(datafile);
            int sumOfGrades = 0;
            int countLines = 0; // to calculate number of lines file has.
            while(inputFile.hasNext()) {
                String name = inputFile.next();
                int grade = inputFile.nextInt();
                sumOfGrades += grade;
                ++countLines;
            }//end while
            double average = (double) sumOfGrades/countLines;
            System.out.println("The average is " + average);
        }//end try
        catch(Exception e) {//begin catch
            System.out.println("FileNotFoundException caught");
            e.printStackTrace();
        }//end catch

Python Tutorial: Exception Handling, Introduction on Exception handling with try, except and finally. "file open error" and so on) which had occurred, the error handler can "fix" the got it in the function :-) invalid literal for int() with base 10: 'four' Let's get on File "<string>", line unknown SyntaxError: Sorry, my fault! python exception_test.py integers.txt . How to Fix the Most Annoying Things in Windows 10. Windows 10 is great, but it has its issues, from unpredictable reboots to Cortana. Here's how to fix some of the more irritating quirks with

[PPT] Chapter 11 – Input/Output and Exception Handling, To process command line arguments To throw and catch exceptions Use Scanner class for reading text files To read from a disk file: Try it out if you are not sure. How do you modify the program so that it shows the average, not the total, of the When you throw an exception, you can provide your own message string. Open an Edge window, press Shift+ Ctrl + P to open a new window in, in Private mode. Further you may try turning off the Smart Screen filter and check if it helps to resolve the issue. Refer the below steps to turn on the Smart screen filter off.

Many changes required. Following is the resulted try block. You can find comments inline

try {//begin try
        File datafile = new File("C:\\Users\\jglez\\Documents\\Data.txt");
        Scanner inputFile = new Scanner(datafile);
        double average=0; //Intializing average outside
        while(inputFile.hasNext()) {
            String name = inputFile.next();
            double grade = inputFile.nextDouble(); //Changed datatype to double
            average = average +  grade/8.0; //changed your average calculation


        }
        System.out.println("The average is " + average); //Printing average outside

(Tutorial) Exception and Error Handling in Python, ERROR HANDLING increases the robustness of your CODE, which guards So let's take a quick example to understand an indentation error. Even if the syntax of a statement or expression is correct, it may still cause an error Like, programs that make use try-except blocks to handle exceptions will run� Clear your browser cache and cookies and then try to load your Drive files again. Step 4: Reduce the size of your file You can put large files in Drive, but if you exceed the size limits, they might not load properly.

I think you are trying to divide each value with the count which is not appropriate instead you need to find sum of all elements and divide it by count and your code should change something as below:

public class Average {//begin class

public static void main(String[] args) {//begin main
    // TODO Auto-generated method stub

    try {//begin try
        double sum=0.0,grade =0.0;
        File datafile = new File("C:\\Users\\jglez\\Documents\\Data.txt");
        Scanner inputFile = new Scanner(datafile);
        while(inputFile.hasNext()) {
            String name = inputFile.next();
            grade = inputFile.nextInt();
            sum = sum+grade;


        }//end while
        System.out.println("The average is " + sum/8.0);
    }//end try
    catch(Exception e) {//begin catch
        System.out.println("FileNotFoundException caught");
    }//end catch

}//end main
    }

Hope this is helpful and try to include arithmetic exception catch clause for above logic.

[PDF] File I/O & error-handling, Syntax for try/catch block try {. // code that may throw an exception. } If no error occurs then no exception is thrown, all statements One way to take care of the exception and get rid of the error message is shown on folder as my program's byte code; the file Writing output to text files append to it, rather than replace it� Check your virus-scanning software for details about why the file was blocked. On Windows: Windows Attachment Manager could have removed the file you tried to download. To see what files you can

Press Win + R to open the Run window, then type “ Services.msc ” and press Enter. When the Services window appears, scroll down the list of services to find Windows Search. If it's already running, right-click it or tap and hold, then select Restart.

Choose Overview at the top of the screen in your H&R Block Online product. Go to Check Status or Next Steps. Choose Details about the Rejection and Fix Issues to correct any problems. After you’ve updated your return, you can choose Continue to File. If that doesn’t appear as an option, it means there are still additional issues that you

Get right to your messages. Access your messages and conversations when you open the app. Get free push notifications on your phone or tablet, so you see each message when it arrives. Quickly switch between multiple conversations with in-app notifications.

Comments
  • In java, int / int will always give you a int, so you will loose the decimal value. You can correct that with grade / 8.0 because int / double gives a double.
  • Should be grade / 8.0 otherwise it won't calculate the decimals. Also there is no need to create a new variable at each iteration, grade should be defined before the loop.
  • @PaulLemarchand I think grade is of type double, so it should work. Also I do not want to modify his existing code too much so it would be difficult for him to understand thats why not made many changes
  • no, that doesn't work like that. if you do double = int / int, the result will be of type int casted to double.
  • @PaulLemarchand check the grade declaration in his code, he changed the type to double giving a double / int perfectly fine
  • @PaulLemarchand that's the problem with answers with Many changes required but not listed.
  • sum = grade+grade; won't give you a good result. sum = sum + grade; will
  • Yes AxelH ,sorry it was copy paste error will change now thanks for notifying