Author Topic: Java assignments  (Read 20824 times)

0 Members and 3 Guests are viewing this topic.

Offline Deque

  • P.I.N.N.
  • Global Moderator
  • Overlord
  • *
  • Posts: 1203
  • Cookies: 518
  • Programmer, Malware Analyst
    • View Profile
Java assignments
« on: 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:

Quote
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/

Example output:
Quote
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
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)

Quote
In cryptography, a cipher (or cypher) is an algorithm for performing encryption or 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, and the encrypted form as 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 (or, in traditional 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)

Quote
In cryptography, a substitution cipher is a method of encryption by which units of plaintext are replaced with 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

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.
« Last Edit: December 13, 2012, 01:25:00 pm by Deque »

Offline Kulverstukas

  • Administrator
  • Zeus
  • *
  • Posts: 6627
  • Cookies: 542
  • Fascist dictator
    • View Profile
    • My blog
Re: Java assignments
« Reply #1 on: December 06, 2012, 07:06:25 pm »
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

Offline Live Wire

  • Knight
  • **
  • Posts: 189
  • Cookies: 4
  • Up on your Net
    • View Profile
Re: Java assignments
« Reply #2 on: December 06, 2012, 10:03:56 pm »
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)
"There is no right or wrong, there is only fun and boring."

Offline Lykos

  • Serf
  • *
  • Posts: 26
  • Cookies: 0
    • View Profile
Re: Java assignments
« Reply #3 on: December 06, 2012, 10:27:20 pm »

Hereeee we go.  Looking forward to continuing this.  Grats on the kid :)

Code: [Select]

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");
            }
        }
    }
}

Offline Deque

  • P.I.N.N.
  • Global Moderator
  • Overlord
  • *
  • Posts: 1203
  • Cookies: 518
  • Programmer, Malware Analyst
    • View Profile
Re: Java assignments
« Reply #4 on: December 07, 2012, 09:21:55 am »
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 :)

Code: [Select]

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
« Last Edit: December 07, 2012, 10:13:34 am by Deque »

Offline parad0x

  • VIP
  • Royal Highness
  • *
  • Posts: 638
  • Cookies: 118
    • View Profile
Re: Java assignments
« Reply #5 on: December 07, 2012, 04:15:54 pm »
Here's  mine.Please give me feedback :P
Code: (Java) [Select]
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");
}
}

Offline Deque

  • P.I.N.N.
  • Global Moderator
  • Overlord
  • *
  • Posts: 1203
  • Cookies: 518
  • Programmer, Malware Analyst
    • View Profile
Re: Java assignments
« Reply #6 on: December 07, 2012, 04:59:06 pm »
Here's  mine.Please give me feedback :P
Code: (Java) [Select]
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:
Code: [Select]
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.
« Last Edit: December 07, 2012, 07:03:30 pm by Deque »

Offline Lykos

  • Serf
  • *
  • Posts: 26
  • Cookies: 0
    • View Profile
Re: Java assignments
« Reply #7 on: December 07, 2012, 10:34:32 pm »
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:
Code: [Select]

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:
Code: [Select]

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.
« Last Edit: December 07, 2012, 10:51:07 pm by Lykos »

Offline parad0x

  • VIP
  • Royal Highness
  • *
  • Posts: 638
  • Cookies: 118
    • View Profile
Re: Java assignments
« Reply #8 on: December 08, 2012, 05:44:16 am »
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) :) :)
Code: (Java) [Select]
/**
 *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
« Last Edit: December 08, 2012, 08:48:07 am by Mr. Perfect »

Offline Deque

  • P.I.N.N.
  • Global Moderator
  • Overlord
  • *
  • Posts: 1203
  • Cookies: 518
  • Programmer, Malware Analyst
    • View Profile
Re: Java assignments
« Reply #9 on: December 08, 2012, 09:00:00 pm »
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.

Quote
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.

Quote
Assignment 2:
Code: [Select]

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.

Quote
BTW, my first assignment(after modification) :) :)
Code: (Java) [Select]
/**
 *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));
}
}

Code: [Select]
System.out.println(""+input);
Why do you do the string concatenation here? Just write

Code: [Select]
System.out.println(input);
Code: [Select]
}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).

Quote
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.

Offline Lykos

  • Serf
  • *
  • Posts: 26
  • Cookies: 0
    • View Profile
Re: Java assignments
« Reply #10 on: December 09, 2012, 06:22:47 am »
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:


Code: [Select]

/**
 * @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. 


Offline Deque

  • P.I.N.N.
  • Global Moderator
  • Overlord
  • *
  • Posts: 1203
  • Cookies: 518
  • Programmer, Malware Analyst
    • View Profile
Re: Java assignments
« Reply #11 on: December 09, 2012, 07:17:02 am »
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):

Code: [Select]
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.

Quote
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.

Quote
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.
« Last Edit: December 09, 2012, 07:20:39 am by Deque »

Offline Satan911

  • VIP
  • Knight
  • *
  • Posts: 289
  • Cookies: 25
  • Retired god/admin
    • View Profile
Re: Java assignments
« Reply #12 on: December 09, 2012, 07:45:10 am »
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.
Satan911
Evilzone Network Administrator

Offline Deque

  • P.I.N.N.
  • Global Moderator
  • Overlord
  • *
  • Posts: 1203
  • Cookies: 518
  • Programmer, Malware Analyst
    • View Profile
Re: Java assignments
« Reply #13 on: December 09, 2012, 07:51:23 am »
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.
« Last Edit: December 09, 2012, 08:00:22 am by Deque »

Offline Lykos

  • Serf
  • *
  • Posts: 26
  • Cookies: 0
    • View Profile
Re: Java assignments
« Reply #14 on: December 09, 2012, 08:21:40 am »
Assignment 3:


Code: [Select]

/**
 * @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.
« Last Edit: December 09, 2012, 08:30:16 am by Lykos »