This week's book giveaway is in the Artificial Intelligence and Machine Learning forum.
We're giving away four copies of Transfer Learning for Natural Language Processing (MEAP) and have Paul Azunre on-line!
See this thread for details.
Win a copy of Transfer Learning for Natural Language Processing (MEAP) this week in the Artificial Intelligence and Machine Learning forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Tim Cooke
  • Paul Clapham
  • Devaka Cooray
  • Bear Bibeault
Sheriffs:
  • Junilu Lacar
  • Knute Snortum
  • Liutauras Vilda
Saloon Keepers:
  • Ron McLeod
  • Stephan van Hulst
  • Tim Moores
  • Tim Holloway
  • Piet Souris
Bartenders:
  • salvin francis
  • Carey Brown
  • Frits Walraven

Even though I used the replace all func its giving me special characters?

 
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
How would you replace all special characters?


 
Ranch Foreman
Posts: 95
6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
1) Java is pass-by-value
2) your replaceAll method is empty - it does literally nothing
3) when using [code] blocks watch out to post your code between them - a mod will fix your post
 
Marshal
Posts: 68917
275
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Bob Winter wrote:. . . a mod will fix your post

Your great trust in us was not misplaced

Maybe you would like to explain a bit more about pass by value because so many people don't know what it means.
 
Bartender
Posts: 7077
65
Eclipse IDE Firefox Browser MySQL Database VI Editor Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Why aren't you using the String#replaceAll(String,String) method?
 
Bob Winter
Ranch Foreman
Posts: 95
6
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Campbell Ritchie wrote:

Bob Winter wrote:. . . a mod will fix your post

Your great trust in us was not misplaced

Maybe you would like to explain a bit more about pass by value because so many people don't know what it means.


So, let me try (although it maybe not fully correct - but I guess someone will correct my mistakes):

Whenever data is stored in a computers memory it has several "properties", like its type, its length (wich is determined by its type), its actual value and, most important: its location. What happens in Java when you create an object and let a reference "point" to it?
First some memory is allocated in some free memory at some arbitrary random location (also called an address) big enough so all stuff can fit. Then there are some other actions happening (that's the lines running in the constructor). And finally, after the object is fully created, the execution of code returns to the very point where creating the object was started. To access the newly created object one need to know its location in memory - its address. This address is finally stored in the refernce. So, to look from the other way at it: What's actually stored in a reference is jus the location in memory where the objects data are stored.

So, what happen when you now call some method with some paramter? To not get too deep into it I use a rather simple way to describe it: When you call a method with some parameter your code jumps to the point in code where the method is located (in assembler terms: it calls a sub-routine). This can happen either without any parameters, or with an arbitrary number of parameters. When you give a parameter what happens is that the memory address wich is stored in the reference is copied and then passed to the methods parameters as a "local copy" (there's a lot more to learn about this - like "reference shadowing" and such).

Long story short: Your own method replaceAll has two parameters - so it gets two local copies, one for each of the parameter.
What would happen if you now do something with any of those references? As Strings are what's called "immutable" (that is their content cannot change) whenever one does some operation on a String a new String is created. As this is a new object it also has a new place in memory and by this a new address. This new address is then maybe stored in one of the local references.

What's the issue with this and why does this not what you think it may would? And why is this such a common issue for many beginners?

Well, as said: When you call a method the address stored in the reference is copied. So you have the original reference and then the local copy inside the method. Whenever you change such local reference the change is only contained local within the method and not propagated back outwards to the caller. This is the very reason why String methods return new Strings: A String can not change its content. And neither can a change made to a local copy of a given parameter propagate back to the original reference.

Let me give you a quick example:

Well, in fact, this code won't even compile as the paramter "input" is marked "final" and hence can't be overwritten. But, even if the parameter would not be marked as final so the code could compile the result would be the same: The output on line 7 would still be the original String defined two lines above as the change done at line 11 only affects the local copy named "input". It does not propagate back to the original.

So, how to solve this (and your code)? Have a look at these lines:

To make this work I first had to remove the final keyword so the address the reference points to can be changed. Then I give the String "This is the original String!" as an input to my "changeString" method. In it I call the method String.concat(String) wich, as the doc explains, concatenates both Strings. So the result becomes this: "This is the original String! And this gets appended!". But, as this is a new String it as a new address. To propagate this back to the caller I have to return this new address using the return keyword. The most important part which gets lost by many beginners is actually the change at line 6. Look carefully: As the method changeString(String) returns a new String reference (the new address which points to the new String) this has to get stored somewhere. In this case I override the already existing reference, but it could had also stored in a new one. The important thing is that the new reference gets stored somewhere. If line 6 would look like this: changeString(someString); nothing would happen as the new String isn't stored anywhere. In fact, it may could get optimized out so the resulting code would only contain this optimized lines:

Although this all is quite different on primitives I won't bother to explain it as a) it doesn't fit the problem, b) my reply is already way too long and c) wouldn't help in understanding the already explained. Also I won't bother to even try to explain pass-by-reference - as, aside from me not really knowing much about it and hence it may would end up wrong, Java doesn't know it anyway.
 
Marshal
Posts: 25452
65
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I merged your stuff with the following thread. I hope that is okay by you.
 
sunya syed
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I dont know how I can fix my decryption method.
My encryption works fine, can someone help me with my code for decryption.

Down below is my code:
http://tpcg.io/0c00KGQQ
 
Campbell Ritchie
Marshal
Posts: 68917
275
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Please post your code here; many people are reluctant to open distant links like that.
Please explain what the problem is and what algorithm you are using.
 
sunya syed
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

sunya syed wrote:I dont know how I can fix my decryption method.
My encryption works fine, can someone help me with my code for decryption.

Down below is my code:
http://tpcg.io/0c00KGQQ



package oops;

import java.util.Arrays;
import java.util.Map;

import java.util.Scanner;  

public class Main {

private static final String Bforce = null;
private static final String BMessage = null;  

public static void main(String[] args) {

System.out.println("----Vigenere Cipher Encryptor----\n");
Scanner in = new Scanner(System.in);



// Allow the user to choose if they want to encrypt or decrypt or brute force a message
System.out.println(" 1 to encrypt a message  ");
System.out.println(" 2 to decrypt a message  ");
System.out.println(" 3 to brute force  ");
int input = in.nextInt();

// ENCRYPT MESSAGE
if (input == 1) {
System.out.print("Enter the password: ");
String key = in.next();
// key number
System.out.print("Enter the key number (1-26) : ");
int number = in.nextInt();  

if (number >= 1 && number <= 26) {

}

else {


}


// message
System.out.print("Enter the message : ");
         
String EMessage = in.next();
String encryptMessage = encrypt(EMessage, key, number);
System.out.println("The encrypted message is: " + encryptMessage);
//for (int x = 0; x <= number; x++) {
// replaceAll("[-+.^:,]","");  
// encrypt the message
  // String encryptMessage = encrypt(EMessage, key);
// System.out.println("The encrypted message is: " + encryptMessage);



}

// DECRYPT MESSAGE option 2
else if (input == 2) {
System.out.print("Enter the password: ");
String key = in.next();
// key number
System.out.print("Enter the key number (1-26) : ");

// NUM 1- 26  OR ELSE IT GIVES AN ERROR
int number = in.nextInt();  

if (number >= 1 && number <= 26) {

}

else {


}



// prompt for message
System.out.print("Enter the message: ");
String dMessage = in.next();
String decryptMessage = decrypt(dMessage, key, number);
System.out.println("The decrypted message is: " + decryptMessage);
//for (int x = 0; x <= number; x++) {
//replaceAll("[-+.^:,?_-`*/()]","");  
// decrypt the message
//// String DecryptMessage = decrypt(DMessage, key);
// System.out.println("The decrypted message is: " + decryptMessage);

// brute force option 3

}


else if  (input == 3) {
System.out.print("Enter the password: ");
String password = in.next();
// key number
System.out.print("Enter the key number (1-26) : ");

// 1-26 OR ELSE ERROR
int number = in.nextInt();  

if (number >= 1 && number <= 26) {

}

else {


}

// message  for user
System.out.print("Enter the message: ");
String BMessage = in.next();

for (int x = 0; x <= number; x++) {
replaceAll("[-+.^:,]","");  
// decrypt w brute force
String BruteMessage = Bforce(BMessage, password);
System.out.println("The decrypted message is: " + BruteMessage);
}
}
else {
System.out.println("Wrong Input!");
}
in.close();
}








private static void replaceAll(String string, String string2) {


}





// Encryption 1
// Encryption Logic:

public static String encrypt(String Message, String Key, int number) {

String eMessage = "";
Message = Message.toUpperCase();
Key = Key.toUpperCase();

for (int i = 0, j = 0; i < Message.length(); i++) {
// Get the character from the message
char letter = Message.charAt(i);
// Get the ASCII value of the character
int ascii = (int) letter;
// Get the value of the character in the password
int passVal = (int) (Key.charAt(j)) - 65;
// Calculate the amount of the shift
int shiftPos = ascii + passVal - number;

// Check if the position is > 90 (that is, past the letter 'Z')
if (shiftPos > 90) {
// Go back  to the letter 'A'
eMessage += (char) (shiftPos % 90 + 64);
}
else {
// Take the character at the shift position
eMessage += (char) (ascii + passVal - number);
}
// System.out.println(EMessage);
j = ++j % Key.length();
}
return eMessage;
}

// Decryption 2
// Decryption Logic:
public static String decrypt(String Message, String Key, int number) {
String dMessage = "";
Message = Message.toLowerCase();
Key = Key.toLowerCase();    

for (int i = 0, j = 0; i < Message.length(); i++) {
char letter = Message.charAt(i);
int num = (int) letter;
int pass = (int) (Key.charAt(j)) - 'a';

int shiftPos = num - pass + number;
if (shiftPos > 90) {
// Go back  to the letter 'A'
dMessage += (char) (shiftPos % 90 - 64);
}
else {


dMessage += (char) (num - pass + number);
}
dMessage += (char)((num - pass - number) % 26 + 65);
j = ++j % Key.length();
dMessage =  dMessage.replaceAll("[^a-zA-Z0-9]", "");
}  


 


return dMessage;


}


// BRUTE FORCE  3    


public static <Bmessage> String Bforce(String Message, String key) {
String BMessage = "";
Message = Message.toLowerCase();
for (int i = 0, j = 0; i < Message.length(); i++) {
char letter = Message.charAt(i);
BMessage += (char)((letter - key.charAt(j) + 26) % 26 + 65);
j = ++j % key.length();
}


return BMessage.replaceAll("[", "");



}
}
 
sunya syed
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Campbell Ritchie wrote:Please post your code here; many people are reluctant to open distant links like that.
Please explain what the problem is and what algorithm you are using.



I have posted the code.
My decryption is not working but my encryption is right.
Below is what It should be doing.
vc.PNG
TThe algorithm
TThe algorithm
 
Bob Winter
Ranch Foreman
Posts: 95
6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Norm Radder wrote:Also posted here: https://www.dreamincode.net/forums/topic/419077-how-do-you-replace-all-special-characters/

https://coderanch.com/wiki/660346/Wiki/Forthright-Cross-Posting-Sites


Also another topic on the same: https://coderanch.com/t/729715/java/replace-func-giving-special-characters
should be merged by mod - also the code tag in this post may be fixed by mod
 
Saloon Keeper
Posts: 11899
253
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That code is a bit messy. There's a lot of duplication, and it's full of useless comments. Your code should be clear enough that you don't need comments to explain what it's doing. Comments are to explain WHY you're doing something, if you have a complex use case.

First, let's make it easier to read by making separate methods to prompt the user for input, and by introducing some constants for the choices the user can make:
<br /> Now, let's take a look at the encrypt method: <br />
The are a couple of issues here:

  • Don't make methods public if they don't have to be.
  • Don't start variable names with an upper case letter.
  • Use more descriptive variable names than 'number'.
  • More useless comments.
  • Use a StringBuilder when building a string using a loop.
  • There's no need to cast a character to int. Casting to int is done automatically when you use the + operator.
  • Don't use magic values such as 65 and 90. Use character literals like 'A' and 'Z' instead.
  • Don't needlessly repeat calculations. You already calculated shiftPos, so why not use it instead of calculating ascii + passVal - number a second time? But:
  • There is no need for the else-clause at all. The modulus operator returns the original value if it is already within range.
  • You don't need the j variable. You can calculate it from i using the modulus operator.

  • Let's clean up your encrypt and decrypt methods:

    Immediately, a few issues stand out like a sore thumb:

  • Why are you using lower case letters in the decrypt method, when you were using upper case letters in the encrypt method?
  • Why are you subtracting 64 from the shiftPos?
  • Why are you appending the decrypted letter twice, in different ways?
  • Why are you removing all non-alphabetic characters from the decrypted string? You are treating symptoms, not fixing the real problem.

  • With these hints in mind, write a new decrypt method and show it to us.
     
    Won't you please? Please won't you be my neighbor? - Fred Rogers. Tiny ad:
    Two software engineers solve most of the world's problems in one K&R sized book
    https://coderanch.com/wiki/718759/books/Building-World-Backyard-Paul-Wheaton
      Bookmark Topic Watch Topic
    • New Topic