Question

In: Computer Science

In Java please Cipher.java: /* * Fix me */ import java.util.Scanner; import java.io.PrintWriter; import java.io.File; import...

In Java please

Cipher.java:

/*
* Fix me
*/
import java.util.Scanner;
import java.io.PrintWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;

public class Cipher {

   public static final int NUM_LETTERS = 26;
   public static final int ENCODE = 1;
   public static final int DECODE = 2;

   public static void main(String[] args) /* FIX ME */ throws Exception {

    // letters
    String alphabet = "abcdefghijklmnopqrstuvwxyz";
      
    // Check args length, if error, print usage message and exit
    if (args.length != 3) {
        System.out.println("Usage:\n");
        System.out.println("java Cipher <filename> <cipher-key> <digit>\n");
        System.out.println("Options:\n");
        System.out.println("filename\tThe filename of the text file to open");
        System.out.println("cipher-key\tThe cipher key for encryption/decryption");
        System.out.println("digit\t\t1 to encode or 2 to decode");

        System.exit(1);
    }

    // Extract input args to variables
           String inputFilename = args[0];
           String key = args[1];
           int action = Integer.parseInt(args[2]);
           if(action != 1 && action != 2) {
               System.out.println("Option " + action + " is not valid");
               System.exit(1);
           }
           String outputFilename = getOutputFilename(inputFilename, action);
           Scanner input = openInput(inputFilename);
           PrintWriter output = openOutput(outputFilename);

    // Read in data and output to file
    // Convert all letters to lowercase for output
    StringBuilder message = new StringBuilder(input.useDelimiter("\\Z").next());

    for(int i = 0; i < message.length(); ++i) {
        int offset = key.charAt(i % key.length()) - 'a';
        if(action == 1) {
            message.setCharAt(i, shiftUpByK(message.charAt(i), offset));
        } else {
            message.setCharAt(i, shiftDownByK(message.charAt(i), offset));
        }
    }

    output.println(message.toString().toLowerCase());

           // Close streams
           input.close();
           output.close();

   }

   /**
   * Open input for reading
   *
   * @param filename
   * @return Scanner
   * @throws FileNotFoundException
   */
   public static Scanner openInput(String filename) throws FileNotFoundException {
       return new Scanner(new File(filename));
   }

  
   /**
   * Open output for writing
   *
   * @param filename
   * @return PrintWriter
   * @throws FileNotFoundException
   */
   static PrintWriter openOutput(String filename) throws FileNotFoundException {
       return new PrintWriter(new File(filename));
   }


/**
* Encode letter by some offset d
*
* @param c input character
* @param offset amount to shift character value
* @return char encoded character
*/
   public static char shiftUpByK(char c, int offset) {
       if ('a' <= c && c <= 'z')
           return (char) ('a' + (c - 'a' + offset) % NUM_LETTERS);
       if ('A' <= c && c <= 'Z')
           return (char) ('A' + (c - 'A' + offset) % NUM_LETTERS);
       return c; // don't encrypt if not an ic character
   }
  
   /**
* Decode letter by some offset d
*
* @param c input character
* @param offset amount to shift character value
* @return char decoded character
*/
   public static char shiftDownByK(char c, int offset) {
       if ('a' <= c && c <= 'z')
           return (char) ('a' + (((c - 'a' - offset) % NUM_LETTERS) + NUM_LETTERS ) % NUM_LETTERS);
       if ('A' <= c && c <= 'Z')
           return (char) ('A' + (((c - 'A' - offset) % NUM_LETTERS) + NUM_LETTERS ) % NUM_LETTERS);
       return c; // don't decrypt if not an ic character
   }

   /**
   * Changes file extension to ".coded" or ".decoded"
   *
   * @param filename
   * @return String new filename or null if action is illegal
   */
   public static String getOutputFilename(String filename, int action) {
       int indexOfExtension = filename.indexOf(".");
       String fileNameWithoutExtension;
       if(indexOfExtension != -1) {
           fileNameWithoutExtension = filename.substring(0, indexOfExtension);
       } else {
           fileNameWithoutExtension = filename;
       }

       if(action == 1) {
           return fileNameWithoutExtension + ".coded";
       } else {
           return fileNameWithoutExtension + ".decoded";
       }
   }


   public String getInfo() {
       return "Program 3, Student's name here";
   }

}

20.23 Program 5b: CipherEx catch exception

Instructor note:

The key is expected to be converted to lowercase before encoding/decoding.

Objectives

  • Command line input
  • File input and output
  • Catching exceptions

Program Description

This program is identical to Cipher.java with these exceptions (no pun intended):

  • You must catch the exceptions when opening the input and output files instead of rethrowing the error in the method headers. For this, your program must output 'Error opening file filename' and exit.
  • You must catch the exceptions when an invalid option is entered for the parameter that decides if the program is to encode or decode. For this, your program must output 'Option option is not valid' and exit.
  • You must catch the exceptions when the wrong number of arguments is passed. For this, your program must output 'Usage: Cipher inputFileName cipherKey (1)encode (2)decode' and exit.

Output

Test case 5 will display an error message:
Error opening file badFilename

Test case 6 will display an error message:
Usage: Cipher inputFileName cipherKey (1)encode (2)decode

The other test cases will be the same as the Cipher class.

Solutions

Expert Solution

I have implemented the updated code to handle the exception per the given description.

Please find the following Code Screenshot, Output, and Code.

ANY CLARIFICATIONS REQUIRED LEAVE A COMMENT

1.CODE SCREENSHOT :

2.OUTPUT :

3.CODE :

/*
* Fix me
*/
import java.util.Scanner;
import java.io.PrintWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;

public class Cipher {

   public static final int NUM_LETTERS = 26;
   public static final int ENCODE = 1;
   public static final int DECODE = 2;
   public static void main(String[] args) /* FIX ME */ throws Exception {
    // letters
    String alphabet = "abcdefghijklmnopqrstuvwxyz";
    // Check args length, if error, print usage message and exit
        try{
    if (args.length != 3) {
        throw new Exception();
    }
        }catch(Exception e){
                System.out.println("Usage: Cipher inputFileName cipherKey (1)encode (2)decode");
        System.exit(1);
        }

    // Extract input args to variables
           String inputFilename = args[0];
           String key = args[1];
           int action = Integer.parseInt(args[2]);
                   try{
           if(action != 1 && action != 2) {
              throw new Exception();
           }}catch(Exception e){
                            System.out.println("Option " + action + " is not valid");
               System.exit(1);
                   }
           String outputFilename = getOutputFilename(inputFilename, action);
           Scanner input = openInput(inputFilename);
           PrintWriter output = openOutput(outputFilename);

    // Read in data and output to file
    // Convert all letters to lowercase for output
    StringBuilder message = new StringBuilder(input.useDelimiter("\\Z").next());

    for(int i = 0; i < message.length(); ++i) {
        int offset = key.charAt(i % key.length()) - 'a';
        if(action == 1) {
            message.setCharAt(i, shiftUpByK(message.charAt(i), offset));
        } else {
            message.setCharAt(i, shiftDownByK(message.charAt(i), offset));
        }
    }

    output.println(message.toString().toLowerCase());

           // Close streams
           input.close();
           output.close();

   }

   /**
   * Open input for reading
   *
   * @param filename
   * @return Scanner
   * @throws FileNotFoundException
   */
   public static Scanner openInput(String filename) {
           Scanner s=null;
           try{
       s=new Scanner(new File(filename));
           }catch(FileNotFoundException e){
                        System.out.println("Error opening file "+filename);
                        System.exit(0);
           }return s;
   }

  
   /**
   * Open output for writing
   *
   * @param filename
   * @return PrintWriter
   * @throws FileNotFoundException
   */
   static PrintWriter openOutput(String filename) throws FileNotFoundException {
       return new PrintWriter(new File(filename));
   }


/**
* Encode letter by some offset d
*
* @param c input character
* @param offset amount to shift character value
* @return char encoded character
*/
   public static char shiftUpByK(char c, int offset) {
       if ('a' <= c && c <= 'z')
           return (char) ('a' + (c - 'a' + offset) % NUM_LETTERS);
       if ('A' <= c && c <= 'Z')
           return (char) ('A' + (c - 'A' + offset) % NUM_LETTERS);
       return c; // don't encrypt if not an ic character
   }
  
   /**
* Decode letter by some offset d
*
* @param c input character
* @param offset amount to shift character value
* @return char decoded character
*/
   public static char shiftDownByK(char c, int offset) {
       if ('a' <= c && c <= 'z')
           return (char) ('a' + (((c - 'a' - offset) % NUM_LETTERS) + NUM_LETTERS ) % NUM_LETTERS);
       if ('A' <= c && c <= 'Z')
           return (char) ('A' + (((c - 'A' - offset) % NUM_LETTERS) + NUM_LETTERS ) % NUM_LETTERS);
       return c; // don't decrypt if not an ic character
   }

   /**
   * Changes file extension to ".coded" or ".decoded"
   *
   * @param filename
   * @return String new filename or null if action is illegal
   */
   public static String getOutputFilename(String filename, int action) {
       int indexOfExtension = filename.indexOf(".");
       String fileNameWithoutExtension;
       if(indexOfExtension != -1) {
           fileNameWithoutExtension = filename.substring(0, indexOfExtension);
       } else {
           fileNameWithoutExtension = filename;
       }

       if(action == 1) {
           return fileNameWithoutExtension + ".coded";
       } else {
           return fileNameWithoutExtension + ".decoded";
       }
   }


   public String getInfo() {
       return "Program 3, Student's name here";
   }

}

Related Solutions

Can you fix the errors in this code? package demo; /** * * */ import java.util.Scanner;...
Can you fix the errors in this code? package demo; /** * * */ import java.util.Scanner; public class Booolean0p {        public class BooleanOp {            public static void main(String[] args) {                int a = 0, b = 0 , c = 0;                Scanner kbd = new Scanner(System.in);                System.out.print("Input the first number: ");                a = kbd.nextInt();                System.out.print("Input...
Can you fix the errors in this code? import java.util.Scanner; public class Errors6 {    public...
Can you fix the errors in this code? import java.util.Scanner; public class Errors6 {    public static void main(String[] args) {        System.out.println("This program will ask the user for three sets of two numbers and will calculate the average of each set.");        Scanner input = new Scanner(System.in);        int n1, n2;        System.out.print("Please enter the first number: ");        n1 = input.nextInt();        System.out.print("Please enter the second number: ");        n2 =...
JAVA ONLY - Complete the code import java.util.Scanner; /** * This program will use the HouseListing...
JAVA ONLY - Complete the code import java.util.Scanner; /** * This program will use the HouseListing class and display a list of * houses sorted by the house's listing number * * Complete the code below the numbered comments, 1 - 4. DO NOT CHANGE the * pre-written code * @author * */ public class HouseListingDemo { public static void main(String[] args) { Scanner scan = new Scanner(System.in); HouseListing[] list; String listNumber, listDesc; int count = 0; double listPrice; String...
----fix code to search and delete a student by Identification number import java.util.Scanner; public class COurseCom666...
----fix code to search and delete a student by Identification number import java.util.Scanner; public class COurseCom666 {     private String courseName;     private String[] students = new String[1];     private int numberOfStudents;     public COurseCom666(String courseName) {         this.courseName = courseName;     }     public String[] getStudents() {         return students;     }     public int getNumberOfStudents() {         return numberOfStudents;     }     public String getCourseName() {         return courseName;     }     public int DeleteStudentsByID() {         return...
Can someone convert this to C++ Please! import java.util.*; // for Random import java.util.Scanner; // for...
Can someone convert this to C++ Please! import java.util.*; // for Random import java.util.Scanner; // for Scanner class game{    public static void main(String args[])    {        // generating a random number        Random rand = new Random();        int code = rand.nextInt(99999) + 1, chances = 1, help, turn, i,match, sum;               // for input        Scanner sc = new Scanner(System.in);               // running for 10 times   ...
NEed UML diagram for this java code: import java.util.ArrayList; import java.util.Scanner; class ToDoList { private ArrayList<Task>...
NEed UML diagram for this java code: import java.util.ArrayList; import java.util.Scanner; class ToDoList { private ArrayList<Task> list;//make private array public ToDoList() { //this keyword refers to the current object in a method or constructor this.list = new ArrayList<>(); } public Task[] getSortedList() { Task[] sortedList = new Task[this.list.size()];//.size: gives he number of elements contained in the array //fills array with given values by using a for loop for (int i = 0; i < this.list.size(); i++) { sortedList[i] = this.list.get(i);...
fix this code in python and show me the output. do not change the code import...
fix this code in python and show me the output. do not change the code import random #variables and constants MAX_ROLLS = 5 MAX_DICE_VAL = 6 #declare a list of roll types ROLLS_TYPES = [ "Junk" , "Pair" , "3 of a kind" , "5 of a kind" ] #set this to the value MAX_ROLLS pdice = [0,0,0,0,0] cdice = [0,0,0,0,0] #set this to the value MAX_DICE_VAL pdice = [0,0,0,0,0,0] cdice = [0,0,0,0,0,0] #INPUT - get the dice rolls i...
Need to able to solve this method WITHOUT using ANY java libraries. ------------------------------ import java.util.Scanner; public...
Need to able to solve this method WITHOUT using ANY java libraries. ------------------------------ import java.util.Scanner; public class nthroot { public static void main(String[] args) { Scanner sc = new Scanner(System.in);    // Read n (for taking the nth root) int num = Integer.parseInt(sc.nextLine());    // Read number to take the nth root of int number = Integer.parseInt(sc.nextLine());    // Read the desired precision int precision = Integer.parseInt(sc.nextLine());    // Print the answer System.out.println(findnthRoot(number, num, precision)); }    private static String...
Please fix all of the errors in this Python Code. import math """ A collection of...
Please fix all of the errors in this Python Code. import math """ A collection of methods for dealing with triangles specified by the length of three sides (a, b, c) If the sides cannot form a triangle,then return None for the value """ ## @TODO - add the errlog method and use wolf fencing to identify the errors in this code def validate_triangle(sides): """ This method should return True if and only if the sides form a valid triangle...
Please convert this java program to a program with methods please. import java.io.*; import java.util.*; public...
Please convert this java program to a program with methods please. import java.io.*; import java.util.*; public class Number{ public static void main(String[] args) {    Scanner scan = new Scanner(System.in); System.out.println("Enter 20 integers ranging from -999 to 999 : "); //print statement int[] array = new int[20]; //array of size 20 for(int i=0;i<20;i++){ array[i] = scan.nextInt(); //user input if(array[i]<-999 || array[i]>999){ //check if value is inside the range System.out.println("Please enter a number between -999 to 999"); i--; } } //...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT