java代写:Arrays, Strings, Testing and Debugging

java代写:这是一个基础的java相关的数组,字符串的代写,涉及了测试和debug调试等方面的内容

Read all instructions in this document before starting any coding!

Table of Contents:

Part 1: Debugging Code [25 Points] Intermission: Background for Caesar Ciphers Part 2. Documentation and Testers for Caesar Cipher [10 Points] Part 3: Caesar Cipher [40 Points] Part 3A: [10 Points] Part 3B: [10 Points] Part 3C [10 Points] Part 3D [10 Points] Extra Credit [5 points] README.md [5 Points] Style [20 Points] Submitting the Assignment Appendix: General Hints and Other Remarks for Parts 1-3

Part 1: Debugging Code [25 Points]

The two files you need for this part:

FunWithIntArrays.java: This class is designed to have some useful features for int arrays but is marred with errors (compile, runtime and logic errors). There are a number of methods in the class whose expected behavior is commented.

ArraysTester.java: This code tests the class FunWithIntArrays. This file is to help you test your changes in the FunWithIntArrays class. You do not need to change this file nor upload it to Vocareum when turning in your work.

1. Part of this assignment is to get more practice with the editing environment of your choice. You may use Vim, eclipse, or any other IDE or text editor of your choice. However, you MUST be comfortable compiling from the command line and navigating Unix.

2. After debugging and fixing the FunWithIntArrays class, compile the ArrayTester.java test driver (original file).

3. Run the ArrayTester program, the output should be the following:

Creating Initial Array:

7, 4, 1, 8, 12, 32, 64, 13,

Creating Array Copy:

7, 4, 1, 8, 12, 32, 64, 13,

Min element is: 1

Max element is: 64

Average value is: 17.625

Testing Sorted Array

1, 4, 7, 8, 12, 13, 32, 64,

List the bugs found in the file header of FunWithIntArrays.java and include a concise and clear description of why the bugs were wrong (see below for instructions.) Do not just list bugs you encountered in the assignment; your descriptions must detail the issues about the bug. They must be specific to FunWithIntArrays.java.

For example, if you fixed the for loop below and it was at line 19:

for (int i = array.length; i >= 0; i–)

to avoid going out of bounds, your entry would look like:

# Error 1: Line 19 Runtime Error – Array out of Bounds – Incorrect: for (int i = array.length; i >= 0; i–) – Fix: for (int i = array.length – 1; i >= 0; i–) Explanation: Correction starts at the first element which is at index array.length-1 rather than array.length. —————————————————————————————— # Error 2: …

Put a sequence of hyphens as above, as well as newlines, between each error for readability.

Submit early and often: When you have finished with the section, submit this section’s Files to turn-in and all previous Files to turn-in together onto Vocareum. Instructions are linked in the beginning.

Files to turn-in for this part: FunWithIntArrays.java

Intermission: Background for Caesar Ciphers

Background

A cipher is an algorithm that takes a message in the form of a sequence of characters called the “plaintext” and returns another sequence of characters called the “ciphertext” which is

1) apparently hard to read, but

2) can be converted back into the original plaintext message. Turning the plaintext into the ciphertext is called encryption; reversing the process is called decryption.

A substitutional cipher is an algorithm that creates a ciphertext by simply substituting, for every occurrence of a particular letter of the alphabet in the plaintext, another particular letter of the alphabet; recovering the plaintext then just involves doing the reverse substitution. In this part, you will implement a kind of substitutional cipher called a rotational cipher or Caesar cipher.

Substitutional ciphers such as the Caesar cipher have been used historically to encode secret diplomatic and military messages, but these days they are not considered very good ways to hide information that you really want to keep secret. In fact, you could fairly trivially write a method that can break one using just character frequencies. More sophisticated modern techniques exist and should be used if you want strong security. But still, substitutional ciphers are useful in some contexts; for example, the “rot 13” rotational cipher is sometimes used to obscure (usually controversial or potentially offensive) text in email or newsgroups.

Functionality

The rotational cipher you will implement in this assignment will affect only letters in the plaintext; numbers, punctuation, etc. are not changed. Here’s why it is called a rotational cipher: Imagine the letters A,B,C,…,X,Y,Z written in order around the rims of two wheels on the same axle, and the wheels lined up so that A on one wheel is next to A on the other, B is next to B, etc. If you peeled the letters off the rims of the wheels and laid them out side-by-side, it would look like:

ABCDEFGHIJKLMNOPQRSTUVWXYZ ABCDEFGHIJKLMNOPQRSTUVWXYZ

Now rotate one of the wheels by one position, and you have the correspondences for the “rot 1” cipher, that substitutes B for A, C for B, … , and A for Z. Again, laid out side-by-side, it would look like:

BCDEFGHIJKLMNOPQRSTUVWXYZA ABCDEFGHIJKLMNOPQRSTUVWXYZ

If instead you rotated one position in the other direction, you have the “rot -1” cipher, which is equivalent to “rot 25”. Laid out, it would look like:

ZABCDEFGHIJKLMNOPQRSTUVWXY ABCDEFGHIJKLMNOPQRSTUVWXYZ

The example shown is a mapping that each letter in the input string should follow. This means that each letter in the input string would have an offset applied to it, mapping into the letter corresponding to the mapping scheme defined by the rotation value.

NOTE: The example of the two wheels spinning shows the mapping scheme of each letter. It does not mean that we are rotating the string as a whole.

“Rot N” ciphers are possible for any integer value of the offset N, but many of them are equivalent; there are only 26 distinct rotational ciphers (including the “rot 0” ‘identity’ cipher shown first above that substitutes each letter with itself, changing nothing). In particular, note that “rot 13” is equivalent to “rot -13”, and so it decodes itself:

NOPQRSTUVWXYZABCDEFGHIJKLM ABCDEFGHIJKLMNOPQRSTUVWXYZ

An important detail: In the rotational cipher you will implement, upper-case letters are always substituted for upper-case letters, and lower-case ones for lower-case ones. The amount of rotation is the same for each. So, you could think of a rotational cipher as really having two sets of wheels, one pair for upper-case and the other for lower-case letters, with each set of wheels rotated the same amount; for example for “rot 13” you would have the correspondences

NOPQRSTUVWXYZABCDEFGHIJKLM ABCDEFGHIJKLMNOPQRSTUVWXYZ nopqrstuvwxyzabcdefghijklm abcdefghijklmnopqrstuvwxyz

Another example:

Plaintext: THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG Ciphertext: QEB NRFZH YOLTK CLU GRJMP LSBO QEB IXWV ALD

In this example, deciphering is done in reverse, with a right shift of 3.

You will use two ways to implement the cipher: (a) by using the standard library Java class String, and (b) by using the StringBuilder class. For both parts, you would be using the Character class provided in the standard Java library.

Part 2. Documentation and Testers for Caesar Cipher [10 Points]

Make sure to read the background on Caesar Ciphers before starting this part.

The files you need for this part:

CaesarWithBugs.class: This is a compiled version of a buggy implementation of the Caesar Cipher you will implement in the next part. We have provided this file under the starter code directory.

Part2Tester.java: This is the tester you will develop for this part. You will submit this file.

In this section, you will learn a new aspect of programming in writing testers – more specifically, unit testers. Unit tests are a series of tests that run against a method to verify their expected behavior. For example, if your method is supposed to calculate the average of 3 integers input by the user your code will work well if the user enters 10, 11 and 12. This input is called the normal case (or happy inputs case.) However, your code may crash if the user enters 10, 2147483647 and 12. This input is called an edge case as 2147483647 is the largest integer allowed for int datatype in Java. Simply adding 10, 2147483647 and 12 will cause an overflow. The ability to find edge cases and appropriate edge cases to test a code is a very important skill that you should gain from 11.

We have provided you with the compiled version (the .class file) of a buggy implementation of the Caesar Cipher that you will implement in the next part of your assignment. You may wish to read carefully the Background and Functionality above before you proceed with this part. jav

We have implemented one version of the encrypt method and one version of the decrypt method. The functionality of these methods are explained in the Java documentation here. You must right-click and download this file, and then open it on your computer locally. Read the documentation and make sure you understand what the methods are supposed to do.

In the file Part2Tester.java you will find the skeleton of a tester for the CaesarWithBugs class’s encrypt and decrypt methods. Your job is to write more tests to uncover as many bugs as you can with these two methods. As you find bugs, describe them at the file header of Part2Tester.java, similarly to what you did in Part1. These tests must be implemented as separate methods, each testing a separate behavior. The methods’ names and headers should descriptively describe what they’re testing. For instance:

// Given an encrypted message,

// When we decrypt the message with a very small rotation,

// Then we get back the original message

public static boolean testDecryptWithSmallPositiveRotation()

Make sure to follow this template when writing your own tests, you will be graded on that as well. In the main method of Part2Tester.java you’ll call all your tests to check if all of them pass. If you find all the 5 (five) bugs there are, at least 5 of your tests should fail. Depending on your perspective, you might count a bug as more than a single bug. But there are 5 classes of error in this code. Take a look at the tests we provided for reference.

Submit early and often: When you have finished with the section, submit this section’s Files to turn-in and all previous Files to turn-in together onto Vocareum. Instructions are linked in the beginning.

Files to turn-in: Part2Tester.java (Include FunWithIntArrays.java in your submission!)

Part 3: Caesar Cipher [40 Points] Make sure to refer to the background on Caesar Ciphers found before Part 2.

You will use three ways to implement the cipher:

(a) by using the standard library Java class String without converting it to a character array;

(b) by manipulating Strings directly as character arrays;

(b) by using the StringBuilder class.

For both parts, you will be using the Character class provided in the standard Java library.

Part 3A: [10 Points]

In this part you will implement the Cypher using basic String operations, including the charAt method to get each character from the string, and the concat method (or +) to build the new String. You will also add tests to a tester for your Cypher methods.

Cypher: To implement the Cypher, complete the following methods to your Caesar class (each of which is described in more detail below) using String operations:

● public static String encryptStr(String s, int rotation)

● public static String decryptStr(String s, int rotation)

● private static char letterOperation(char letter, int rotation)

Here are the details for each method:

public static String encrypt(String s, int rotation)

This method takes a String and an int and creates and returns a new String which is the encrypted version of s where each character which is an upper or lower case letter is shifted forward by the amount rotation, wrapping around when necessary as described above. It should not change non-alphabetic characters. This method returns the new encrypted String.

public static String decrypt(String s, int rotation)

This method will decrypt a String by applying the int rotation in the opposite direction. So a string encrypted with one rotation should should be recovered by calling decrypt with the same value for rotation. This method returns the new decrypted String.

private static char letterOperation(char letter, int rotation)

This method will take a character(char) as an input and perform rotation (indicated by the int parameter) only if the character is an alphabet(Uppercase or Lowercase) and return the rotated character. If the character is not alphabetical (an upper or lower case letter), it will return the original character. This method should be called when encrypt and/or decrypt methods are used. Please note that this method is private. This method will be used in parts B and C as well.

Tester: Next, add tests to the CaesarTester.java main method to test the functions you just wrote. Note that because letterOperation is private, you cannot test that method directly. Hint: Feel free to copy and paste the tests you already wrote in part 2!

⚠️ Notes and restrictions:

● You will be graded on the correctness of your Cypher methods and the completeness of your tester.

● For this assignment, you are NOT allowed to use the built-in toCharArray method provided by standard Java library, nor the other encrypt/decrypt methods you wrote or will write. The penalty for doing so is a zero for this portion of the assignment.

● Note: You cannot change the signature (name, return type, parameters) of any method above. The signatures must remain unchanged otherwise our testers will fail and assign 0 points.

Submit early and often: When you have finished with the section, submit this section’s Files to turn-in and all previous Files to turn-in together onto Vocareum. Instructions are linked in the beginning.

Files to turn-in: Caesar.java, CaesarTester.java (Include previous parts’ files! FunWithIntArrays.java, Part2Tester.java)

Part 3B: [10 Points]

In this part you will implement the Cypher using a character array, by using the built-in string method toCharArray. You must also directly store the encrypted/decrypted characters in a character array. Before returning, convert that array to a String.

Cypher: To implement the Cypher, complete the following methods to your Caesar class (each of which is described in more detail below) directly using character arrays.

● public static String encryptChArr(String s, int rotation)

● public static String decryptChArr(String s, int rotation)

While the parameter types, return type, and the behavior of these methods are identical to Part A’s methods, the implementation details (the algorithm) will differ.

When you have completely filled out the character array with the result, convert it to a String, and then return that String.

Tester: Next, add tests to the CaesarTester.java main method to test the functions you just wrote. Note that because letterOperation is private, you cannot test that method directly. Hint: Feel free to copy and paste the tests you already wrote in part 2!

⚠️ Notes and restrictions:

● For this assignment, you are NOT allowed to use the built-in concat method nor the + concatenation operator of Strings provided by standard Java library. You also must NOT use the other encrypt/decrypt methods you wrote or will write. The penalty for doing so is a zero for this portion of the assignment.

● Note: You cannot change the signature (name, return type, parameters) of any method above. The signatures must remain unchanged otherwise our testers will fail and assign 0 points.

Submit early and often: When you have finished with the section, submit this section’s Files to turn-in and all previous Files to turn-in together onto Vocareum. Instructions are linked in the beginning.

Part 3C [10 Points]

For this part, you are required to use the StringBuilder class, which is a class similar to String class and is also included in the java.lang package. The intention of this section is for you to implement a behavior using a class that has already been written. Refer to the official documentation for StringBuilder for all information regarding StringBuilder itself. (PDF Version in case link doesn’t work)

By using StringBuilder objects, we will be able to manipulate sequences of characters in much faster runtime than if we used String objects. The reason is that whenever we manipulate a String object, we create new objects, which takes up more memory. On the other hand, since we are able to manipulate a StringBuilder object within itself, the runtime of it would be faster.

Cypher: To implement this part of the cipher, complete the following methods in your Caesar class (each of which is described in more detail below):

● public static String encryptSB(String s, int rotation)

● public static String decryptSB(String s, int rotation)

While the parameter types, return type, and the behavior of these methods are identical to Part A’s methods, the implementation details (the algorithm) will differ.

You will initiate an instance of a StringBuilder and use it to manipulate the string in progress. The StringBuilder keeps the String inside (StringBuilder has a String inside it, starting with an empty string “”) and manipulates that string. Use method calls to instruct how you want to manipulate the string.

When the string is finished, make the StringBuilder return the String to you, and then return the String.

Tester: Add tests to the CaesarTester.java main method to test the functions you just wrote. Note that because letterOperation is private, you cannot test that method directly. Hint: Feel free to copy and paste the tests you already wrote in part 2 and/or that you used for the encrypt and decrypt methods!

Notes and restrictions:

● You will be graded on the correctness of your Cypher methods and the completeness of your tester.

● For this PA, you are NOT allowed to use the built-in setCharAt method provided by standard Java library, nor the other encrypt/decrypt method you wrote or will write. The penalty for doing so is a zero for this portion of the assignment.

● Note: You cannot change the signature (name, return type, parameters) of any method above. The signatures must remain unchanged otherwise our testers will fail and assign 0 points.

Submit early and often: When you have finished with the section, submit this section’s Files to turn-in and all previous Files to turn-in together onto Vocareum.

Part 3D [10 Points]

Finally, we want to see how much more efficient using StringBuilder is compared to just using String, and also how using a character array is the most efficient of all (and why’s that?)

We have provided a file for you called “script” that tests the runtime of the two method you wrote on encrypting. To run it, type the following Linux command:

./script

The If you’re on Windows you should run this script on an ieng6 machine. If you get the message Permission denied, then do the following instead:

chmod u+x ./script

./script

The script will show you the time of running encrypt as implemented using StringBuilder, and encrypt as implemented using String concatenation. An example of it is:

Timing for encryptSB method:

real 0m1.136s

user 0m0.969s

sys 0m0.310s

Timing for encryptChArr method:

real 0m0.824s

user 0m0.879s

sys 0m0.240s

Timing for encryptStr method:

real 0m18.654s

user 0m18.114s

sys 0m0.515s

NOTE: This is an example. The only thing you need to get “correct” is to show the output similar to above. encryptChArr should be the fastest, closely followed by encryptSB, with encryptStr coming at a distant third. However, your methods do not need to exactly match these times. We only care about correctness for now. No need to worry about efficiency.

By using the script, answer the following questions in a file called part3d.txt :

1. Run the script three times. Write down the “real” runtime for each method of each trial in the file.

2. Why is using StringBuilder more efficient than directly manipulating a string? Explain the reasoning in your own words.

3. Why is using a character array the fastest?

4. Compare and contrast how easy/hard, fast/slow, straightforward/complicated it was to code each Part.

Submit early and often: When you have finished with the section, submit this section’s Files to turn-in and all previous Files to turn-in together onto Vocareum. Instructions are linked in the beginning.

Files to turn-in: part3d.txt (Include previous parts’ files! FunWithIntArrays.java, Part2Tester.java, Caesar.java, CaesarTester.java)

Extra Credit [5 points]

Introduction

The extra credit portion of your PAs is an opportunity for you to go beyond the requirements of the assignment to explore topics that are interesting to you, and to really challenge yourself.

Here are the reasons to do extra credit:

● You get really into the assignment and you want to explore more, or want an additional challenge.

● You think you will ask me for a recommendation letter at some point in the future. Doing the extra credit allows me to talk concretely about how you went above and beyond the course requirements, and sounds much better than “this student did well, they got an A”.

● You will have a couple more points towards your final grade!

Assignment

You implemented a very simple encryption mechanism in part 1. However, the Caesar Cypher is NOT secure. Your task is to research and then implement an additional encryption scheme. You should create a new class named ExtraCreditEncryption which must, at a minimum, support an encrypt and decrypt method. This is an extremely open-ended assignment, and most encryption schemes will be far too complicated to implement. We recommend that you Google for “text encryption assignment” because that will turn up algorithms that are suitable for implementation in a class setting. However, be sure you don’t accidentally stumble on the answer to any of the required portions of the assignment (if you do, put it away immediately).

In a header comment at the top of your file, include an overview of what encryption/decryption algorithm you chose. The main method in this file should run your encrypt and decrypt methods on several test cases, and print the results, so that we can see that your methods work correctly.

Submission Instructions

● You must also turn in ExtraCreditEncryption.java and optionally any other additional files you created.

README.md [5 Points]

In a file called “README.md”, write a concise summary for each part. Explain the requirements of each part, what you learned, and what your programs, testers, or both did. Your descriptions should be concise and understandable.

The audience of the README is anyone who does not know any programming or computer science at all. This means use absolutely no Java or CSE terms like “methods” and “variables”, but high-level terms like “program” are fine. Describe the general intention and procedure, as well as your methodology.

Since there are three parts, there are three sections in your README. Each section includes the brief summary of each part, the description of the programs and testers, and what you learned. Therefore, your README will contain three summaries, three sets of descriptions, and three sets of explanations of what you learned. For example, for the tester section, a summary could be:

● “In this section, we wrote testers for code we were not able to read. Rather, the testers were based on the documentation and our task was to figure out whether the functions had correct behavior.”

● “Part2Tester.java contains the code I wrote to test the provided functions for correctness.”

● “I learned to check for edge cases, and that sometimes code appears to work, but when you use bigger numbers, it fails.”

Do write the README in your own words, though.

Style [20 Points] Refer to the complete guidelines and a set of examples of what your style should look like.

1. [2 points] File header

2. [1 point ] Class header

3. [3 points] Method header

4. [3 points] Use proper indenting

5. [1 point ] Use descriptive variable names

6. [2 points] Avoid using magic numbers – When to use variables for magic number?

– (1) When you use unique values with unexplained meaning (eg. LARGE_NUMBER for 999999, etc.)

– (2) When you use a value for multiple times, or a value that may change in the future (eg. GRID_SIZE in a board game, like 2048 or Monopoly)

7. [3 points] Write short methods

8. [3 points] Write short lines

9. [2 points] Write appropriate inline comments

Submitting the Assignment How to Submit on Vocareum

Submission Files: (Make sure your assignment submission contains all of the files and they work on the ieng6 lab machines!)

Regular submission:

● Part 1:

○ FunWithIntArrays.java

● Part 2:

○ Part2Tester.java

● Part 3:

○ Caesar.java

○ CaesarTester.java

○ part3d.txt

● README.md

Extra credit:

● ExtraCreditEncryption.java

● Any other files you created necessary for your StarPointEncryption.java

Maximum Score Possible: 100 out of 100 Points + 5 points for extra credit

If you noticed after each part, “Submit early and often” was written. Submitting your code after each section is one way of doing it. As you progress through this assignment, we reminded you to submit at least part of the assignment until the entire assignment is sent. In future PAs, it is up to you to remember to submit early and often.

Appendix: General Hints and Other Remarks for Parts 1-3

1. START EARLY! Go to discussion sections and tutoring hours for help.

2. Before you write any Java code, be sure you clearly understand the concept of a rotational cipher. Here are some examples of input-output behavior of the encrypt and decrypt methods: The rotational offset can be any int (positive, negative or 0); but any rotational offset will be equivalent to one in the range 0 through 25. For example, it can be seen that a rotation of -39 is equivalent to one of 13, and a rotation of 26 is equivalent to one of 0.

Thinking about this in terms of what the “edges” are might help you here.

3. The standard library Java class Character contains some static methods that may be useful to you in this assignment:

public static boolean isLetter(char c) public static boolean isUpperCase(char c) public static boolean isLowerCase(char c)

The String class defines many instance methods, and so these are instance methods that every String object has. Some important ones are described in Chapter 4 of the text. For this assignment, the most useful ones are probably these:

public int length() public char charAt(int index)

public char[] toCharArray() <- for Part 3B ONLY, returns a String as a character array public String(char[] arr) <- you can do new String(arr), where arr is a char array 4. Note that in Java, Strings are immutable, that is, no String instance method can change anything about the contents of a String object once it is created. In particular, the String object passed in as argument to your encryptStr(String, int) and decryptStr(String, int) methods cannot itself be modified by those methods. Instead, you will loop through the chars in that String, translating them one-by-one according to the required rotational cipher, and building up new Strings by string concatenation, until you get the resulting String you want, and then return that String. 5. One thing that can help in correctly computing the rotational substitution for a letter is understanding how to deal with char values as numerical values. Given the numerical value of a char, you can add a number to it (an offset, given by the rotation), and so get the char for the corresponding ciphertext letter. 6. To operate on the numerical value of a char, it can be cast to int, or assigned it to an int variable, or in some contexts it will be automatically converted to int for you. The value so obtained is the Unicode code for the char, which for us is the same as the ASCII code. ASCII code charts are available many places online; looking at such a chart, you can see that all the uppercase letters are in order, and have int values in the range 65 (which is the int value of the char 'A') through 90 (which is the int value of 'Z'). Similarly, the lowercase letters have the 26 int values in order in the range 97 through 122, which are the int values of 'a' and 'z' respectively. 7. When computing a letter substitution, the resulting letter has to have an int value in the appropriate range: uppercase letters go only to uppercase letters, and lowercase to lowercase. So, when applying an offset to a letter, you have to make sure you "wrap back around" so you do not exceed the limits of the range. This "wrapping around" makes sure the transformation is a rotation, and not just a simple offset. As an example, suppose you want to compute the substitution for char 'd', with a rotation of -40. This is equivalent to a positive rotation of 12. (Make sure you handle any rotation amount, including negative rotations, correctly!) Adding this offset to the int value of 'd', we get (int)'d' + 12 as the numerical value of the letter we want. We can convert back to char with a cast: (char) ((int)'d' + 12) which is the char 'p'. Now suppose you want to apply the same rotation of 12 to the char 'Q'. The expression (char) ((int)'Q' + 12) yields an int value corresponding to character ']'; but it should be 'C'. The problem is that adding 12 to 'Q' gives an int greater than 90, so it goes past the end of the range of the uppercase chars. If you take this approach, you need to figure out how to "wrap back around" in all cases like this. 8. Different from String objects, a StringBuilder object is mutable. We are able to change the calling object itself. The class contains methods such as append and insert that would enable us to alter the objects themselves. This means that while it’s not possible to “edit” a Strin

发表评论

电子邮件地址不会被公开。 必填项已用*标注