Skip to content

Output file contains wrong data [closed]

I have a program that is to ask the user their name (this will be used as the file name).

Problem 1: how to I add .txt to the name given to make the file output as .txt.

Then the user is asked how my test entries would they like to enter (this works).

Next they input an integer for each entry with a value between 0-150. (This works)

Last, it is to store the validated test entries in the variable “score” then write the entries on separate lines.

Problem 2: the program will create a file that contains the invalid entries that are not between 0-150. How do I fix this?

        // Create a Scanner object for keyboard input.
        Scanner keyboard = new Scanner(;
        // Get the filename.
        System.out.print("Enter student name: ");
        fileName = keyboard.nextLine();
        //Get the number of test entries wanted
        System.out.print("How many test entries: ");
        numOfTests = keyboard.nextInt();

        //keeping track of test entry number
        //prompting the user for test score
        for (int i = 0; i < numOfTests; i++) {
            System.out.print("Enter the score (must be 0 - 150) : " + (i + 1) + ": ");
            score = keyboard.nextInt();
            //making sure test entry is not a negative number or greater than 150
            while (score < 0 || score > 150) {
                System.out.print("Invalid - must be 0 though 150 : " + (i + 1) + ": ");
                score = keyboard.nextInt();
        }        // Close the file.


Problem 1: After you scan for student name, do fileName = fileName + ".txt"

Problem 2: Move outputFile.println(score) below your while loop.