Author Topic: Java assignments  (Read 20807 times)

0 Members and 2 Guests are viewing this topic.

Offline Deque

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

Offline Satan911

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

Offline parad0x

  • VIP
  • Royal Highness
  • *
  • Posts: 638
  • Cookies: 118
    • View Profile
Re: Java assignments
« Reply #17 on: December 09, 2012, 12:17:02 pm »
This is my third assignment.
Here we goooooooooooooooooo.........................
Code: (Java) [Select]
/**
 * 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
« Last Edit: December 09, 2012, 02:33:07 pm 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 #18 on: December 09, 2012, 01:58:39 pm »
Code: [Select]
    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.

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

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

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

Code: [Select]
}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.
« Last Edit: December 09, 2012, 02:12:59 pm by Deque »

Offline Lykos

  • Serf
  • *
  • Posts: 26
  • Cookies: 0
    • View Profile
Re: Java assignments
« Reply #19 on: December 09, 2012, 07:50:42 pm »
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.


Code: [Select]

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


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

Offline Deque

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

Quote
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 %.
« Last Edit: December 10, 2012, 10:50:49 am by Deque »

Offline parad0x

  • VIP
  • Royal Highness
  • *
  • Posts: 638
  • Cookies: 118
    • View Profile
Re: Java assignments
« Reply #21 on: December 10, 2012, 12:45:57 pm »
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:


Code: [Select]
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:
Code: [Select]
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:
Code: [Select]
//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).
Code: (Java) [Select]
/**
 * 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") );
}
}
« Last Edit: December 10, 2012, 03:54:30 pm 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 #22 on: December 10, 2012, 04:19:25 pm »
@Mr. Perfect:

Code: [Select]
}while(!userInput.equalsIgnoreCase("quit" ) || !userInput.equalsIgnoreCase("exit") );
This part still doesn't make sense.
Please try the following, maybe you will understand:

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

Offline parad0x

  • VIP
  • Royal Highness
  • *
  • Posts: 638
  • Cookies: 118
    • View Profile
Re: Java assignments
« Reply #23 on: December 10, 2012, 04:39:58 pm »
@Mr. Perfect:

Code: [Select]
}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. ;)
« Last Edit: December 10, 2012, 04:41:23 pm 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 #24 on: December 10, 2012, 04:57:42 pm »
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:

Code: (Java) [Select]
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.
« Last Edit: December 10, 2012, 04:58:48 pm by Deque »

Offline Lykos

  • Serf
  • *
  • Posts: 26
  • Cookies: 0
    • View Profile
Re: Java assignments
« Reply #25 on: December 12, 2012, 04:09:57 am »
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.

Offline parad0x

  • VIP
  • Royal Highness
  • *
  • Posts: 638
  • Cookies: 118
    • View Profile
Re: Java assignments
« Reply #26 on: December 12, 2012, 12:39:35 pm »
At last,here is my third assignment.Thanks Deque you helped me.Here's the code...
Code: (Java) [Select]
/**
 * 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 "";
    }
}


Offline Dark Nebulae

  • Peasant
  • *
  • Posts: 117
  • Cookies: -79
  • Unleash the Hacker within you
    • View Profile
Re: Java assignments
« Reply #27 on: December 12, 2012, 01:09:30 pm »
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.


Code: [Select]

/**
 * @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)
Trust is like a piece of paper.Once it is crumbled,it can never be perfect.

Offline Lykos

  • Serf
  • *
  • Posts: 26
  • Cookies: 0
    • View Profile
Re: Java assignments
« Reply #28 on: December 12, 2012, 05:28:22 pm »
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? 
« Last Edit: December 12, 2012, 05:29:31 pm by Lykos »

Offline Deque

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

___________________________________________________________________

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

Code: [Select]
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
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)
« Last Edit: December 13, 2012, 01:31:27 pm by Deque »