Question

Part B: Java Programming Problems. Choose 2 of the following problems. Each solution is worth 20 marks. You are expected to u

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

1) Java Program to copy Sentence from file to another file

original.txt

- 0 x original - Notepad File Edit Format View This is a Sentence Help In 1, Col 19 100% Windows (CRLF) UTF-8

CODE

import java.io.*;
import java.io.FileReader;
import javax.swing.*;
public class Main
{
   // Function to reverse String
    public static String reverse(String sentence)
    {
        if (sentence.isEmpty()) {
           return sentence;
        }
        return reverse(sentence.substring(1)) + sentence.charAt(0);
    }
   public static void main(String[] args) throws IOException{
       // Reading a File from given path
        FileReader fr=new FileReader(new File("C:\\Users\\ChiTTi ThaLLI\\Desktop\\original.txt"));
        // Creating BufferReader to Read data from file
        BufferedReader br = new BufferedReader(fr);
        String s=br.readLine(); // Reading sentence from file
        br.close(); // Closing Buffered Reader
        fr.close(); // Closing FileReader
        // Creating FileWriter to create and write to a file
        FileWriter fw=new FileWriter("C:\\Users\\ChiTTi ThaLLI\\Desktop\\copy.txt");
        String reversed=reverse(s); // Calling function to reverse string, storing to variable
        fw.write(reversed);        // Writing reversed string to file
        fw.close();                   // Closing FileWriter
        JFrame f=new JFrame();       // Creating JFrame to display message
        JOptionPane.showMessageDialog(f,"Successfully Copied"); // Displaying message
        System.exit(1);               // Terminating Java Program
   }
}

OUTPUT

Message 0 Successfully copied OK

copy.txt

copy - Notepad File Edit Format View ecnetnes a si siht Help In 1, Col1 100% Windows (CRLF) UTF-8

CODE in EDITOR

Main.java X 10 import java.io.*; 2 import java.io.FileReader; 3 import javax.swing. *; 4 public class Main 5 { // Function to

2) Java program to remove duplicates from array and print top 5 from array

CODE

import java.util.Scanner;
import java.util.Arrays;
public class Duplicate {

   @SuppressWarnings("resource")
   public static void main(String[] args) {
       // Scanner class instance read user input
       Scanner scan=new Scanner(System.in);
       int array[]=new int[10];   // Creating array of size 10
       int n = array.length;       // Getting array size
       for(int i=0;i<10;i++) {
           array[i]=scan.nextInt();// Scanning 10 values from user
       }
       System.out.print("Original Array : ");
       for(int i=0;i<10;i++) {
           System.out.print(array[i]+" ");
       }
       System.out.println();
       Arrays.sort(array);
       System.out.print("Sorted Array : ");
       for(int i=0;i<10;i++) {
           System.out.print(array[i]+" ");
       }
       System.out.println();
       n = removeDuplicates(array, n); // Calling function to get nonduplicate values index
       int[] array2=new int[n];       // Creating new array to store non duplicate values
       for(int i=0;i<n;i++) {
           array2[i]=array[n-i-1];
       }
       System.out.print("Array Without Duplicates : ");
       for(int i=0;i<n;i++) {
           System.out.print(array2[i]+" ");
       }
       System.out.println();
       int maxim=0;
       if(array2.length>4) {
           maxim=5;
       }else {
           maxim=array2.length;
       }
       System.out.print("Top 5 numbers from Highest to Lowest : ");
       for(int i=0;i<maxim;i++) {
           System.out.print(array2[i]+" ");
       }
       System.out.println();
   }
   // Function to remove duplicate elements
    // This function returns new size of modified
    // array.
    static int removeDuplicates(int arr[], int n)
    {
        if (n == 0 || n == 1)
            return n;
     
        // To store index of next unique element
        int j = 0;
     
        // Doing same as done in Method 1
        // Just maintaining another updated index i.e. j
        for (int i = 0; i < n-1; i++)
            if (arr[i] != arr[i+1])
                arr[j++] = arr[i];
     
        arr[j++] = arr[n-1];
     
        return j;
    }

}

OUTPUT in CONSOLE

** E * ? @- pre @ Console X <terminated> Duplicate [Java Application] C:\Program FilesVava\jdk-13\bin\javaw.exe (20-Feb-2020,

CODE in EDITOR

Duplicate.java X 10 import java.util.Scanner; 2 import java.util.Arrays; 3 public class Duplicate ! @SuppressWarnings (resou

6BqHjy5JWPgAAAAASUVORK5CYII=

3) Java program to count no.of Lines and no.of Words in a file

counting.txt

Help counting - Notepad File Edit Format View This is text file this file contains 4 lines and 12 words In 1, Col1 100% Windo

CODE

import java.io.*;

// Class to count lines and words in a file
public class Couting {

   public static void main(String[] args) throws IOException{
       // Creating a FileReader instance with given file path
       FileReader fr=new FileReader(new File("C:\\Users\\ChiTTi ThaLLI\\Desktop\\counting.txt"));
       // Creating BufferedReader to read data from file
       BufferedReader br = new BufferedReader(fr);
       String s;                               // String to store data
       int lines_count=0;                       // Variable to store lines count
       int word_count=0;                       // Variable to store word count
       while((s = br.readLine()) != null){       // Loop until reaches END OF FILE
           lines_count=lines_count+1;            // Incrementing Lines count
           if(!(s.equals("")))                // Checking line is not empty
            {
               String[] words = s.split(" ");   // Splitting string and store words into array
               word_count=word_count+words.length; // Incrementing word count by size of array above
            }
       }
       br.close();   // Closing bufferedreader
       fr.close(); // CLosing file reader
      
       // Printing Lines count and Word count
       System.out.println("Lines count in File: "+lines_count);
       System.out.println("Word count in File: "+word_count);
   }

}

OUTPUT in CONSOLE

Console X <terminated> Couting [Java Application] C:\Program FilesVava Lines count in File: 4 Word count in File: 12

CODE IN EDITOR

Couting.java X 1 import java.io.*; 3 // Class to count lines and words in a file 4 public class Couting { public static void

Feel free to ask any doubts in the comment section below

NOTE: Could you Please Consider my Efforts on this work and Give UP VOTE.

Thank YOU : )

Add a comment
Know the answer?
Add Answer to:
Part B: Java Programming Problems. Choose 2 of the following problems. Each solution is worth 20...
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
  • Word count. A common utility on Unix/Linux systems. This program counts the number of lines, words...

    Word count. A common utility on Unix/Linux systems. This program counts the number of lines, words (strings of characters separated by blanks or new lines), and characters in a file (not including blank spaces between words). Write your own version of this program. You will need to create a text file with a number of lines/sentences. The program should accept a filename (of your text file) from the user and then print three numbers: The count of lines/sentences The count...

  • Prelab Exercises Your task is to write a Java program that will print out the following...

    Prelab Exercises Your task is to write a Java program that will print out the following message (including the row of equal marks): Computer Science, Yes!!!! ========================= An outline of the program is below. Complete it as follows: a. In the documentation at the top, fill in the name of the file the program would be saved in and a brief description of what the program does. b. Add the code for the main method to do the printing. //...

  • import java.util.Scanner; // TASK #1 Add the file I/O import statement here /** This class reads...

    import java.util.Scanner; // TASK #1 Add the file I/O import statement here /** This class reads numbers from a file, calculates the mean and standard deviation, and writes the results to a file. */ public class StatsDemo { // TASK #1 Add the throws clause public static void main(String[] args) { double sum = 0; // The sum of the numbers int count = 0; // The number of numbers added double mean = 0; // The average of the...

  • Using the Design Recipe, write an algorithm for each of the following programming problems, showing all...

    Using the Design Recipe, write an algorithm for each of the following programming problems, showing all work (i.e., Contract, Purpose Statement, Examples and Algorithm): 5.Write a program that reads two times in military format (e.g., 0900, 1730) and prints the number of hours and minutes between the two times. Note that the first time can come before or after the second time. 6.An online bank wants you to create a program that shows prospective customers how their deposits will grow....

  • Choose 3 of 5 Problems to Solve Need Soon as possible Choose 3 of5 Problems to...

    Choose 3 of 5 Problems to Solve Need Soon as possible Choose 3 of5 Problems to Solve (20 Point/Each) Problem l: Triangle Printing Program: Write an application that prints a right triangle with 1 to 8 rows. Prompt the user to enter an odd number in the range of 1 to 8 to specify the number of rows in the diamond. Add a validation loop to ensure the user does not enter an even number or a number outside the...

  • ** Language Used : Python ** PART 2 : Create a list of unique words This...

    ** Language Used : Python ** PART 2 : Create a list of unique words This part of the project involves creating a function that will manage a List of unique strings. The function is passed a string and a list as arguments. It passes a list back. The function to add a word to a List if word does not exist in the List. If the word does exist in the List, the function does nothing. Create a test...

  • Kindly solve this using C PROGRAMMING ONLY. 4. Write a program marks.c which consists of a...

    Kindly solve this using C PROGRAMMING ONLY. 4. Write a program marks.c which consists of a main function and three other functions called. readmarks , changemarks (, and writemarks() The program begins by calling the function readmarks () to read the input file marksin. txt which consists of a series of lines containing a student ID number (an integer) and a numeric mark (a float). Once the ID numbers and marks have been read into arrays (by readmarks () the...

  • Overview These exercises will allow you to have some practice with basic Java file Input/Output. In...

    Overview These exercises will allow you to have some practice with basic Java file Input/Output. In addition, you will also have an opportunity to have more practice with methods and arrays.   Objectives Practice with programming fundamentals Variables - Declaration and Assignment Primitive types Arithmetic Expressions Simple keyboard input and text display output Branching - if-elseif-else syntax Loops - simple while loops, nested while loops Methods - functions and procedures ArrayLists - collections of variables File I/O Works towards the following...

  • Solve the following three problems using "Java with Akka Actors". Read the submission instructions carefully. Problem...

    Solve the following three problems using "Java with Akka Actors". Read the submission instructions carefully. Problem 1 (25 Points): Fibonacci Numbers 1. Develop an actor program for computing Fibonacci numbers concurrently. Particularly, create an actor which receives a request for a particular Fibonacci number from a client actor. If it is one of the base cases, the actor replies with a message containing the answer; otherwise, it creates the two sub-problems you would normally create in a recursive implementation. It...

  • How can I create Loops and Files on Java? • Create a program that reads a...

    How can I create Loops and Files on Java? • Create a program that reads a list of names from a source file and writes those names to a CSV file. The source file name and target CSV file name should be requested from the user • The source file can have a variable number of names so your program should be dynamic enough to read as many names as needed • When writing your CSV file, the first row...

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