Learning simple java string decoding/decryption - java

I want to write a program that decrypts an input string. It selects 0,2,4,6,8 etc. characters from each section of text input and displays it in reverse in the decryption output.
Input: bxoqb swi eymrawn yim
Output: my name is bob
Keep in mind that the program ignores the space symbol, and repeats the loop at the beginning of each word!
I couldn't find anything on the net that isn't based on a more complicated encryption/decryption systems. I'm starting with the simple stuff, first.
edit: Yes, my question is how do I learn how to do this? Or if someone could teach me a technique to decode strings like this?

pseudo code:
Split your string based of space and store it in list.
iterate your list, get each string(bxoqb) and now extract characters(bob) as you want and save it
Iterate same list in reverse order.
Hope it helps you to start.

The following code is the most straightforward way...
//code starts
public static void main(String[] args) {
String str = "bxoqb swi eymrawn yim";
String ans = decryption(str);
System.out.println(ans);
}
public static String decryption(String str) {
String ans = "";
String[] words = str.split(" ");
for (String s : words) {
for (int i = 0; i < s.length(); i += 2) {
ans = s.charAt(i) + ans;
}
ans = " " + ans;
}
return ans.trim();
}
//code ends
Hope it helps.

Related

How can I remove a £ symbol from an array object and save it?

I'm coding a basic chatbot for a University project. I'm up to a point where the user must set a budget by entering an amount. At the moment, the program is able to search for a number in the user's message and save it correctly. However, when a £ sign is prefixed to it, it can't save as an integer due to having the pound sign in the message.
This is my code:
//Scan the user message for a budget amount and save it.
for (int budgetcount = 0; budgetcount < words.length; budgetcount++)
{
if (words[budgetcount].matches(".*\\d+.*"))
{
if (words[budgetcount].matches("\\u00A3."))
{
words[budgetcount].replace("\u00A3", "");
System.out.println("Tried to replace a pound sign");
ResponsesDAO.budget = Integer.parseInt(words[budgetcount]);
}
else
{
System.out.println("Can't find a pound sign here.");
}
}
I have previously tried .contains(), and other ways of indicating that it is a pound sign that I want to remove but I still get the "Can't find a pound sign here." print out.
If anybody can offer advice or correct my code I would appreciate it greatly.
Thanks in advance!
Strings in JAVA are immutable. You are replacing but never assigning back the result to words[budgetcount].
Change the following line in your code,
words[budgetcount] = words[budgetcount].replace("\u00A3", "");
Here is another way to do it by using Character.isDigit(...) to identify a digit and knitting a digit-only String which can later be parsed as an Integer,
Code Snippet:
private String removePoundSign(final String input) {
StringBuilder builder = new StringBuilder();
for (int i = 0; i < input.length(); i++) {
char ch = input.charAt(i);
if (Character.isDigit(ch)) {
builder.append(ch);
}
}
return builder.toString();
}
Input:
System.out.println(removePoundSign("£12345"));
Output:
12345
You can also use String.replaceAll method.
Code snippet:
public class TestClass {
public static void main(String[] args){
//Code to remove non-digit number
String budgetCount = "£34556734";
String number=budgetCount.replaceAll("[\\D]", "");
System.out.println(number);
//Code to remove any specific characters
String special = "$4351&2.";
String result = special.replaceAll("[$+.^&]",""); // regex pattern
System.out.println(result);
}
}
Output:
34556734
43512

Splitting every String the user enters with a comma error

I am supposed to split every string the user enters with a comma.
For example, if the user enters in "Rabbit", I am supposed to print it out as
"R, a, b, b, i, t"
To do that, I searched up the split method String.split();
The code I wrote is as follows
import java.util.*;
class Split{
public static void main(String [] args){
Scanner input = new Scanner(System.in);
System.out.println("Enter a String");
String str= input.nextLine();
printLetters(str);
}
public static String[] printLetters (String a){
return a.split(",");
}
}
Actually I am supposed to write the code using a method that accepts Strings, but when I wrote the String.split(), it said I have to use String [], so I just changed it to String[].
But that code didn't print anything.
I want to know why that is so, and also want to know how to accomplish this task using public static String.
I know there are lots of posts related to it, but I couldn't find anything that matches the requirement, which is using public static String.
I didn't learn the split method either, so I'm not supposed to use it to be honest.
This is my first year taking computer science, and the only things I know are
for loops, if else, nested loops, etc.
It would be preferable not to use the split method, but it's ok to use it because I'm curious about it too.
Thank you in advance :)
From what I can see, you are trying to take an input string and return a new string with inserted commas after every character.
String.split() does something quite different. For example, if I had "R,a,b,b,i,t", I could use String.split() with the delimiter , to get ["R", "a", "b", "b", "i", "t"] back.
A simple solution to your problem would be to iterate through the input string character by character and after each character except for the last one, add a comma to the return string.
Since your assignment is to actually do this yourself, I won't be posting a code solution. However, I hope my explanation cleared up your misconceptions and is enough for you to write a solution.
Use String.join().
import java.util.*;
class Split{
public static void main(String [] args){
Scanner input = new Scanner(System.in);
System.out.println("Enter a String");
String str= input.nextLine();
String word = printLetters(str);
System.out.println(word);
}
public static String printLetters (String a){
return String.join(", ", a.split(""));
}
}
See String.join() and String.split() for more info.
public static void printLetters (String a){
String output = "";
for (int i=0; i<a.length(); i++)
{
output += a.charAt(i);
if (i != a.length()-1)
output += ",";
}
System.out.println(output);
}
See #Andrew Fan's answer. It describes what the split method does. What you need to do is like the reverse of that. You may use a for loop or a while loop.
*Since you are new to programming,
output += ","
is the same as
output = output + ","

Java Word Count

I am just starting out in Java so I appreciate your patience. Anyways, I am writing a word count program as you can tell by the title, I am stuck at the numWords function below the for loop, I am not sure what I should set it equal to. If someone could set me in the right direction that would be awesome. Thank you. Here is all of my code thus far, let me know if I not specific enough in what I am asking, this is my first post. Thanks again.
import java.util.Scanner;
public class WCount {
public static void main (String[] args) {
Scanner stdin = new Scanner(System.in);
String [] wordArray = new String [10000];
int [] wordCount = new int [10000];
int numWords = 0;
while(stdin.hasNextLine()){
String s = stdin.nextLine();
String [] words = s.replaceAll("[^a-zA-Z ]", "").toLowerCase().split("\\s\
+");
for(int i = 0; i < words.length; i++){
numWords = 0;
}
}
}
}
If your code is intended to just count words, then you don't need to iterate through the words array at all. In other words, replace your for loop with just:
numWords += words.length;
Most likely a simpler approach would be to look for sequences of alpha characters:
Matcher wordMatch = Pattern.compile("\\w+").matcher();
while (wordMatch.find())
numWords++;
If you need to do something with the words (such as store them in a map to a count) then this approach will make that simpler:
Map<String,Integer> wordCount = new HashMap<>();
Matcher wordMatch = Pattern.compile("\\w+").matcher();
while (wordMatch.find()) {
String word = wordMatch.group();
int count = wordCount.getOrDefault(word, 0);
wordCount.put(word, count + 1);
}
Don't worry. We were all beginners once.
First of all, you don't need to do the loop because "length" attribute already has it. But, if you want to practice with loops is so easy as increasing the counter each time the iterator advances and that's it.
numWords++;
Hint: Read the input
String sentence = stdin.nextLine();
Split the string
String [] words = sentence.split(" ");
Number of words in a sentence
System.out.println("number of words in a sentence are " + words.length);
You mentioned in comments that you would also like to print the line in alphabetical order. For that Java got you covered:
Arrays.sort(words);
The best way to count the amount of words in a String String phrase is simply to get a String array from it using the String method split String[] words = phrase.split(" ") and giving it as argument the space itself, this will return a String array with each different words, then you can simple check its lengthwords.length and this will give you the exact number.

Remove only one frequency of duplicate word from String array

I have a string array
String a = "This is a life and our life will be full of fun just like the Benn Steller's Secret life of Walter Mitty.";
String a1[]=a.split(" ");
for(String temp: a1)
{
System.out.println(temp);
}
Here "life" is repeated three times. Now I have to remove only one frequency of duplicate word form array.
please guide me....
Thanks.
You can use something like this, but this will remove only first occurence of specified word:
Full code which removes one duplicate. You need to know that it doesn't ignore special characters, and space is delimiter in this case.
public static void main(String []args){
String a = "This is a life and our life will be full of fun just like the Benn Steller's Secret life of Walter Mitty Mitty";
System.out.println(removeOneDuplicate(a));
}
public static String removeOneWord(String str, String word){
int value = str.indexOf(word);
String result = str.substring(0, value);
result += str.substring( value+word.length(), str.length());
return result;
}
public static String removeOneDuplicate(String a){
String [] tmp = a.split(" ");
Map<String, Integer> map = new HashMap<String, Integer>();
for(String s: tmp){
if( map.containsKey(s)){
int value = map.get(s);
if(value == 1)
a = removeOneWord(a, s);
map.put(s, value + 1);
}
else
map.put(s, 1);
}
return a;
}
Sample results:
INPUT: This is a life and our life will be full of fun just like the Benn Steller's Secret life of Walter Mitty Mitty
OUTPUT: This is a and our life will be full fun just like the Benn Steller's Secret life of Walter Mitty
In result You can see that life, of and Mitty is removed.
EDIT
If you want to remove all duplicates and leave first occurence of word change following lines:
int value = str.indexOf(word); -> int value = str.lastIndexOf(word);
int value = map.get(s);
if(value == 1)
a = removeOneWord(a, s);
map.put(s, value + 1);
to:
a = removeOneWord(a, s);
First of all, the example you provided is not a String array. It is a String.
I am giving the solution based on String. If you need it for String array, you will be able to do this on your own, if you understand this.
First, lets take a string tokenizer. A tokenizer breaks apart a string by a given character set. In its simplest form, it breaks apart a string by space.
For example, a string str = "This is a test". A simple tokenizer will break this string into words like "This" "is" "a" "test".
Below is the code to declare and use tokenizer:
StringTokenizer st = new StringTokenizer(a); // a is given your string
Now, we declare an array of string below. (An array of string is an array, the element of each array is a single string.)
String[] str_arr = new String[100];
We will now use the tokenizer to get each word of your string and keep each words in the array of strings like below:
int index=0; // to keep track of index of the array (of strings)
while (st.hasMoreElements()) {
str_arr[index] = (String) st.nextElement();
index++;
}
So, now we have an array of strings named 'str_arr'. Now we will check for each element of the array whether duplicate values are occuring or not. If we find a duplicate, we will replace it with a null value. But, we will do it only once. The remaining duplicates will be kept as it is, this is what you asked for, right?
To keep track of a string already searched and made null, we will use a HashMap like this.
HashMap<String, Integer> hash_map = new HashMap<String, Integer>();
Now, we will run 2 nested loops and after that, we will have a modified array where only multiple occurrence of a string is reduced by 1.
for(int i=0; i<index; i++){
String current_string = str_arr[i];
for(int j=i+1; j<index; j++){
if( (current_string.equals(str_arr[j])) && (hash_map.containsKey(current_string)==false) && str_arr[j]!=""){
hash_map.put(str_arr[j], 1);
str_arr[j]="";
break;
}
}
}
Now, you can print all the words simply as below:
for(int i=0; i<index; i++)
System.out.print(str_arr[i]+" ");
INPUT: This is a life and our life will be full of fun just like the Benn Steller's Secret life of Walter Mitty.
OUTPUT: This is a life and our will be full of fun just like the Benn Steller's Secret life Walter Mitty.
Sorry for long explanation, but still if you can't get any point, please comment. I will try to reply.
Thanks!
Happy Coding :)
As we know, set does not contain duplicate at all.
My Code:
String a = "This is a life and our life will be full of fun just like the Benn Steller's Secret life of Walter Mitty.";
String[] aSpilt = a.split(" ");
List<String> list = Arrays.asList(aSpilt);
System.out.print("The input is : ");
list.forEach((s) -> System.out.print(s + " "));
System.out.println();
Set<String> noDuplicateSet = new LinkedHashSet<>();
Set<String> duplicateSet = new LinkedHashSet<>();
list.forEach((i) -> {
if (!noDuplicateSet.add(i) && i.equals("life")) {
duplicateSet.add(i + " ");
}
});
System.out.print("The output is : ");
noDuplicateSet.forEach((s) -> System.out.print(s + " "));
System.out.println("");
duplicateSet.forEach((s) -> System.out.print(s + " "));
My output:
The input is : This is a life and our life will be full of fun just like the Benn Steller's Secret life of Walter Mitty.
The output is : This is a life and our will be full of fun just like the Benn Steller's Secret Walter Mitty
Note:
I kept the first life and remove the rest, and of was encountered more than once which I did not touched because the question wants just to keep first life and remove the rest.
I used lambda expression to traverse collections
Sources:
http://www.programcreek.com/2013/03/hashset-vs-treeset-vs-linkedhashset/
http://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html
public static void main(String args[])
{
String s;
Scanner in=new Scanner(System.in);
s=in.nextLine();
String ch[]=s.split(" ");
String m=in.nextLine();
for(int i=;i<ch.length;i++)
{
if(ch[i].matches(m))
ch[i]="";
S.o.p(ch[i]);
}
}

Loops and Stacks, palindrome homework assignment

I'm working on an assignment for my programming class but I've run into some difficulty and I'm not sure where else to look. Basically the question asks that we write a program that checks for palindromes.
The user enters text (No non-alphanumberic chars allowed.)
The String is pushed one character at a time into a stack
The characters are pulled one at a time out of the stack thus reversing the String
If the original is the same as the reverse, we have a palindrome
I'm having some trouble with my loops though and don't know where to go from here, does anyone have any advice or pointers? What am I doing wrong?
Here's what I have so far.
import java.util.Stack;
import java.util.regex.*;
import javax.swing.*;
public class Question1 {
static Stack PDrome = new Stack();
public static String Reverse (String input) {
String reverse;
if (input.length() <= 1) {
return input;
}
//pushing onto the stack
for (int i=0; i<input.length();i++) {
PDrome.push(input.charAt(i));
}
//popping from the stack into the string
for (int i=0; i<input.length(); i++) {
PDrome.pop()=reverse.charAt(i);
}
return reverse;
}
//Illegal char check method
public static boolean checker (String input) {
Pattern p = Pattern.compile("[^a-z0-9]", Pattern.CASE_INSENSITIVE);
Matcher m = p.matcher(input);
boolean b = m.find();
if (b) {
System.out.println("There is a special character in your string");
System.exit(0);
}
return b;
}
//Main
public static void main (String [] args) {
//input
String input = JOptionPane.showInputDialog("Enter text to check if it's a palndrome");
//error case
if (input==null); {
System.out.println("Nothing Entered");
System.exit(0);
}
//checking for illegal chars
checker(input);
}
}
This part:
String reverse;
...
//popping from the stack into the string
for (int i=0; i<input.length(); i++)
{
PDrome.pop()=reverse.charAt(i);
}
should be like this:
String reverse = "";
...
//popping from the stack into the string
for (int i=0; i<input.length(); i++)
{
// appends the popped character to reverse
reverse += PDrome.pop();
}
note that when appending a large number of string, this isn't the best way to do it since Java's string is immutable and repeatedly appending a string would require creating a new string each time. This problem is small enough that it wouldn't really matter though, but when the problem gets large you'll want to use StringBuffer/StringBuilder.
PDrome.pop()=reverse.charAt(i); is wrong.
reverse is null -> NullPointerException
Are you assigning a value to a function? (pop())
You have to build reverse from pop'ping from the stack.
So you should start with an empty string: reverse = ""; and add the chars taken from the stack:
while (!PDrome.isEmpty())
reverse += PDrome.pop();
Naming detail
Please use non capital letters to start fields and method names:
"someIntegerVariable"
"methodForCalculation"
and only capital letters to start class and interface names:
Stack
ArrayList
MyClass
:)
(from the Java conventions)
What are you actually doing here?
PDrome.pop()=reverse.charAt(i);
You should have use PDrome.pop() to retrieve one char at a time and append it to reverse.
This is a much cleaner way to write it in my opinion. It is a recursive approach.
bool isPalindrome(String s)
{
if(s.length() <= 1)
return true;
return s[0] == s[s.length() - 1] && isPalindrome(s.substr(1, s.length() - 2);
}
It is MUCH shorter as you can see.

Categories