EvilZone
Programming and Scripting => Java => : Deque December 06, 2012, 06:11:54 PM
-
Hello EZ,
a member here asked me if I could teach some Java.
I did some Skype sessions in the past, however, that won't work anymore, since I have to care for a little baby and I can't plan anything. But I promised to give assignments, answer questions and review the code.
The final goal will be a cryptography application with a Swing GUI, so not only learning Java, but also some cryptography on the way.
I will post the assignments here for everyone who wants to join, so that maybe more people can profit from that.
The first assignment only needs some basics in command line input/output and loops.
If you have any questions, just ask.
1. Assignment - basic IO
Write a program that asks a user for input. If the user presses enter, the input is echoed back to the command line. The computer asks again for input (and echoes it back) until the user enters "exit" or "quit".
An example output might look like this:
your input?
aaa
aaa
your input?
Hello
Hello
your input?
exit
2. Assignment - encoding a string
Modify your program from assignment 1.
Instead of repeating the user input the computer prints out the letters that follow right after in the ASCII chart.
Have a look at the ASCII chart here: http://www.asciitable.com/ (http://www.asciitable.com/)
Example output:
your input?
a
b
your input?
ab;
bc<
your input?
zZ8
{[9
Hint: Make use of the data type char. The value of a char is the same as in the ASCII table, i.e. 'a' == 97.
3. Assignment - a shift cipher
Modify your program from assignment 2.
You have to add a little feature now. In assigment 2 every character of the string was shifted by one character. Now let the user decide how many characters should be shifted.
Set bounds to the characters used. The bounds should be from 32 (= ' ') to 126 ('~').
So if your program shifts over the bounds (overflow) it should shift the rest from the lower bounds (32). If the user enters a negative shift value and the bounds are underflowed, it should shift the rest from the higher bounds (126).
---------------------------------------------------------------------------------------------
Info: This is a very simple cipher now, called shift cipher or caesar's cipher: https://en.wikipedia.org/wiki/Caesar_cipher (https://en.wikipedia.org/wiki/Caesar_cipher)
The key of the encryption in this case is the number the characters are shifted.
The key of decryption is -key of encryption (so you shift it back).
This cipher is a good one to implement (it is simple) and to show vulnerabilities of ciphers (it is easy to crack). That's the reason I chose it.
But if you stay tuned we will also use Java for something that is used today (like AES)
For more theoretical background:
What is a cipher? (https://en.wikipedia.org/wiki/Cipher (https://en.wikipedia.org/wiki/Cipher))
In cryptography (https://en.wikipedia.org/wiki/Cryptography), a cipher (or cypher) is an algorithm (https://en.wikipedia.org/wiki/Algorithm) for performing encryption (https://en.wikipedia.org/wiki/Encryption) or decryption (https://en.wikipedia.org/wiki/Decryption)—a series of well-defined steps that can be followed as a procedure.
[...]
When using a cipher the original information is known as plaintext (https://en.wikipedia.org/wiki/Plaintext), and the encrypted form as ciphertext (https://en.wikipedia.org/wiki/Ciphertext). The ciphertext message contains all the information of the plaintext message, but is not in a format readable by a human or computer without the proper mechanism to decrypt it. The operation of a cipher usually depends on a piece of auxiliary information, called a key (https://en.wikipedia.org/wiki/Key_%28cryptography%29) (or, in traditional NSA (https://en.wikipedia.org/wiki/NSA) parlance, a cryptovariable). The encrypting procedure is varied depending on the key, which changes the detailed operation of the algorithm. A key must be selected before using a cipher to encrypt a message. Without knowledge of the key, it should be difficult, if not nearly impossible, to decrypt the resulting ciphertext into readable plaintext
The shift cipher is a substitution cipher. (https://en.wikipedia.org/wiki/Substitution_cipher (https://en.wikipedia.org/wiki/Substitution_cipher))
In cryptography (https://en.wikipedia.org/wiki/Cryptography), a substitution cipher is a method of encryption (https://en.wikipedia.org/wiki/Encryption) by which units of plaintext are replaced with ciphertext (https://en.wikipedia.org/wiki/Ciphertext), according to a regular system; the "units" may be single letters (the most common), pairs of letters, triplets of letters, mixtures of the above, and so forth. The receiver deciphers the text by performing an inverse substitution.
---------------------------------------------------------------------------------------------
Preparation assignment 4
In preparation for the next assignment try to answer those questions (if you are sure you are right, it is enough to answer this for yourself, if not ask me):
How do you decrypt an encrypted message with a shift of 5?
How many keys has your shift cipher?
Which vulnerabilities has this cipher?
How would you try to crack a (large) message encrypted by shift cipher?
If you have absolutely no idea, read the wikipedia article about the shift cipher: https://en.wikipedia.org/wiki/Shift_cipher (https://en.wikipedia.org/wiki/Shift_cipher)
It helps if you first go away (mentally) from how to code the cracking. Just think about a way you could crack a message that you get on paper.
4. Assignment - shift cipher crack
Write a program that cracks a message which was encrypted by a shift cipher.
If you have no idea how to start, tell me how you want to crack the cipher and I will help you by separating your task into steps.
-
Very nice :) I'll try to adapt those in other languages that I am learning ATM :)
Keep up the posts. Btw how many assignment will there be?
And since when do you have a baby? I thought it's not popping out due to next year? :P
-
Congrats on your kid. If you ever want someone to give you lesson ideas, im your man. but it looks like you got that covered. will definitely try to incorporate into languages that need improvement (my python is kinda rusty)
-
Hereeee we go. Looking forward to continuing this. Grats on the kid :)
import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
boolean done = false;
Scanner input = new Scanner(System.in);
while(!done)
{
System.out.println("Your input?");
String user_input = input.nextLine();
if(user_input.equalsIgnoreCase("exit") || user_input.equalsIgnoreCase("quit"))
{
System.exit(0);
}
else
{
System.out.println(user_input + "\n");
}
}
}
}
-
Very nice :) I'll try to adapt those in other languages that I am learning ATM :)
Keep up the posts. Btw how many assignment will there be?
And since when do you have a baby? I thought it's not popping out due to next year? :P
I don't know yet how many assignments there will be. It depends on my student (how much he knows, how much he needs in order to learn the stuff)
My baby is three months old, Kulver. You didn't really think he will stay in the belly for over a year, did you? :D
He is also the reason I am not on IRC anymore.
Congrats on your kid. If you ever want someone to give you lesson ideas, im your man. but it looks like you got that covered. will definitely try to incorporate into languages that need improvement (my python is kinda rusty)
Oh, thanks. :D
You can of course do the assignments in other languages, but I probably won't give you feedback for that. I don't know any Python.
Hereeee we go. Looking forward to continuing this. Grats on the kid :)
import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
boolean done = false;
Scanner input = new Scanner(System.in);
while(!done)
{
System.out.println("Your input?");
String user_input = input.nextLine();
if(user_input.equalsIgnoreCase("exit") || user_input.equalsIgnoreCase("quit"))
{
System.exit(0);
}
else
{
System.out.println(user_input + "\n");
}
}
}
}
Well done Lykos.
Using equalsIgnoreCase() is a good choice here.
Now try
1. without using System.exit(0). Rather use the loop condition to ask if the input is "exit", "quit" or something else.
2. Make sure to close the scanner when it is not needed anymore.
3. The boolean "done" is not necessary at all, because you never change it. Remove it.
4. user_input doesn't comply with the Java code conventions. Use camel case: userInput
-
Here's mine.Please give me feedback :P
import java.io.*;
class Assignment1 {
public static void main(String[] args)throws IOException
{
String input;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
do {
System.out.println("Your input?");
input = br.readLine();
if input(input == "quit" || input == "exit")
{
System.exit(0);
}
System.out.println(""+input);
}while(input != "exit" || input != "quit");
}
}
-
Here's mine.Please give me feedback :P
import java.io.*;
class Assignment1 {
public static void main(String[] args)throws IOException
{
String input;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
do {
System.out.println("Your input?");
input = br.readLine();
if input(input == "quit" || input == "exit")
{
System.exit(0);
}
System.out.println(""+input);
}while(input != "exit" || input != "quit");
}
}
Have you tried if it works? If so, it was more random than anything else.
Your logic is correct. But Java is a bitch when it comes to comparing Strings.
The operators == and != compare references, but not the contents of a String (or object).
To find out if a String object has the same content as another you need to use equals().
Example:
String string = "Mr. Perfect";
if(string.equals("Mr. Perfect")) {
System.out.println("equals");
}
*(Hint: the data type of an object starts with an uppercase letter, i.e. String; the data type of a primitive starts with a lowercase letter, i.e. int, long)*
Also:
- Try without the use of System.exit() (not only now, avoid it always, it makes your code unembedable)
- close your stream (the BufferedReader)
_____________________________________________________________
Edit: Second assignment is out in the first post.
But make sure to correct the first assigment before starting the second.
-
Not sure how to exit programs in Java without System.exit(0), unless I just flat out don't need to use it. Took out the boolean, and replaced the System.exit with break to simply get out of the loop. Not sure if that's what you pushing me towards or not. Might be something I don't know about. I'll edit this post with assignment 2 when I finish it.
Assignment 1:
import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
while(true)
{
System.out.println("Your input?");
String userInput = input.nextLine();
if(userInput.equalsIgnoreCase("exit") || userInput.equalsIgnoreCase("quit"))
{
break;
}
else
{
System.out.println(userInput + "\n");
}
}
input.close();
}
}
Assignment 2:
import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
while(true)
{
System.out.println("Your input?");
String userInput = input.nextLine();
char[] charArray;
charArray = userInput.toCharArray();
if(userInput.equalsIgnoreCase("exit") || userInput.equalsIgnoreCase("quit"))
{
break;
}
else
{
for(char c : charArray)
{
System.out.print(++c);
}
System.out.println();
}
}
input.close();
}
}
The .toCharArray is something I had no idea about. Not sure if that is the best way to do this, but it seemed like it was either this or splitting the string at every dang ASCII character and then adding that to the array. So .toCharArray seems like a really cool thing that I can definitely make use of in other programs as well.
-
Have you tried if it works? If so, it was more random than anything else.
It works.I posted it after testing.
It is the way in which we are taught to program in school.
BTW, my first assignment(after modification) :) :)
/**
*Assignment 1
* @author Mr. Perfect
*/
import java.io.*;
class Assignment1 {
public static void main(String[] args)throws IOException
{
String input;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
do {
System.out.println("Your input?");
input = br.readLine();
if ("quit".equalsIgnoreCase(input) || "exit".equalsIgnoreCase(input))
{
br.close();
break;
}
System.out.println(""+input);
}while(!"exit".equalsIgnoreCase(input) || !"quit".equalsIgnoreCase(input));
}
}
One question, in what way it will affect the program if we don't close the stream BufferedReader. :P
-
Not sure how to exit programs in Java without System.exit(0), unless I just flat out don't need to use it.
It is alright the way you did. You exit by reaching the end of your main. That is not a problem, if you structure your code well.
System.exit() is bad. It shuts down the JVM regardless what runs within. If there is still a task, it will be shut down too. That makes it hard to reuse your code, to embed it and to make unit tests.
Took out the boolean, and replaced the System.exit with break to simply get out of the loop. Not sure if that's what you pushing me towards or not. Might be something I don't know about. I'll edit this post with assignment 2 when I finish it.
Your way is right.
I wanted to push you to using the loop conditional statement (where you have a "true" now) to control the loop. The reason is a better readability. Another programer will read the conditional statement first in order to see, what has to be true to keep the loop running. In your case the programmer is forced to look into the body of the loop to see your condition for breaking it.
The rest looks fine.
Assignment 2:
import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
while(true)
{
System.out.println("Your input?");
String userInput = input.nextLine();
char[] charArray;
charArray = userInput.toCharArray();
if(userInput.equalsIgnoreCase("exit") || userInput.equalsIgnoreCase("quit"))
{
break;
}
else
{
for(char c : charArray)
{
System.out.print(++c);
}
System.out.println();
}
}
input.close();
}
}
The .toCharArray is something I had no idea about. Not sure if that is the best way to do this, but it seemed like it was either this or splitting the string at every dang ASCII character and then adding that to the array. So .toCharArray seems like a really cool thing that I can definitely make use of in other programs as well.
toCharArray is good. You could as well use the Scanner to return single chars, but which way doesn't matter here imho. Well done.
Now split your code into methods: I.e.
One method for getting the user input (returns a String)
One method to encode the user input (takes a String, returns a String)
___________________________________________________________
It works.I posted it after testing.
It is the way in which we are taught to program in school.
Do they really teach you to compare the content of strings with == ?
That only works by accident.
BTW, my first assignment(after modification) :) :)
/**
*Assignment 1
* @author Mr. Perfect
*/
import java.io.*;
class Assignment1 {
public static void main(String[] args)throws IOException
{
String input;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
do {
System.out.println("Your input?");
input = br.readLine();
if ("quit".equalsIgnoreCase(input) || "exit".equalsIgnoreCase(input))
{
br.close();
break;
}
System.out.println(""+input);
}while(!"exit".equalsIgnoreCase(input) || !"quit".equalsIgnoreCase(input));
}
}
System.out.println(""+input);
Why do you do the string concatenation here? Just write
System.out.println(input);
}while(!"exit".equalsIgnoreCase(input) || !"quit".equalsIgnoreCase(input))
That condition is always true (think about it, no string can be "exit" and "quit" at the same time).
One question, in what way it will affect the program if we don't close the stream BufferedReader. :P
Unclosed streams lead to bugs that are very hard to fix. I once had to fix a certain bug in a bigger project and it took me several days to find the cause. It was not where I expected it. There was a table that didn't work right and the code for the table just looked fine. Everything worked fine as standalone too, but within the big project it worked only sometimes.
The reason was not the code where the bug occured. The reason where unclosed streams elsewhere which held open some files the table needed to access. The streams never released their resources, they never said "I am done, anyone else can use these files now", so these files couldn't be opened by others as long as the software ran.
It might not be an issue in your small program right now. But it will be some time. You want to write reusable code. Every good programmer does that. Reusability and readability are very important.
Now imagine you take your code (or code of other people) and copy it to a bigger project, but forget to add the stream closing. Or you might open another program (that doesn't close streams) within a program of yours. You will get very weird bugs with this.
Or imagine you don't get used to closing streams right now, then you won't think of it, when it is really necessary. Make it your habit to close streams. It will spare you a lot of time of bugfixing.
-
Alright, so Deque, I get what you're saying about wanting the loop condition to handle when to end the loop, but I'm not quite sure how to do that. I've tried putting the condition of if the input is exit or quit in the condition, but it ends up printing out the encoded string and THEN exiting when I do that. Same with do-while. Saying exit or quit makes the program stop, but it also spits back the encoded message first, which is not what I want. I guess I could possible do a nested while loop and this would take care of that, but also be much less elegant and end up making future programmers have to look through two loops instead of one. So maybe I'm missing something here, but having while(true) and then break seems like the best way so far. Any hints in the right direction would be appreciated.
So here is my modularized code, like you wanted:
/**
* @author: Lykos
* @version: 0.3
*/
import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
String userInput = "";
while(true)
{
System.out.println("Your input?");
userInput = getInput();
if(userInput.equalsIgnoreCase("exit") || userInput.equalsIgnoreCase("quit"))
{
break;
}
System.out.println(encode(userInput));
}
}
private static String getInput()
{
Scanner input = new Scanner(System.in);
String userInput = input.nextLine();
input.close();
return userInput;
}
private static String encode(String input)
{
char[] charArray = input.toCharArray();
for(int index = 0; index < charArray.length; index++)
{
++charArray[index];
}
String s = new String(charArray);
return s;
}
}
Not gonna lie, the encode method pissed me off a little till I switched to a traditional for loop instead of the for-each. Not sure if you want the main method to be cut down more than this or not. I'll try something after I post this to see if I can cut it down a little more, but for now, there we go.
-
Alright, so Deque, I get what you're saying about wanting the loop condition to handle when to end the loop, but I'm not quite sure how to do that. I've tried putting the condition of if the input is exit or quit in the condition, but it ends up printing out the encoded string and THEN exiting when I do that. Same with do-while. Saying exit or quit makes the program stop, but it also spits back the encoded message first, which is not what I want. I guess I could possible do a nested while loop and this would take care of that, but also be much less elegant and end up making future programmers have to look through two loops instead of one. So maybe I'm missing something here, but having while(true) and then break seems like the best way so far. Any hints in the right direction would be appreciated.
Ah, I see your problem and I didn't realize this first.
You could do something like that, but I have to admit that this is not much better than using break (it still is regarding the readability of the loop condition, but now you have to check for that condition twice):
do {
get userinput
if(userinput not "quit" and userinput not "exit") {
encode userinput
print encoded userinput
}
} while (userinput not "quit" and userinput not "exit");
Do it the way you think it is best.
Not gonna lie, the encode method pissed me off a little till I switched to a traditional for loop instead of the for-each.
Yes, a foreach loop isn't suitable in all cases. When you have to change the contents of an array you can't really use a foreach.
Not sure if you want the main method to be cut down more than this or not.
No, that's alright.
I will post the third assignment later.
-
Good work for the community here Deque.
Just curious but what's your current job title? PM me if you don't want to hijack this thread.
-
Good work for the community here Deque.
Just curious but what's your current job title? PM me if you don't want to hijack this thread.
I am not working atm, but doing my masters degree in computer science.
I've got a scholarship and they don't want me to work, they would shorten their money by the amount that I earn.
-
Assignment 3:
/**
* @author: Lykos
* @version: 0.5
* @description: Simple shift cipher. Takes a string from the user, and the user enters the amount to shift it by.
*/
import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
String userInput = "";
while(true)
{
System.out.println("Enter the string you would like to cipher: ");
userInput = getInput();
if(userInput.equalsIgnoreCase("exit") || userInput.equalsIgnoreCase("quit"))
{
break;
}
System.out.println("Enter the amount you would like to shift the string by: ");
int shiftAmount = getShift();
System.out.println(encode(userInput, shiftAmount));
}
input.close();
}
private static int getShift()
{
Scanner input = new Scanner(System.in);
String shiftAmount = input.nextLine();
int shift = Integer.parseInt(shiftAmount);
input.close();
return shift;
}
private static String getInput()
{
Scanner input = new Scanner(System.in);
String userInput = input.nextLine();
input.close();
return userInput;
}
private static String encode(String input, int shiftAmount)
{
char[] charArray = input.toCharArray();
for(int index = 0; index < charArray.length; index++)
{
charArray[index] += shiftAmount;
}
String s = new String(charArray);
return s;
}
}
Not much really had to be changed. Originally I did the code for getShift() in the main method, then remembered it'd be better to make a different method for it. So did that, then just had to make another parameter for encode.
Kinda dreading incorporating Swing into this. Seems like that's gonna be a lot of re-doing code. I've just barely touched the surface of Swing though, so maybe there's some shortcuts/convenient things I don't know.
Anyway, this is fun shit. Thank you very much for doing this, Deque. This should definitely keep me working during break, since I'm done with CoSci classes for a month. I appreciate this a lot.
-
Don't have that much time right now, you get detailed feedback later. Just some little thing you have to consider:
What if the message is "abc" and the shift is 200?
Your program should start shifting from the beginning again, if you shift over the bounds.
The % operator will help you here.
-
I am not working atm, but doing my masters degree in computer science.
I've got a scholarship and they don't want me to work, they would shorten their money by the amount that I earn.
Understandable if you are doing research I guess. If you have time (and can) I'd be interested in hearing about what your are doing. Finishing my studies in software engineering right now and still unsure if I wanna go work right away (get good job with Microsoft.. intern there) or go for graduate studies.
-
This is my third assignment.
Here we goooooooooooooooooo.........................
/**
* Assignment 3
* @author Mr. Perfect
*/
import java.util.Scanner;
public class Asignment3 {
public static void main(String[] args) {
String userInput;
do {
Scanner input=new Scanner(System.in);
System.out.println("Your input?");
userInput= input.nextLine();
char[] charArray;
if (userInput.equalsIgnoreCase("quit") || userInput.equalsIgnoreCase("exit"))
{input.close();
break;
}
System.out.println("How many places you want to shift the characters?");
int places = input.nextInt();
charArray=userInput.toCharArray();
for(char a : charArray )
{
a+=places;
System.out.print(a);
}
System.out.println();
}while(!userInput.equalsIgnoreCase("quit") || !userInput.equalsIgnoreCase("exit"));
}
}
I don't know how to use % operator. :P
I don't know answers to your questions. :P
-
private static int getShift()
{
Scanner input = new Scanner(System.in);
String shiftAmount = input.nextLine();
int shift = Integer.parseInt(shiftAmount);
input.close();
return shift;
}
private static String getInput()
{
Scanner input = new Scanner(System.in);
String userInput = input.nextLine();
input.close();
return userInput;
}
Very good that you made a new method for reading the shift.
These two methods are pretty similar. Think about a way to shorten them by reusing code.
Kinda dreading incorporating Swing into this. Seems like that's gonna be a lot of re-doing code. I've just barely touched the surface of Swing though, so maybe there's some shortcuts/convenient things I don't know.
We make babysteps towards it, so I don't think it will be much of a problem.
Anyway, this is fun shit. Thank you very much for doing this, Deque. This should definitely keep me working during break, since I'm done with CoSci classes for a month. I appreciate this a lot.
Thank you and you are welcome. :)
Edit: In case you already know what the % operator does or you have done some research about it, would you explain it for others?
_____________________________________________________________________
This is my third assignment.
Here we goooooooooooooooooo.........................
You missed assignment 2. I recommend to do one step at a time. Don't let yourself affect by others. Make the assignments at your own learning pace. Make sure to understand, what you are doing.
I don't know how to use % operator. :P
I don't know answers to your questions. :P
Let's first make your code working (without the bounds check) and care afterwards for the % operator. I will explain it then. Or even better, Lykos can explain it in case he got this far by then.
Same for the questions. That's why I wanted you to make one step at a time, so you don't get distracted and focus on the current task.
}while(!userInput.equalsIgnoreCase("quit") || !userInput.equalsIgnoreCase("quit"));
Why do you check for "quit" twice?
The rest of the code looks fine. Well done so far.
Like Lykos I suggest you create some methods to structure your code and improve reusability and readability this way.
Doing this is inevitable when the program gets bigger.
___________________________________________________________________
@Satan911: I answer you later.
-
Here's my condensed code, using getInput() for the shiftAmount and also taking in the string to shift. Just had to parseInt to get getInput()'s value into int.
/**
* @author: Lykos
* @version: 0.6
* @description: Simple shift cipher. Takes a string from the user, and the user enters the amount to shift it by.
*/
import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
String userInput = "";
while(true)
{
System.out.println("Enter the string you would like to cipher: ");
userInput = getInput();
if(userInput.equalsIgnoreCase("exit") || userInput.equalsIgnoreCase("quit"))
{
break;
}
System.out.println("Enter the amount you would like to shift the string by: ");
int shiftAmount = Integer.parseInt(getInput());
System.out.println(encode(userInput, shiftAmount));
}
input.close();
}
private static String getInput()
{
Scanner input = new Scanner(System.in);
String userInput = input.nextLine();
input.close();
return userInput;
}
private static String encode(String input, int shiftAmount)
{
char[] charArray = input.toCharArray();
for(int index = 0; index < charArray.length; index++)
{
charArray[index] += shiftAmount;
}
String s = new String(charArray);
return s;
}
}
Haven't figured out how to incorporate % into this yet. I haven't actually been able to find the bounds. I've done z and then shifted it by some arbitrarily high number (such as 1000000000) and still get stuff back. It was a chinese character, if I remember right. So I guess I need to know where you want the bounds to be, Deque, cause it doesn't seem to have one right now. Maybe just from 32 to 126 on the ASCII chart? That's everything from spacebar to ~, which would be the typical input (at least for an english speaker). If that's the bounds you want, I think I could incorporate % pretty easily.
Anyway, for an explanation of %, or Modulo, for Mr. Perfect:
% is called the modulo operator. It returns the remainder of a division equation. So take this for example:
2 / 2 = 1 (typical division equation).
2 % 2 = 0 (Since 2 goes into 2 a set amount of times, there is no remainder).
Another example:
3 % 2 = 1 (2 goes into 3 once, with one unit left over).
5 % 2 = 1 (2 goes into 5 twice, with one unit left over).
11 % 3 = 2 (3 goes into 11 three times, which equals 9, and 11 - 9 = 2 for the remainder).
For an example of this in a real program, we can use modulo to figure out whether a number is even or not:
//Omitting the code where we get an int from the user and assign it to a variable named userInput
if(userInput % 2 == 0)
{
System.out.println("This number is even!"); // Number is even because when divided by two, there is no remainder.
}
else
{
System.out.println("This number is odd!"); // Number is odd if there is a remainder when dividing by 2.
}
Hopefully this clears it up. Modulo, %, just returns the remainder from a division equation. Let me know if this isn't clear enough, I can try to explain in a different way.
-
Haven't figured out how to incorporate % into this yet. I haven't actually been able to find the bounds. I've done z and then shifted it by some arbitrarily high number (such as 1000000000) and still get stuff back. It was a chinese character, if I remember right. So I guess I need to know where you want the bounds to be, Deque, cause it doesn't seem to have one right now. Maybe just from 32 to 126 on the ASCII chart? That's everything from spacebar to ~, which would be the typical input (at least for an english speaker). If that's the bounds you want, I think I could incorporate % pretty easily.
Uff, you are right. That is my fault, I really thought I had already given bounds in the assignment description. Yes, make it 32 to 126, so you actually see what is going on and don't have any control symbols in it. I will change the assignment description right away.
A char is far more than just the ASCII values. It has 16 bits for unicode. That's why you got some chinese stuff. If you overflow a char it turns around (highest char value + 1 = lowest char value).
Here's my condensed code, using getInput() for the shiftAmount and also taking in the string to shift. Just had to parseInt to get getInput()'s value into int.
Well done.
If the user enters a string instead of a number to shift the characters your program will break. Try to catch that. Do you have experience with exception handling? If not I will explain it.
Also good explanation for %.
-
Haven't figured out how to incorporate % into this yet. I haven't actually been able to find the bounds. I've done z and then shifted it by some arbitrarily high number (such as 1000000000) and still get stuff back. It was a chinese character, if I remember right. So I guess I need to know where you want the bounds to be, Deque, cause it doesn't seem to have one right now. Maybe just from 32 to 126 on the ASCII chart? That's everything from spacebar to ~, which would be the typical input (at least for an english speaker). If that's the bounds you want, I think I could incorporate % pretty easily.
Anyway, for an explanation of %, or Modulo, for Mr. Perfect:
% is called the modulo operator. It returns the remainder of a division equation. So take this for example:
2 / 2 = 1 (typical division equation).
2 % 2 = 0 (Since 2 goes into 2 a set amount of times, there is no remainder).
Another example:
3 % 2 = 1 (2 goes into 3 once, with one unit left over).
5 % 2 = 1 (2 goes into 5 twice, with one unit left over).
11 % 3 = 2 (3 goes into 11 three times, which equals 9, and 11 - 9 = 2 for the remainder).
For an example of this in a real program, we can use modulo to figure out whether a number is even or not:
//Omitting the code where we get an int from the user and assign it to a variable named userInput
if(userInput % 2 == 0)
{
System.out.println("This number is even!"); // Number is even because when divided by two, there is no remainder.
}
else
{
System.out.println("This number is odd!"); // Number is odd if there is a remainder when dividing by 2.
}
Hopefully this clears it up. Modulo, %, just returns the remainder from a division equation. Let me know if this isn't clear enough, I can try to explain in a different way.
Sorry Lykos and Deque.I knew the modulo operator but when you posted it in a hint,I thought you were talking about something else.Today when I was writing this assignment in my notebook then it struck to my mind that % is modulo operator and returns remainder.Sorry for the inconvinience. :P
You guys are really a great help.Thank you. ;) ;)
Here is my third assignment(upto where I understood all the conditions).
/**
* Assignment 3
* @author Mr. Perfect
*/
import java.util.Scanner;
public class Asignment3 {
public static void main(String[] args) {
String userInput;
do {
Scanner input=new Scanner(System.in);
System.out.println("Your input?");
userInput= input.nextLine();
char[] charArray;
if (userInput.equalsIgnoreCase("quit") || userInput.equalsIgnoreCase("exit"))
{input.close();
break;
}
System.out.println("How many places you want to shift the characters?");
int places = input.nextInt();
charArray=userInput.toCharArray();
for(char a : charArray )
{
a+=places;
if(places > 126)
{
a = (char) (places%126);
a+=32;
System.out.print(a);
}
else if(places < 0)
{
a=(char) (126-places);
System.out.print(a);
}
else{
System.out.print(a);
}
}
System.out.println();
}while(!userInput.equalsIgnoreCase("quit" ) || !userInput.equalsIgnoreCase("exit") );
}
}
-
@Mr. Perfect:
}while(!userInput.equalsIgnoreCase("quit" ) || !userInput.equalsIgnoreCase("exit") );
This part still doesn't make sense.
Please try the following, maybe you will understand:
String string = "edit this string";
if(!userInput.equalsIgnoreCase("quit" ) || !userInput.equalsIgnoreCase("exit")) {
System.out.println("condition true");
} else {
System.out.println("condition false");
}
Now try to make the condition false by changing the string.
Your code for assignment 3 has a bug:
Type in '}' and shift 3.
The result should be '!', but it isn't.
Last thing to do: Use methods to structure your code. Create at least a method for the userinput and a method to encrypt the message.
-
@Mr. Perfect:
}while(!userInput.equalsIgnoreCase("quit" ) || !userInput.equalsIgnoreCase("exit") );
This part still doesn't make sense.
Your code for assignment 3 has a bug:
Type in '}' and shift 3.
The result should be '!', but it isn't.
Last thing to do: Use methods to structure your code. Create at least a method for the userinput and a method to encrypt the message.
1. Why that part doesn't make sense? The loop will continue till the userInput is not equal to exit or quit. ???
2. I'll try to fix the bug. :P
3. I'll post after using structures in my code. ;)
-
1. Why that part doesn't make sense? The loop will continue till the userInput is not equal to exit or quit. ???
Your loop only works right, because you have a break in your if-statement here:
if (userInput.equalsIgnoreCase("quit") || userInput.equalsIgnoreCase("exit"))
{input.close();
break;
}
But as I already said in a previous previous post, the loop condition can never be false. Just try it. You will see.
-
I'll be able to work on this again in a couple days. I have final exams right now that I have to study for, so no spare time unfortunately. Thanks for responding about the bounds. And yes, I have experience with exception handling so I'll put that in as well when I get the chance, hopefully over this weekend.
-
At last,here is my third assignment.Thanks Deque you helped me.Here's the code...
/**
* Assignment 3
* @author Mr. Perferct
*Purpose:A program to encrypt messages using Caeser's Cipher.
*/
import java.util.Scanner;
public class Assignment_3 {
private static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
while (true) {
System.out.println("Your input?");
String userinput = UserInput();
if (userinput.equalsIgnoreCase("quit")
|| userinput.equalsIgnoreCase("exit")) {
break;
}
System.out.println("Enter the amount you want to move the cipher?");
int move = Amount();
System.out.print("The encrypted string is: ");
System.out.print(Encrypt(userinput, move));
}
input.close();
}
public static String UserInput() {
String userinput = input.nextLine();
return userinput;
}
private static int Amount() {
String p = input.nextLine();
int places = Integer.parseInt(p);
return places;
}
private static String Encrypt(String input, int places) {
char[] charArray = input.toCharArray();
for (char a : charArray) {
a += places;
if (places < 0) {
a = (char) (126 - places);
System.out.print(a);
} else if (a > 126) {
a = (char) (a % 126);
a += 32;
System.out.print(a);
} else {
System.out.print(a);
}
}
System.out.println();
return "";
}
}
-
Here's my condensed code, using getInput() for the shiftAmount and also taking in the string to shift. Just had to parseInt to get getInput()'s value into int.
/**
* @author: Lykos
* @version: 0.6
* @description: Simple shift cipher. Takes a string from the user, and the user enters the amount to shift it by.
*/
import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
String userInput = "";
while(true)
{
System.out.println("Enter the string you would like to cipher: ");
userInput = getInput();
if(userInput.equalsIgnoreCase("exit") || userInput.equalsIgnoreCase("quit"))
{
break;
}
System.out.println("Enter the amount you would like to shift the string by: ");
int shiftAmount = Integer.parseInt(getInput());
System.out.println(encode(userInput, shiftAmount));
}
input.close();
}
private static String getInput()
{
Scanner input = new Scanner(System.in);
String userInput = input.nextLine();
input.close();
return userInput;
}
private static String encode(String input, int shiftAmount)
{
char[] charArray = input.toCharArray();
for(int index = 0; index < charArray.length; index++)
{
charArray[index] += shiftAmount;
}
String s = new String(charArray);
return s;
}
}
Hey Lycos,your code doesn't work. :o
Have you tried running it before posting? 8)
-
Hey Lycos,your code doesn't work. :o
Have you tried running it before posting? 8)
Yes, many times. And since I don't have my main computer running right now, I just copied and pasted the code I posted into a new project on this computer. My code works perfectly. I have no idea what you're talking about. Care to elaborate on what error you're getting, or how it doesn't work?
-
I have to admit that this was my fault and I recognized when Mr. Perfect asked me for help for this code.
I told you that you should always close your streams, right? There is an exception from that. Once you close System.in (or .err or .out), you can't just reopen it again. System.in is the input stream for your terminal. When you pack it into the Scanner and close the Scanner, the System.in is closed too.
I really didn't know that, because I usually get input via command line arguments or a GUI.
So I am sorry, that I gave a wrong advice in this case.
But what remains is: Always close your streams, unless it is a System. stream.
___________________________________________________________________
private static String Encrypt(String input, int places) {
char[] charArray = input.toCharArray();
for (char a : charArray) {
a += places;
if (places < 0) {
a = (char) (126 - places);
System.out.print(a);
} else if (a > 126) {
a = (char) (a % 126);
a += 32;
System.out.print(a);
} else {
System.out.print(a);
}
}
System.out.println();
return "";
}
Well done so far. I had to smile about your solution. You are kind of cheating here, Mr. Perfect.
The reason we structure the code into methods is reusability. Now imagine we want to create a graphical userinterface for that. We will just re-use the encrypt-method to get a result. That is not possible with your method, since it only prints out the correct result, but returns an empty string (the GUI will get and show that empty string).
Like I told you before: Don't use a foreach loop to modify your array. Rather do it like this:
for(int index = 0; index < charArray.length; index++) {
charArray[index] = //new value here, however this is how you can modify the array
//...
}
You just have to convert your charArray back to string when you are done and return that.
Your code doesn't comply with the Java code conventions. Here is a link to them: http://www.oracle.com/technetwork/java/codeconv-138413.html (http://www.oracle.com/technetwork/java/codeconv-138413.html)
In your case it is the names of your methods. They have to start with a lowercase letter.
Last: You have an off-by-one-error:
If you enter the last character '~' and shift it by 1 it should return the first character ' ' (space). But you get the character right after the space.
An underflow doesn't seem to work at all. (i.e. type in space and a negative shift)
-
Yes, many times. And since I don't have my main computer running right now, I just copied and pasted the code I posted into a new project on this computer. My code works perfectly. I have no idea what you're talking about. Care to elaborate on what error you're getting, or how it doesn't work?
When I ran this program,Here is what I got 8) 8)
Enter the string you would like to cipher:
abc
Enter the amount you would like to shift the string by:
Exception in thread "main" java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Scanner.java:1516)
at Main.getInput(Main.java:34)
at Main.main(Main.java:25)
Java Result: 1
-
When I ran this program,Here is what I got 8) 8)
Enter the string you would like to cipher:
abc
Enter the amount you would like to shift the string by:
Exception in thread "main" java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Scanner.java:1516)
at Main.getInput(Main.java:34)
at Main.main(Main.java:25)
Java Result: 1
That's because of the stream closing. See my last post.
___________________________________________________
@Mr. Perfect: When you are done, try to answer the questions in preparation for assignment 4. I added one question and gave some help there.
You don't have to know how to code it in order to answer them. I will help you with the implementation once you have a plan in your mind.
I will also create an encrypted message that you can use for testing. (Will add it in the first post then)
-
At last, my assignment 3.
/**
* Assignment 3
* @author Mr. Perferct
*/
import java.util.Scanner;
public class Assignment_3 {
private static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
while (true) {
System.out.println("Your input?");
String userinput = userInput();
if (userinput.equalsIgnoreCase("quit")
|| userinput.equalsIgnoreCase("exit")) {
break;
}
System.out.println("Enter the amount you want to move the cipher?");
int move = amount();
System.out.print("The encrypted string is: ");
System.out.println(encrypt(userinput, move));
}
input.close();
}
public static String userInput() {
String userinput = input.nextLine();
return userinput;
}
private static int amount() {
String p = input.nextLine();
int places = Integer.parseInt(p);
return places;
}
private static String encrypt(String input, int places) {
char[] charArray = input.toCharArray();
for(int index = 0; index < charArray.length; index++)
{
charArray[index] += places;
}
String s = new String(charArray);
return s;
}
}
-
At last, my assignment 3.
/**
* Assignment 3
* @author Mr. Perferct
*/
import java.util.Scanner;
public class Assignment_3 {
private static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
while (true) {
System.out.println("Your input?");
String userinput = userInput();
if (userinput.equalsIgnoreCase("quit")
|| userinput.equalsIgnoreCase("exit")) {
break;
}
System.out.println("Enter the amount you want to move the cipher?");
int move = amount();
System.out.print("The encrypted string is: ");
System.out.println(encrypt(userinput, move));
}
input.close();
}
public static String userInput() {
String userinput = input.nextLine();
return userinput;
}
private static int amount() {
String p = input.nextLine();
int places = Integer.parseInt(p);
return places;
}
private static String encrypt(String input, int places) {
char[] charArray = input.toCharArray();
for(int index = 0; index < charArray.length; index++)
{
if(places < 0)
{
charArray[index]=(char) (126 + places);
}else{
charArray[index] += places;
}
}
String s = new String(charArray);
return s;
}
}
Well Mr. Perfect, this code looks perfect.You are a good learner. +1 for that spirit.
-
At last, my assignment 3.
/**
* Assignment 3
* @author Mr. Perferct
*/
import java.util.Scanner;
public class Assignment_3 {
private static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
while (true) {
System.out.println("Your input?");
String userinput = userInput();
if (userinput.equalsIgnoreCase("quit")
|| userinput.equalsIgnoreCase("exit")) {
break;
}
System.out.println("Enter the amount you want to move the cipher?");
int move = amount();
System.out.print("The encrypted string is: ");
System.out.println(encrypt(userinput, move));
}
input.close();
}
public static String userInput() {
String userinput = input.nextLine();
return userinput;
}
private static int amount() {
String p = input.nextLine();
int places = Integer.parseInt(p);
return places;
}
private static String encrypt(String input, int places) {
char[] charArray = input.toCharArray();
for(int index = 0; index < charArray.length; index++)
{
charArray[index] += places;
}
String s = new String(charArray);
return s;
}
}
Try to put the bounds in. Do you need more help with it?
-
Try to put the bounds in. Do you need more help with it?
Here is my bounded program.
/**
* Assignment 3
* @author Mr. Perferct
*/
import java.util.Scanner;
public class Assignment_3 {
private static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
while (true) {
System.out.println("Your input?");
String userinput = userInput();
if (userinput.equalsIgnoreCase("quit")
|| userinput.equalsIgnoreCase("exit")) {
break;
}
System.out.println("Enter the amount you want to move the cipher?");
int move = amount();
System.out.print("The encrypted string is: ");
System.out.println(encrypt(userinput, move));
}
input.close();
}
public static String userInput() {
String userinput = input.nextLine();
return userinput;
}
private static int amount() {
String p = input.nextLine();
int places = Integer.parseInt(p);
return places;
}
private static String encrypt(String input, int places) {
char[] charArray = input.toCharArray();
for(int index = 0; index < charArray.length; index++)
{
charArray[index] += places;
if((int)(charArray[index]) > 126)
{
charArray[index]=(char)((int)(charArray[index]) % 126);
charArray[index]+=32;
}
}
String s = new String(charArray);
return s;
}
}
-
That's very good. You got the upper bounds right. Now do the lower bounds in case the user enters a negative shift (if shifted character < 32 do ...)
If you want to you can also add a decrypt method and give the user the choice to de- or encrypt the message.
That would be additional, you may also proceed trying to find a vulnerability that can help you to crack a message. You already told me about pattern and that is right. But which pattern is it? What is the difference between a random text and a shift-encrypted message (take a long message as given, i.e. 200 words)?
-
Here is my program with lower bounds.
/**
* Assignment 3
* @author Mr. Perferct
*/
import java.util.Scanner;
public class Assignment_3 {
private static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
while (true) {
System.out.println("Your input?");
String userinput = userInput();
if (userinput.equalsIgnoreCase("quit")
|| userinput.equalsIgnoreCase("exit")) {
break;
}
System.out.println("Enter the amount you want to move the cipher?");
int move = amount();
System.out.print("The encrypted string is: ");
System.out.println(encrypt(userinput, move));
}
input.close();
}
public static String userInput() {
String userinput = input.nextLine();
return userinput;
}
private static int amount() {
String p = input.nextLine();
int places = Integer.parseInt(p);
return places;
}
private static String encrypt(String input, int places) {
char[] charArray = input.toCharArray();
for(int index = 0; index < charArray.length; index++)
{
charArray[index] += places;
if((int)(charArray[index]) > 126)
{
charArray[index]=(char)((int)(charArray[index]) % 126);
charArray[index]+=32;
}
else if((int)(charArray[index]) < 32){
charArray[index]=(char)((int)(charArray[index] % 32));
charArray[index]-=126;
}
}
String s = new String(charArray);
return s;
}
}
-
Here is my program with lower bounds.
/**
* Assignment 3
* @author Mr. Perferct
*/
import java.util.Scanner;
public class Assignment_3 {
private static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
while (true) {
System.out.println("Your input?");
String userinput = userInput();
if (userinput.equalsIgnoreCase("quit")
|| userinput.equalsIgnoreCase("exit")) {
break;
}
System.out.println("Enter the amount you want to move the cipher?");
int move = amount();
System.out.print("The encrypted string is: ");
System.out.println(encrypt(userinput, move));
}
input.close();
}
public static String userInput() {
String userinput = input.nextLine();
return userinput;
}
private static int amount() {
String p = input.nextLine();
int places = Integer.parseInt(p);
return places;
}
private static String encrypt(String input, int places) {
char[] charArray = input.toCharArray();
for(int index = 0; index < charArray.length; index++)
{
charArray[index] += places;
if((int)(charArray[index]) > 126)
{
charArray[index]=(char)((int)(charArray[index]) % 126);
charArray[index]+=32;
}
else if((int)(charArray[index]) < 32){
charArray[index]=(char)((int)(charArray[index] % 32));
charArray[index]-=126;
}
}
String s = new String(charArray);
return s;
}
}
Still not working right. Why do you do (charArray[index] % 32)? That doesn't make sense.
You still have an off-by-one-error in the upper bounds part. Imagine I use ~ as input and 0 shift. By doing (charArray[index]) % 126) this will result into 0. You add 32 afterwards, which will result into the space character. That means you have shifted it by 1.
I appreciate that you try very hard. But I don't want to give you the solution. I will however give you a similar one that I wrote. It is not exactly the same, so it will train you in reading code of others. This shift cipher is for letters A-Z (bounds are 65-90). It ignores whitespaces (which is not your task) and every letter a-z is made to an uppercase one before shifted (which is also not your task).
public String encrypt(String plainText, String key) {
plainText = prepareString(plainText);
StringBuffer code = new StringBuffer();
int shift = parseKeyToInt(key);
for (char c : plainText.toCharArray()) {
if (Character.isWhitespace(c)) {
code.append(c);
} else {
int s = ((c % 'A' + shift) % 26);
if (s > 25) {
s = s - 26;
} else if (s < 0) {
s = s + 26;
}
code.append((char) (s + 'A'));
}
}
return code.toString();
}
private String prepareString(String code) {
code = code.toUpperCase();
code = code.replaceAll("[^A-Z\\s]", "");
return code;
}
private int parseKeyToInt(String key) {
int number;
try {
number = Integer.parseInt(key);
} catch (NumberFormatException e) {
number = 0;
}
return number;
}
-
Here is the modified program. :)
/**
* Assignment 3
* @author Mr. Perferct
*/
import java.util.Scanner;
public class Assignment {
private static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
while (true) {
System.out.println("Your input?");
String userinput = userInput();
if (userinput.equalsIgnoreCase("quit")
|| userinput.equalsIgnoreCase("exit")) {
break;
}
try{
System.out.println("Enter the amount you want to move the cipher?");
int move = amount();
System.out.print("The encrypted string is: ");
System.out.println(encrypt(userinput, move));
}catch(NumberFormatException e)
{
System.out.println("You entered a wrong key! \n The key should be in the integer format.");
}
}
input.close();
}
public static String userInput() {
String userinput = input.nextLine();
return userinput;
}
private static int amount() {
String p = input.nextLine();
int places = Integer.parseInt(p);
return places;
}
private static String encrypt(String input, int places) {
char[] charArray = input.toCharArray();
int upperBound = 126;
int lowerBound = 32;
for (int index = 0; index < charArray.length; index++) {
if (!Character.isWhitespace(charArray[index])){
int c = charArray[index];
c += places;
if (c > upperBound) {
c -= lowerBound;
c = c % (upperBound - lowerBound);
c += lowerBound;
} else {
while (c < 32) {
c = c + (upperBound - lowerBound);
}
}
charArray[index] = (char) c;
}
}
String s = new String(charArray);
return s;
}
}
Deque, I've edited the program to handle exceptions and if there is any whitespace,then it will leave it as it is. :)
-
Here is the modified program. :)
/**
* Assignment 3
* @author Mr. Perferct
*/
import java.util.Scanner;
public class Assignment {
private static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
while (true) {
System.out.println("Your input?");
String userinput = userInput();
if (userinput.equalsIgnoreCase("quit")
|| userinput.equalsIgnoreCase("exit")) {
break;
}
try{
System.out.println("Enter the amount you want to move the cipher?");
int move = amount();
System.out.print("The encrypted string is: ");
System.out.println(encrypt(userinput, move));
}catch(NumberFormatException e)
{
System.out.println("You entered a wrong key! \n The key should be in the integer format.");
}
}
input.close();
}
public static String userInput() {
String userinput = input.nextLine();
return userinput;
}
private static int amount() {
String p = input.nextLine();
int places = Integer.parseInt(p);
return places;
}
private static String encrypt(String input, int places) {
char[] charArray = input.toCharArray();
int upperBound = 126;
int lowerBound = 32;
for (int index = 0; index < charArray.length; index++) {
if (!Character.isWhitespace(charArray[index])){
int c = charArray[index];
c += places;
if (c > upperBound) {
c -= lowerBound;
c = c % (upperBound - lowerBound);
c += lowerBound;
} else {
while (c < 32) {
c = c + (upperBound - lowerBound);
}
}
charArray[index] = (char) c;
}
}
String s = new String(charArray);
return s;
}
}
Deque, I've edited the program to handle exceptions and if there is any whitespace,then it will leave it as it is. :)
Great. Now add a decrypt-method too. (shouldn't be more than one line in the body ;) )
Do you want to do assignment 4 or go ahead to GUI programming?
In the latter case I would like to see your GUI code to give you suggestions for your architecture.
-
Made a bit more awesome for n00bs. ;) Couldn't do it in one line. :(
Let's do the 4th assignment.For the GUI,what about the design I made for my Text Encrypter/Decrypter?
Here's the 3rd assignment. ;D
/**
* Assignment 3
* @author Mr. Perferct
*/
import java.util.Scanner;
public class Assignment {
private static Scanner input = new Scanner(System.in);
private static Scanner hello = new Scanner(System.in);
public static void main(String[] args) {
while (true) {
Scanner hello = new Scanner(System.in);
System.out.println("Advanced Text Encrypter/Decrypter");
System.out.println("What do you want to do: \n1.)Encrypt \n2.)Decrypt ");
System.out.println("Enter your choice: ");
int choice = hello.nextInt();
System.out.println("Your input?");
String userinput = userInput();
if (userinput.equalsIgnoreCase("quit")
|| userinput.equalsIgnoreCase("exit")) {
break;
}
try{
System.out.println("Enter the amount you want to move the cipher?");
int move = amount();
if (choice == 1){
System.out.print("The encrypted string is: ");
System.out.println(encrypt(userinput, move));}
else {
System.out.print("The decrypted string is: ");
System.out.println(encrypt(userinput, move));
}
}catch(NumberFormatException e)
{
System.out.println("You entered a wrong key! \n The key should be in the integer format.");
}
}
input.close();
hello.close();
}
public static String userInput() {
String userinput = input.nextLine();
return userinput;
}
private static int amount() {
String p = input.nextLine();
int places = Integer.parseInt(p);
return places;
}
private static String encrypt(String input, int places) {
char[] charArray = input.toCharArray();
int upperBound = 126;
int lowerBound = 32;
for (int index = 0; index < charArray.length; index++) {
if (!Character.isWhitespace(charArray[index])){
int c = charArray[index];
c += places;
if (c > upperBound) {
c -= lowerBound;
c = c % (upperBound - lowerBound);
c += lowerBound;
} else {
while (c < 32) {
c = c + (upperBound - lowerBound);
}
}
charArray[index] = (char) c;
}
}
String s = new String(charArray);
return s;
}
}
-
Made a bit more awesome for n00bs. ;) Couldn't do it in one line. :(
Let's do the 4th assignment.For the GUI,what about the design I made for my Text Encrypter/Decrypter?
Here's the 3rd assignment. ;D
I meant that you should make a method for decryption. But I am ok with this too. But shouldn't you call:
encrypt(userinput, -move)
for decryption (note the minus)?
About the GUI:
That's what I asked you about: Do you want to get feedback for the GUI part now or do you want to do Assignment 4? I'd rather concentrate on one thing at a time.
So either I give you feedback for the GUI first, or I help you with assignment 4 (we can do the GUI part later of course).