Question

composed the following java code to read a string from a text file but receiving compiling...

composed the following java code to read a string from a text file but receiving compiling errors. The text file is MyNumData.txt. Included the original java script that generated the output file.

Shown also in the required output results after running the java program. I can't seem to search for the string and output the results. Any assistance will be greatly appreciated.

import java.io.BufferedReader;

import java.io.FileReader;

import java.util.ArrayList;

public class Main {

  public static void main(String[] args) {

    System.out.print("Enter the name of the input file to search:");

    final String file = "MyNumData.txt";

    fname = scan.nextLine();

    String line = null;

    ArrayList<String> fileContents = new ArrayList<>();

    System.out.print("Please enter the string to search:");

try {

      FileReader fReader = new FileReader(file);

      BufferedReader fileBuff = new BufferedReader(fReader);

      while ((line = fileBuff.readLine()) != null) {

        fileContents.add(line);

      }

      System.out.println ("The following lines were found:", ++line);

      fileBuff.close();

    } catch (Exception e) {

      System.out.println(e.getMessage());

    }

    }

}

java code that generates the ouput file:

import java.io.*;

import java.util.Scanner;

public class CodingChallenge5CRM {

  public static void main(String[] args){

    Scanner sc = new Scanner(System.in);

    System.out.println("Welcome to the Prime, Perfect Square, and Perfect Number Tester ");

    System.out.print("Please enter the name of the output file to save your data:");

    String name = sc.nextLine();

    PrintWriter pw = null;

    try {

      FileOutputStream fout = new FileOutputStream(name);

      pw = new PrintWriter(fout);

    }

    catch (Exception e){

      e.printStackTrace();

    }

    System.out.print("Enter a start number:");

    int a = Integer.parseInt(sc.nextLine());

    System.out.print("Enter a stop number:");

    int b = Integer.parseInt(sc.nextLine());

    

    for (int i = a; i<=b; i++){

      int ps = 0;

      for (int k = 0; k<a; k++){

        if (k*k == i){

         ps = 1;

         System.out.println("The number " + i+ " is: Perfect Square");

         pw.println("The number " + i+ " is: Perfect Square");

        }

      }

      if (ps == 1)

       continue;

      int sum = 0;

      for (int j = 2; j<i; j++){

        if (i % j == 0)

         sum = sum + j;

      }

      if (sum == 0){

        System.out.println("The number " + i+ " is: Prime");

        pw.println("The number " + i+ " is: Prime");

      }

      else if (sum + 1 == i){

        System.out.println("The number " + i+ " is: Perfect");

        pw.println("The number " + i+ " is: Perfect");

      }

      else if (sum + 1 > i){

        System.out.println("The number " + i+ " is: Imperfect Abundant");

        pw.println("The number " + i+ " is: Imperfect Abundant");

      }

      else{

        System.out.println("The number " + i+ " is: Imperfect Deficient");

        pw.println("The number " + i+ " is: Imperfect Deficient");

      }

    }   

       

  }

Output needs to look like this:

Welcome to the Prime, Perfect Square, and Perfect Number Tester

Enter the name of the output file: MyNumData.txt

Enter a start number: 20

Enter a stop number : 30

The number 20 is: Imperfect Abundant

The number 21 is: Imperfect Deficient

The number 22 is: Imperfect Deficient

The number 23 is: Prime

The number 24 is: Imperfect Abundant

The number 25 is: Perfect Square

The number 26 is: Imperfect Deficient

The number 27 is: Imperfect Deficient

The number 28 is: Perfect

The number 29 is: Prime

The number 30 is: Imperfect Abundant

Enter the name of the input file to search: MyNumData.txt

Enter the string to search: prim

The following lines were found:

The number 23 is: Prime

The number 29 is: Prime

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Below is the updated code as per the requirements. Changes are highlighted in bold:

import java.io.BufferedReader;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        String line, fname;

        System.out.print("Enter the name of the input file to search: ");
        fname = scan.nextLine(); // read file name

        ArrayList<String> fileContents = new ArrayList<>();
        System.out.print("Please enter the string to search: ");
        String search = scan.nextLine(); // read string to search

        try {
            FileReader fReader = new FileReader(fname);
            BufferedReader fileBuff = new BufferedReader(fReader);
            while ((line = fileBuff.readLine()) != null) {
                // add to file contents if search string exists in line
                if (line.toLowerCase().contains(search.toLowerCase())) {
                    fileContents.add(line);
                }

            }

            System.out.println("The following lines were found:");
            for (String l : fileContents) {
                System.out.println(l);
            }

            fileBuff.close();

        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }
}

Also, I found one issue in your CodingChallenge5CRM code, you are not closing the PrintWriter instance pw. Please close this using below statement:

pw.close();

Below is the sample output showing execution after the fix:

Enter the name of the input file to search: MyNumData.txt Please enter the string to search: prim The following lines were fo

This completes the requirement. Let me know if you have any queries.

Thanks!

Add a comment
Know the answer?
Add Answer to:
composed the following java code to read a string from a text file but receiving compiling...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Online shopping cart (continued) (Java) Hello, I need help with Java to figure this out. In...

    Online shopping cart (continued) (Java) Hello, I need help with Java to figure this out. In my Shopping Cart Manager Class (Bottom Code), I get "Resource leak: 'sc' is never closed." I have tried multiple things and cannot figure it out. Thank you. Online shopping cart (continued) (Java) Hello, I need help with Java to figure this out. In my Shopping Cart Manager Class (Bottom Code), I get "Resource leak: 'sc' is never closed." I have tried multiple things and...

  • Java Im doing a binary search on an array and need to allow as many queries...

    Java Im doing a binary search on an array and need to allow as many queries as possible and cannot figure out how to. The output should read something like this. Enter a number. 3 3 is a prime number. Enter another number. 4 4 is not a prime number. Enter another number. 8 Current file not large enough for 8. Enter another number. -1 Bye. My code so far looks like this. public static void main(String[] args)    {...

  • I am given an input file, P1input.txt and I have to write code to find the...

    I am given an input file, P1input.txt and I have to write code to find the min and max, as well as prime and perfect numbers from the input file. P1input.txt contains a hundred integers. Why doesn't my code compile properly to show me all the numbers? It just stops and displays usage: C:\> java Project1 P1input.txt 1 30 import java.io.*; // BufferedReader import java.util.*; // Scanner to read from a text file public class Project1 {    public static...

  • Getting started with Java on elvis Download Greeting.java from the class web site. Use FileZilla to...

    Getting started with Java on elvis Download Greeting.java from the class web site. Use FileZilla to place it into your Lab5 directory. Look at the content of your directory to see the file using the command ls Look at the content of the file in your directory using the command more Greeting.java Compile the HelloClass program using the command javac Greeting.java. Then use ls to see your class file. Run the program without parameters using the command java Greeting Run...

  • I need to write a program in java that reads a text file with a list...

    I need to write a program in java that reads a text file with a list of numbers and sorts them from least to greatest. This is the starter file. import java.util.*; import java.io.*; public class Lab3 { static final int INITIAL_CAPACITY = 5; public static void main( String args[] ) throws Exception { // ALWAYS TEST FOR REQUIRED INPUT FILE NAME ON THE COMMAND LINE if (args.length < 1 ) { System.out.println("\nusage: C:\\> java Lab3 L3input.txt\n"); System.exit(0); } //...

  • 1. Import file ReadingData.zip into NetBeans. Also, please download the input.txt file and store it into...

    1. Import file ReadingData.zip into NetBeans. Also, please download the input.txt file and store it into an appropriate folder in your drive. a) Go through the codes then run the file and write the output with screenshot (please make sure that you change the location of the file) (20 points) b) Write additional Java code that will show the average of all numbers in input.txt file (10 points) import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; import java.io.*; 1- * @author mdkabir...

  • My Java code from last assignment: Previous Java code: public static void main(String args[]) { //...

    My Java code from last assignment: Previous Java code: public static void main(String args[]) { // While loop set-up boolean flag = true; while (flag) { Scanner sc = new Scanner(System.in); // Ask user to enter employee number System.out.print("Enter employee number: "); int employee_number = sc.nextInt(); // Ask user to enter last name System.out.print("Enter employee last name: "); String last_name = sc.next(); // Ask user to enter number of hours worked System.out.print("Enter number of hours worked: "); int hours_worked =...

  • How to write a Java file out that that reads from numbers.txt with these numbers 2...

    How to write a Java file out that that reads from numbers.txt with these numbers 2 6 7 9 5 4 3 8 0 1 6 8 2 3 and write to a file called totalSum.txt that looks like: 2+6+7+9=24 and so on using this code import java.io.*; import java.util.Scanner; public class FileScanner {    public static void main(String[] args)    {        /* For Homework! Tokens*/        Scanner file = null;        PrintWriter fout= null;   ...

  • Modify the program that you wrote for the last exercise in a file named Baseball9.java that...

    Modify the program that you wrote for the last exercise in a file named Baseball9.java that uses the Player class stored within an array. The program should read data from the file baseball.txt for input. The Player class should once again be stored in a file named Player.java, however Baseball9.java is the only file that you need to modify for this assignment. Once all of the input data from the file is stored in the array, code and invoke a...

  • Can you help me with this code in Java??? import java.util.Scanner; public class Main { public...

    Can you help me with this code in Java??? import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scan = new Scanner(System.in); int rows = 3; int columns = 4; int[][] arr = new int[rows][columns]; for(int i = 0; i < rows; ++i) { for(int j = 0; j < columns; ++j) { System.out.println("Enter a value: "); arr[i][j] = scan.nextInt(); } } System.out.println("The entered matrix:"); for(int i = 0; i < rows; ++i) { for(int j...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT