Question

In: Computer Science

I am having an issue with trying to make my code to have a required output...

I am having an issue with trying to make my code to have a required output

////////////Input//////////

With computer science, you can work in any industry.
0

//////////Output//////////

Required Output

Enter some text to encrypt\n
Enter a key\n
Error: Key is divisible by 26. That's a bad key!\n
Useless key: 0\n

///////////Cipher.java///////// ------------ My code.

public class Cipher
{
    private String plainText;
    private int key;

    public Cipher(String text, int key) throws EmptyPlainText, UselessKeyException
    {
        if (text == null || text.length() == 0)
        {
            throw new EmptyPlainText("Error: Nothing to encrypt!");
        }
        if (key % 26 == 0)
        {
            throw new UselessKeyException(26, "Error: Key is divisible by 26. That's a bad key!");
        }

        this.plainText = text;
        this.key = key;
    }

    public String getPlainText()
    {
        return plainText;
    }

    public int getKey()
    {
        return key;
    }

    public String getCipherText()
    {
        String cipher = "";
        int k = key % 26;
        char c;
        int integer;

        for (int counter = 0; counter < plainText.length(); counter++)
        {
            c = plainText.charAt(counter);
            if (Character.isUpperCase(c))
            {
                integer = c - 'A';
                integer += k;
                integer %= 26;
                c = (char) (integer + 'A');
            } else if (Character.isLowerCase(c))
            {
                integer = c - 'a';
                integer += k;
                integer %= 26;
                c = (char) (integer + 'a');
            } else
                c += k;

            cipher += c;
        }
        return cipher;
    }
}

///////////CipherDemo/////////

import java.util.Scanner;

public class CipherDemo {
    public static void main(String[] args) {
        Scanner keyboard = new Scanner(System.in);
        System.out.println("Enter some text to encrypt");
        String input = keyboard.nextLine();
        System.out.println("Enter a key");
        int key = keyboard.nextInt();

        try {
            Cipher c = new Cipher(input, key);
            System.out.println("Plain text: " + c.getPlainText());
            System.out.println("Cipher text: " + c.getCipherText());
            System.out.println("Key: " + c.getKey());
        } catch (EmptyPlainText e) {
            System.out.println(e.getMessage());
        } catch (UselessKeyException e) {
            System.out.println(e.getMessage());
            System.out.println("Useless key: " + e.getUselessKey());
        }
    }
}

Solutions

Expert Solution

//Java code

public class EmptyPlainText extends Exception {
   String message;
    public EmptyPlainText()
    {
        super();
        message ="";
    }
    public EmptyPlainText(String message)
    {
        super(message);
    }

    @Override
    public String getMessage() {
        return message;
    }
}

//======================================

public class UselessKeyException extends Exception {
    String message;
    int uselessKey;
    public UselessKeyException()
    {
        super();
        message ="";
        uselessKey=0;
    }
    public UselessKeyException(int uselessKey,String message)
    {
        this.message = message;
        this.uselessKey = uselessKey;
    }

    @Override
    public String getMessage() {
        return message;
    }

    public int getUselessKey() {
        return uselessKey;
    }

    @Override
    public synchronized Throwable getCause() {
        return super.getCause();
    }
}

//=====================================

public class Cipher
{
    private String plainText;
    private int key;

    public Cipher(String text, int key) throws EmptyPlainText, UselessKeyException
    {
        if (text == null || text.length() == 0)
        {
            throw new EmptyPlainText("Error: Nothing to encrypt!");
        }
        if (key % 26 == 0)
        {
            throw new UselessKeyException(key , "Error: Key is divisible by 26. That's a bad key!");
        }

        this.plainText = text;
        this.key = key;
    }

    public String getPlainText()
    {
        return plainText;
    }

    public int getKey()
    {
        return key;
    }

    public String getCipherText()
    {
        String cipher = "";
        int k = key % 26;
        char c;
        int integer;

        for (int counter = 0; counter < plainText.length(); counter++)
        {
            c = plainText.charAt(counter);
            if (Character.isUpperCase(c))
            {
                integer = c - 'A';
                integer += k;
                integer %= 26;
                c = (char) (integer + 'A');
            } else if (Character.isLowerCase(c))
            {
                integer = c - 'a';
                integer += k;
                integer %= 26;
                c = (char) (integer + 'a');
            } else
                c += k;

            cipher += c;
        }
        return cipher;
    }
}

//==============================

import java.util.Scanner;

public class CipherDemo {
    public static void main(String[] args) {
        Scanner keyboard = new Scanner(System.in);
        System.out.println("Enter some text to encrypt");
        String input = keyboard.nextLine();
        System.out.println("Enter a key");
        int key = keyboard.nextInt();

        try {
            Cipher c = new Cipher(input, key);
            System.out.println("Plain text: " + c.getPlainText());
            System.out.println("Cipher text: " + c.getCipherText());
            System.out.println("Key: " + c.getKey());
        } catch (EmptyPlainText e) {
            System.out.println(e.getMessage());
        } catch (UselessKeyException e) {
            System.out.println(e.getMessage());
            System.out.println("Useless key: " + e.getUselessKey());
        }
    }
}

//Output

//If you need any help regarding this solution ........... please leave a comment ..... thanks

"C:\Program Files\Javaljdk1.8.0_221\bin\java.exe" ... Enter some text to encrypt Java Enter a key Error: Key is divisible by 26. That's a bad key! Useless key: 26 Process finished with exit code 0


Related Solutions

I have the following code for my java class assignment but i am having an issue...
I have the following code for my java class assignment but i am having an issue with this error i keep getting. On the following lines: return new Circle(color, radius); return new Rectangle(color, length, width); I am getting the following error for each line: "non-static variable this cannot be referenced from a static context" Here is the code I have: /* * ShapeDemo - simple inheritance hierarchy and dynamic binding. * * The Shape class must be compiled before the...
I am having an issue with the code. The issue I am having removing the part...
I am having an issue with the code. The issue I am having removing the part when it asks the tuter if he would like to do teach more. I want the program to stop when the tuter reaches 40 hours. I believe the issue I am having is coming from the driver. Source Code: Person .java File: public abstract class Person { private String name; /** * Constructor * @param name */ public Person(String name) { super(); this.name =...
I am trying to make a new code that uses functions to make it. My functions...
I am trying to make a new code that uses functions to make it. My functions are below the code. <?php */ $input; $TenBills = 1000; $FiveBills = 500; $OneBills = 100; $Quarters = 25; $Dimes = 10; $Nickels = 5; $Pennies = 1; $YourChange = 0; $input = readline("Hello, please enter your amount of cents:\n"); if(ctype_digit($input)) { $dollars =(int)($input/100); $cents = $input%100;    $input >= $TenBills; $YourChange = (int)($input/$TenBills); $input -= $TenBills * $YourChange; print "Change for $dollars dollars...
Working with Python. I am trying to make my code go through each subject in my...
Working with Python. I am trying to make my code go through each subject in my sample size and request something about it. For example, I have my code request from the user to input a sample size N. If I said sample size was 5 for example, I want the code to ask the user the following: "Enter age of subject 1" "Enter age of subject 2" "Enter age of subject 3" "Enter age of subject 4" "Enter age...
I am trying to get this code to work but I am having difficulties, would like...
I am trying to get this code to work but I am having difficulties, would like to see if some one can solve it. I tried to start it but im not sure what im doing wrong. please explain if possible package edu.hfcc; /* * Create Java application that will create Fruit class and Bread class * * Fruit class will have 3 data fields name and quantity which you can change. * The third data field price should always...
This is my code for python. I am trying to do the fourth command in the...
This is my code for python. I am trying to do the fourth command in the menu which is to add an employee to directory with a new phone number. but I keep getting error saying , "TypeError: unsupported operand type(s) for +: 'dict' and 'dict". Below is my code. What am I doing wrong? from Lab_6.Employee import * def file_to_directory(File): myDirectory={}       with open(File,'r') as f: data=f.read().split('\n')    x=(len(data)) myDirectory = {} for line in range(0,199):      ...
this is my code in python I am trying to open a file and then print...
this is my code in python I am trying to open a file and then print the contents on my console but when i run it nothing prints in the console def file_to_dictionary(rosterFile): myDictionary={}    with open(rosterFile,'r') as f: for line in f: myDictionary.append(line.strip()) print(myDictionary)             return myDictionary    file_to_dictionary((f"../data/Roster.txt"))      
This is the code I have. My problem is my output includes ", 0" at the...
This is the code I have. My problem is my output includes ", 0" at the end and I want to exclude that. // File: main.cpp /*---------- BEGIN - DO NOT EDIT CODE ----------*/ #include <iostream> #include <fstream> #include <sstream> #include <iomanip> using namespace std; using index_t = int; using num_count_t = int; using isConnected_t = bool; using sum_t = int; const int MAX_SIZE = 100; // Global variable to be used to count the recursive calls. int recursiveCount =...
hello, I am having an issue with a question in my highway engineering course. the question...
hello, I am having an issue with a question in my highway engineering course. the question is: An equal tangent sag vertical curve has an initial grade of –2.5%. It is known that the final grade is positive and that the low point is at elevation 82 m and station 1 + 410.000. The PVT of the curve is at elevation 83.5 m and the design speed of the curve is 60 km/h. Determine the station and elevation of the...
I am having trouble with my assignment and getting compile errors on the following code. The...
I am having trouble with my assignment and getting compile errors on the following code. The instructions are in the initial comments. /* Chapter 5, Exercise 2 -Write a class "Plumbers" that handles emergency plumbing calls. -The company handles natural floods and burst pipes. -If the customer selects a flood, the program must prompt the user to determine the amount of damage for pricing. -Flood charging is based on the numbers of damaged rooms. 1 room costs $300.00, 2 rooms...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT