Running 2 java codes - java

I have 2 java programs (ciphers), one is Playfair and second is Transposition.
Now i want to run Playfair code, then right after that compile Transposition using the result i got from Playfair code. How should i make this?(
Playfair code
import java.awt.Point;
import java.util.Scanner;
public class PlayfairCipher {
private static char[][] charTable;
private static Point[] positions;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String key = prompt("Enter an encryption key (min length 6): ", sc, 6);
String txt = prompt("Enter the message: ", sc, 1);
String jti = prompt("Replace J with I? y/n: ", sc, 1);
boolean changeJtoI = jti.equalsIgnoreCase("y");
createTable(key, changeJtoI);
String enc = encode(prepareText(txt, changeJtoI));
System.out.printf("%nEncoded message: %n%s%n", enc);
System.out.printf("%nDecoded message: %n%s%n", decode(enc));
}
private static String prompt(String promptText, Scanner sc, int minLen) {
String s;
do {
System.out.print(promptText);
s = sc.nextLine().trim();
} while (s.length() < minLen);
return s;
}
private static String prepareText(String s, boolean changeJtoI) {
s = s.toUpperCase().replaceAll("[^A-Z]", "");
return changeJtoI ? s.replace("J", "I") : s.replace("Q", "");
}
private static void createTable(String key, boolean changeJtoI) {
charTable = new char[5][5];
positions = new Point[26];
String s = prepareText(key + "ABCDEFGHIJKLMNOPQRSTUVWXYZ", changeJtoI);
int len = s.length();
for (int i = 0, k = 0; i < len; i++) {
char c = s.charAt(i);
if (positions[c - 'A'] == null) {
charTable[k / 5][k % 5] = c;
positions[c - 'A'] = new Point(k % 5, k / 5);
k++;
}
}
}
private static String encode(String s) {
StringBuilder sb = new StringBuilder(s);
for (int i = 0; i < sb.length(); i += 2) {
if (i == sb.length() - 1)
sb.append(sb.length() % 2 == 1 ? 'X' : "");
else if (sb.charAt(i) == sb.charAt(i + 1))
sb.insert(i + 1, 'X');
}
return codec(sb, 1);
}
private static String decode(String s) {
return codec(new StringBuilder(s), 4);
}
private static String codec(StringBuilder text, int direction) {
int len = text.length();
for (int i = 0; i < len; i += 2) {
char a = text.charAt(i);
char b = text.charAt(i + 1);
int row1 = positions[a - 'A'].y;
int row2 = positions[b - 'A'].y;
int col1 = positions[a - 'A'].x;
int col2 = positions[b - 'A'].x;
if (row1 == row2) {
col1 = (col1 + direction) % 5;
col2 = (col2 + direction) % 5;
} else if (col1 == col2) {
row1 = (row1 + direction) % 5;
row2 = (row2 + direction) % 5;
} else {
int tmp = col1;
col1 = col2;
col2 = tmp;
}
text.setCharAt(i, charTable[row1][col1]);
text.setCharAt(i + 1, charTable[row2][col2]);
}
return text.toString();
}
}
and Transposition
import java.util.*;
import java.util.Scanner; // needed for Scanner
public class transpositionCipher
{
public static void main(String args[])
{
String key;
String message;
String encryptedMessage;
// Letters in the x-axis
int x=0;
// Letters in the y-axis
int y=0;
// Prompt the user
System.out.print( "Type your Key : " );
// Read a line of text from the user.
Scanner scan = new Scanner(System.in);
key = scan.nextLine();
// Display the input back to the user.
System.out.println( "Your Key is " + key );
//Prompt the user
System.out.print( "Type your Message : " );
//Read a line of text from the user.
message = scan.nextLine();
//Display the input back to the user.
System.out.println( "Your Message is " + message );
int msgchar = message.length();
int keycahr = key.length();
if (!((msgchar % keycahr) == 0)){
do{
message = message + "x";
msgchar = message.length();
}while(!((msgchar % keycahr) == 0));
}
encryptedMessage = "";
// To set the temp as [x][y]
char temp[][]=new char [key.length()][message.length()];
char msg[] = message.toCharArray();
// To populate the array
x=0;
y=0;
// To convert the message into an array of char
for (int i=0; i< msg.length;i++)
{
temp[x][y]=msg[i];
if (x==(key.length()-1))
{
x=0;
y=y+1;
} // Close if
else
{
x++;
}
} // Close for loop
// To sort the key
char t[]=new char [key.length()];
t=key.toCharArray();
Arrays.sort(t);
for (int j=0;j<y;j++)
{
for (int i=0;i<key.length();i++)
{
System.out.print(temp[i][j]);
}
System.out.println();
}
System.out.println();
// To print out row by row (i.e. y)
for (int j=0;j<y;j++){
// To compare the the sorted Key with the key
// For char in the key
for (int i=0;i<key.length();i++){
int pos=0;
// To get the position of key.charAt(i) from sorted key
for (pos=0;pos<t.length;pos++){
if (key.charAt(i)==t[pos]){
// To break the for loop once the key is found
break;
}
}
System.out.print(temp[pos][j]);
encryptedMessage+=temp[pos][j];
}
System.out.println();
}
System.out.println(encryptedMessage);
System.exit(0);
}enter code here
}

Take the output of one operation (PlayfairCipher.encode), which is the cyphertext and input it to the second operation (your transpositionial code) as it's plaintext.
Scanner sc = new Scanner(System.in);
String key = prompt("Enter an encryption key (min length 6): ", sc, 6);
String txt = prompt("Enter the message: ", sc, 1);
String jti = prompt("Replace J with I? y/n: ", sc, 1);
boolean changeJtoI = jti.equalsIgnoreCase("y");
PlayfairCipher.createTable(key, changeJtoI);
String enc = PlayfairCipher.encode(prepareText(txt, changeJtoI));
//Now instead of using 'message' for the second encryption, you use the output of the first operation 'enc'
int x=0;
int y=0;
int msgchar = enc.length();
int keycahr = key.length();
if (!((msgchar % keycahr) == 0)){
do{
enc = enc + "x";
msgchar = enc.length();
}while(!((msgchar % keycahr) == 0));
}
...

Related

How to swap every 2 letters in a String? - Java

So I'm currently working on a personal project and I made a program that tries to swap every 2 letter in a given string.
So I want the output like this:
(Note Input String is "abllte")
ballet
So I wrote this method
public static String codeString(String input) {
String firstLetter = "";
String secoundLetter = "";
String result = "";
for(int i = 0; i < input.length()-1; i++){
for(int c = 0; c < i; c = c +2)
{
firstLetter = input.substring(c,c + 1);
secoundLetter = input.substring(c + 1, c + 2);
}
result = result + secoundLetter + firstLetter;
}
return result;
}
But I get this output:
ababllll
Any idea how to solve this?
Thank you in advance!
You only need one loop. This works for both even and odd length character strings.
first, the methods used return the StringBuilder in its current modified state.
So sb.insert(i, sb.charAt(i+1)) inserts the char at i+1 at i
So if sb contained ab, StringBuilder would now contain bab
insert returns the modifed StringBuilder so now sb.deleteCharAt(i+2) deletes the second a (the one that was just copied).
this is then repeated until all characters are swapped.
Because of the constant inserting and deletion of characters this is not very efficient.
for (String s : new String[] { "abcdefg", "abcdefgh" }) {
StringBuilder sb = new StringBuilder(s);
for (int i = 0; i < sb.length() - 1; i += 2) {
sb.insert(i, sb.charAt(i + 1)).deleteCharAt(i + 2);
}
System.out.println(s + " -> " + sb);
}
Prints
abcdefg -> badcfeg
abcdefgh -> badcfehg
For a more efficient algorithm, this would be the way to go. It's also much more intuitive.
for (String s : new String[] { "abcdefg", "abcdefgh" }) {
char ch[] = s.toCharArray();
for (int i = 0; i < ch.length - 1; i+=2) {
char c = ch[i];
ch[i] = ch[i + 1];
ch[i + 1] = c;
}
String d = String.valueOf(ch);
System.out.println(s + " -> " + d);
}
This prints the same as above.
I'm not sure what the point of your nested for loop is. You can do this with just one loop.
public static String codeString(String input) {
String firstLetter = "";
String secoundLetter = "";
String result = "";
for(int i = 0; i < input.length()-1; i+=2){
firstLetter = input.substring(i,i+1);
secoundLetter = input.substring(i+1,i+2);
result = result + secoundLetter + firstLetter;
}
return result;
}
If your input string has an odd number of characters, you'll have to append the extra last character.
public static String codeString(String input) {
String firstLetter = "";
String secoundLetter = "";
String result = "";
for(int i = 0; i < input.length()-1; i+=2){
firstLetter = input.substring(i, i+1);
secoundLetter = input.substring(i+1, i+2);
result = result + secoundLetter + firstLetter;
}
if(input.length() % 2 == 1)
result += input.substring(input.length()-1, input.length());
return result;
}
You do not need a nested loop. Change the outer loop to step by 2 i.e. i = i + 2 and remove the inner loop.
public class Main {
public static void main(String[] args) {
System.out.println(codeString("abllte"));
}
public static String codeString(String input) {
String firstLetter = "";
String secondLetter = "";
String result = "";
for (int i = 0; i < input.length() - 1; i = i + 2) {
firstLetter = input.substring(i, i + 1);
secondLetter = input.substring(i + 1, i + 2);
result = result + secondLetter + firstLetter;
}
return result;
}
}
Output:
ballet
An alternative approach:
You can create a function with two parameters: input string as the first parameter and n as the second parameter, where every n characters in the input string need to be reversed.
public class Main {
public static void main(String[] args) {
System.out.println(codeString("abllte", 1));
System.out.println(codeString("abllte", 2));
System.out.println(codeString("abllte", 3));
System.out.println(codeString("abllte", 4));
}
public static String codeString(String input, int n) {
if (n <= input.length() / 2) {
StringBuilder result = new StringBuilder();
for (int i = 0; i < input.length() - n + 1; i = i + n) {
result.append(new StringBuilder(input.substring(i, i + n)).reverse());
}
return result.toString();
} else {
return input;
}
}
}
Output:
abllte
ballet
lbaetl
abllte

What is wrong with this swapping program in Java, why and what should I do?

I am making a multiple string input random swap without using a temp variable.
But when I input, this happens a few times:
This happens more frequently... (note that the first output is always null and some outputs occasionally repeat)
My code:
import java.util.Arrays;
import java.util.Scanner;
public class myFile {
public static boolean contains(int[] array, int key) {
Arrays.sort(array);
return Arrays.binarySearch(array, key) >= 0;
}
public static void println(Object line) {
System.out.println(line);
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String finalText = "";
String[] input = new String[5];
String[] swappedInput = new String[input.length];
int[] usedIndex = new int[input.length];
int swapCounter = input.length, useCounter;
for (int inputCounter = 0; inputCounter < input.length; inputCounter++) { //input
println("Enter input 1 " + (inputCounter + 1) + ": ");
input[inputCounter] = in.nextLine();
}
while (--swapCounter > 0) {
do{
useCounter = (int) Math.floor(Math.random() * input.length);
}
while (contains(usedIndex, useCounter));
swappedInput[swapCounter] = input[swapCounter].concat("#" + input[useCounter]);
swappedInput[useCounter] = swappedInput[swapCounter].split("#")[0];
swappedInput[swapCounter] = swappedInput[swapCounter].split("#")[1];
usedIndex[useCounter] = useCounter;
}
for (int outputCounter = 0; outputCounter < input.length; outputCounter++) {
finalText = finalText + swappedInput[outputCounter] + " ";
}
println("The swapped inputs are: " + finalText + ".");
}
}
Because of randomality some times useCounter is the same as swapCounter and now look at those lines (assume useCounter and swapCounter are the same)
swappedInput[swapCounter] = input[swapCounter].concat("#" + input[useCounter]);
swappedInput[useCounter] = swappedInput[swapCounter].split("#")[0];
swappedInput[swapCounter] = swappedInput[swapCounter].split("#")[1];
In the second line you are changing the value of xxx#www to be www so in the third line when doing split you dont get an array with two values you get an empty result thats why exception is thrown in addition you should not use swappedInput because it beats the pourpuse (if i understand correctly yoush shoud not use temp values while you are using addition array which is worse) the correct sollution is to only use input array here is the solution
public class myFile {
public static boolean contains(int[] array, int key) {
Arrays.sort(array);
return Arrays.binarySearch(array, key) >= 0;
}
public static void println(Object line) {
System.out.println(line);
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String finalText = "";
String[] input = new String[5];
int[] usedIndex = new int[input.length];
int swapCounter = input.length, useCounter;
for (int inputCounter = 0; inputCounter < input.length; inputCounter++) { //input
println("Enter input 1 " + (inputCounter + 1) + ": ");
input[inputCounter] = in.nextLine();
}
while (--swapCounter >= 0) {
do {
useCounter = (int) Math.floor(Math.random() * input.length);
}
while (contains(usedIndex, useCounter));
// Skip if results are the same
if (useCounter == swapCounter) {
swapCounter++;
continue;
}
input[swapCounter] = input[swapCounter].concat("#" + input[useCounter]);
input[useCounter] = input[swapCounter].split("#")[0];
input[swapCounter] = input[swapCounter].split("#")[1];
usedIndex[useCounter] = useCounter;
}
for (int outputCounter = 0; outputCounter < input.length; outputCounter++) {
finalText = finalText + input[outputCounter] + " ";
}
println("The swapped inputs are: " + finalText + ".");
}
}

Using java, input string="aabbcdeaaaabbb" and the output must be aaaa

Using java, input string="aabbcdeaaaabbb" and the output must be aaaa, as sequence here is having repeated 4 times a. Can anyone help me to get this "aaaa" as output using java implementation.
Algorithm to find the Longest substring having same character repeated.
for eg:
I/P: aabbcdefaaaacccccc O/P: cccccc
Please check my program below and suggest any optimization for faster processing:
public class LongestSubString {
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(
System.in));
System.out
.println("Enter a word to find longest substring with same characters repeated");
String word = reader.readLine();
System.out.println("Entered word is: " + word);
System.out.println("Longest repeated characters substring is: "
+ subStringFinder(word));
}
/*
*longest substring finder with same character repeated
*/
public static String subStringFinder(String word) {
char[] tokens = word.toCharArray();
int len = tokens.length;
int wordLen = word.length();
System.out.println("len of input word: " + wordLen);
List<String> myList = new ArrayList<>();
StringBuilder strConcat = new StringBuilder("");
for (int j = 0; j <= len - 1; j++) {
if (j + 1 > len - 1) {
if ((strConcat.length() >= 1)
&& (strConcat.charAt(strConcat.length() - 1) == (tokens[j]))) {
strConcat.append("" + tokens[j]);
myList.add(strConcat.toString());
}
}
else {
if (tokens[j] == tokens[j + 1]) {
if ((strConcat.length() >= 1)
&& (strConcat.charAt(strConcat.length() - 1) == (tokens[j]))) {
strConcat.append("" + tokens[j]);
myList.add(strConcat.toString());
} else {
strConcat = new StringBuilder("");
strConcat.append("" + tokens[j]);
}
} else {
if ((strConcat.length() >= 1)
&& (strConcat.charAt(strConcat.length() - 1) == (tokens[j]))) {
strConcat.append("" + tokens[j]);
myList.add(strConcat.toString());
} else {
strConcat = new StringBuilder("");
strConcat.append("" + tokens[j]);
}
}
}
}
int max = 0, index = 0;
for (int i = 0; i < myList.size(); i++) {
String strEle = myList.get(i);
int strLen = strEle.length();
if (max < strLen) {
max = strLen;
index = i;
}
}
return myList.get(index);
}
}
I believe your code is overly complicated. You don’t need a StringBuilder nor an ArrayList. I tried to understand your intention, but then skipped it and wrote my own version instead. Hope it helps anyway.
public static String subStringFinder(String word) {
if (word == null || word.isEmpty()) {
return word;
}
char currentChar = word.charAt(0);
int longestStart = 0;
int longestLength = 0;
int currentStart = 0;
int currentLength = 1;
for (int ix = 1; ix < word.length(); ix++) {
if (word.charAt(ix) == currentChar) {
currentLength++;
} else {
if (currentLength > longestLength) {
longestStart = currentStart;
longestLength = currentLength;
}
currentChar = word.charAt(ix);
currentStart = ix;
currentLength = 1;
}
}
if (currentLength > longestLength) {
longestStart = currentStart;
longestLength = currentLength;
}
return word.substring(longestStart, longestStart + longestLength);
}
String in = "aabbcdeaaaabbb";
String t;
ArrayList<String> out = new ArrayList<String>();
String l="";
int c=0;
String n;
for(int i=0;i<in.length;i++) {
n=in.substring(i, i+1); //get the current character
if(n.equals(l)){
l=n; c++;
}
else {
t=n;
for(int j=1;j<c;j++) {
n+=t;
}
c=0;
out.add(n);
c=0;
}
}

Count Occurrence of each letter in a loop and display with letter with the most number of occurences

I'm having trouble in using this code I found on the net. my goal is to count the number of times a letter show and display the letter with the most occurrence and if there are 2 or more letters that occurred at the same number of times then they will both show up.
This is my current output:
Current Output
Here is the code i found on the net and working with:
public void fcount(String str)
{
int[] occurence = new int[255];
// Scanner scanner = new Scanner(System.in);
// str = scanner.nextLine();
// optional to put eveyting in uppercase
str = str.toUpperCase();
// convert to char
char[] digit = str.toCharArray();
// count
for(int i = 0; i < digit.length; i++)
occurence[digit[i]]++;
// find max
int max = 0; // max value
char maxValue = 0; // max index
for(int i = 0; i < occurence.length; i++)
{
// new max ?
if(occurence[i] > max) {
max = occurence[i];
maxValue = (char) i;
}
}
// result
System.out.println("Character used " + max + " times is: " + (char) maxValue);
// return "";
}
And Here is the the loop where i'm using it:
public void calpha()
{
char startUpper = 'A';
String cones = null;
for (int i = 0; i < 12; i++) {
cones = Character.toString(startUpper);
System.out.println(startUpper);
}
fcount(cones);
}
There is an error in you loop:
cones = Character.toString(startUpper);
You are just re-assigning the value of cones, so fcount receives a string containing only the last character.
A solution is
cones += Character.toString(startUpper);
You have an issue in your int[] occurence = new int[255]; statement and usage: occurence[digit[i]]++ may lead to IndexOutOfBoundsException since char type is up to 2^16
Your code can not deal with non-ANSII characters. Mine does.
import java.util.*;
class Problem {
public static void main(String args[]) {
final String input = "I see trees outside of my window.".replace(" ", "");
final List<Character> chars = new ArrayList<>(input.length());
for (final char c : input.toCharArray()) {
chars.add(c);
}
int maxFreq = 0;
final Set<Character> mostFrequentChars = new HashSet<>();
for(final char c : chars) {
final int freq = Collections.frequency(chars, c);
if (freq > maxFreq) {
mostFrequentChars.clear();
mostFrequentChars.add(c);
maxFreq = freq;
}
else {
if (freq == maxFreq) {
mostFrequentChars.add(c);
}
}
}
for (Character c : mostFrequentChars) {
System.out.println(c);
}
}
}
Try this code:
public static void main(String[] args) throws IOException {
char startUpper = 'A';
String cones = "";
for (int i = 0; i < 12; i++) {
cones += Character.toString(startUpper);
System.out.println(startUpper);
}
fcount(cones);
}
public static void fcount(String str) {
HashMap<Character, Integer> hashMap = new HashMap<Character, Integer>();
HashSet<Character> letters = new HashSet<Character>();
str = str.toUpperCase();
//Assume that string str minimium has 1 char
int max = 1;
for (int i = 0; i < str.length(); i++) {
int newValue = 1;
if (hashMap.containsKey(str.charAt(i))) {
newValue = hashMap.get(str.charAt(i)) + 1;
hashMap.put(str.charAt(i), newValue);
if (newValue>=max) {
max = newValue;
letters.add(str.charAt(i));
}
} else {
hashMap.put(str.charAt(i), newValue);
}
}
System.out.println("Character used " + max + " times is: " + Arrays.toString(letters.toArray()));
// return "";
}

Java Eclipse Encryption Trouble

I need to make a program that will encrypt and decrypt what the user enters. I am having trouble figuring out a way that will combine all the chars to make the encrypted word. Here is my code (I am using Eclipse):
import java.util.Scanner;
public class Encryption
{
public static String message = "";
public static boolean hasMessage = false;
public static boolean encrypted = false;
static char a = 0;
static char b;
static int w;
static int x;
static int y;
static int z;
static int i;
public static void display()
{
System.out.println("Message: " + message + "\n");
}
public static void encrypt(String word)
{
if(!hasMessage)
{
System.out.println("No message");
// Tell the user there is no message
}
else if(encrypted)
{
System.out.println("Message is already encrypted");
// Tell the user the message is already encrypted
}
else
{
// Reset the message to blank
for (int i = 0; i < message.length(); i++) {
i = j;
``char a = message.charAt(i);
for (int j=0; j==message.length(); j++)
{
int w = (int) a * 2;
int x = (int) w + 2;
char y = (char) x;
}
}
}
=
//get char from each letter (increase char each time), cast as int
}
System.out.println(message);
encrypted = true;
// Using the parameter word, modify message
// to contain a new value following a predictable pattern
// Hint: alter each character's ASCII value by casting
// to an integer and using math operators
// Display the new message
// Set encrypted to true
}
public static void decrypt(String word)
{
if(!hasMessage)
{
System.out.println("No message");
// Tell the user there is no message
}
else if(!encrypted)
{
System.out.println("Message not encrypted");
// Tell the user the message is not encrypted
}
else
{
int a = (int) w / 2;
int w = (int) x - 2;
char x = (char) y;
System.out.println(message);
// Like encrypt, but in reverse
}
}
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
int menuChoice = 0;
while(menuChoice != 4)
{
System.out.println( "[1] Enter Word\n" +
"[2] Encrypt\n" +
"[3] Decrypt\n" +
"[4] Quit\n");
menuChoice = sc.nextInt();
if(menuChoice == 1)
{
System.out.println("Input message");
message = sc.next();
// prompt user to input message
// assign next word to the class-level variable message
hasMessage = true;
encrypted = false;
// set hasMessage to true
// set encrypted to false
}
else if(menuChoice == 2)
{
encrypt(message);
}
else if(menuChoice == 3)
{
decrypt(message);
}
}
}
}
The trouble probably from the for loop. I don't really know what this for loop should do so I can't help you to change it.
for (message.charAt(a); a==message.length(); a++)
{
int w = (int) a * 2;
int x = (int) w + 2;
char y = (char) x;
}
What this does in pseudocode:
Ask for the character at 0 in string a and do nothing. This is only wasting time so I don't know what this actually is for.
Check if the message is empty if yes go on otherwise quite the loop.
Execute the code in this loop.
I guess what you want to do is loop through the string char by char like this:
for (int i = 0; i < message.length(); i++) {
char a = message.charAt(i);
}

Categories