I feel as though I have the math and logic correct, I'm not sure what I'm doing wrong. Iv'e tried it with a few different values of b and nothing works. For some reason, "f" is always changed to "v" and "k" always to "q", no matter the constant used. My output is: glqvafkpuzejotydinsxchmrwb, abcdwvghijqlmnolqrstgvwxyb. Decipher method works when b = 0.
public class Asgn2No2CodeDecode {
public static void main(String[] args) {
System.out.println(affineCipher("abcdefghijklmnopqrstuvwxyz"));
System.out.println(affineDecipher(affineCipher("abcdefghijklmnopqrstuvwxyz")));
}
public static String affineCipher(String plainTxt)
{
StringBuilder cipherTxt = new StringBuilder();
String alphabet = "abcdefghijklmnopqrstuvwxyz";
int a = 5;
int b = 6;
int charNum = 0;
char alphChar;
char ciphChar;
for (int i = 0; i < plainTxt.length(); i++)
{
ciphChar = plainTxt.charAt(i);
if (Character.isLetter(ciphChar))
{
for (int j = 0; j<alphabet.length(); j++)
{
alphChar = alphabet.charAt(j);
if (ciphChar == alphChar)
{
charNum = ((a*j + b)%26);
}//end if
}//end for alph
cipherTxt.append(alphabet.charAt(charNum));
}else cipherTxt.append(plainTxt.charAt(i));
}//end for plain
return cipherTxt.toString();
}//end affineCipher(String)
public static String affineDecipher(String cipherTxt)
{
StringBuilder plainTxt = new StringBuilder();
String alphabet = "abcdefghijklmnopqrstuvwxyz";
int aInv = 21;
int b = 6;
int charNum = 0;
char alphChar;
char ciphChar;
for (int i = 0; i < cipherTxt.length(); i++)
{
ciphChar = cipherTxt.charAt(i);
if (Character.isLetter(ciphChar))
{
for (int x = 0; x<alphabet.length(); x++)
{
alphChar = alphabet.charAt(x);
if (ciphChar == alphChar)
{
if (x>=b)
{
charNum = (((aInv*(x-b))%26));
}
else charNum = (-((aInv*(x-b))%26));
}//end if
}//end for alph
plainTxt.append(alphabet.charAt(charNum));
}else plainTxt.append(cipherTxt.charAt(i));
}//end for plain
return plainTxt.toString();
}//end affineCipher(String)
}
Related
First Class which is giving me the error. I'm to make an array with the letters A-Z, and then have the user input the keys which it takes and compares each character's position in the array of the key with the position of a user inputted string
import java.util.*;
public class Encrypt{
private Square plain1;
private Square plain2;
private Square Encrypt1;
private Square Encrypt2;
public Encryption(String key1, String key2) {
Square plain1 = new Square();
Square plain2 = new Square();
Square Encrypt1= new Square(key1);
Square Encrypt2= new Square(key2);
}
public String encrypt(String msg) {
String EmpS = "";
String STR = "";
for(int i = 0; i < message.length(); i+=2){
char iMsg = message.charAt(i);
char iMsg2 = message.charAt(i+1);
int[] posRay = plain1.findPosition(iMsg);
int[] posRay2 = plain2.findPosition(iMsg2);
String answer = "" + Encrypt1.getChar(posRay[0], posRay2[1]);
String Combined = "" + answer;
String answer2 = "" + Encrypt2.getChar(posRay2[0], posRay[1]);
String Combined2 = "" + answer2;
String BothCom = Combined + Combined2;
STR = STR.concat(BothCom);
return STR;
}
return STR;
}
2nd class that is responsible for the array
public class Square {
private char[][] matrix;
public Square() {
arr= new char[5][5];
int ascii= 65;
for (int i = 0; i < 5; i++){
for(int j = 0; j < 5; j++){
arr[i][j] = (char) ascii;
ascii++;
}
}
}
}
public int[] findPosition(char Chart) {
int[] position= new int[2];
position[0] = -1;
popositions[1] = -1;
for (int i = 0; i < 5; i++){
for (int j = 0; i < 5; j++){
if(matrix[i][j] == Chart){
posistion[0] = i;
position[1] = j;
return position;
}
}
}
I'm getting this as an error (everything else works), what's the issue?:
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "Square.getPos(char)" because "this.plain1" is null
at findPosition.encrypt(Encrypt.java:45)
at IO.printResults(IO.java:101)
at Test.main(Proj8.java:26)
You are not assigning your class variables, you are actually assigning new local variables inside the method. Change to:
public Encryption(String key1, String key2) {
plain1 = new Square();
plain2 = new Square();
Encrypt1= new Square(key1);
Encrypt2= new Square(key2);
}
This was the code I designed to solve this problem but it seems not to work at all.I used nested for loops to compare the letters of the first string and the second string since they are likely to have different lengths
import java.util.*;
public class Trim
{
public static String myTrim(String input, String list)
{
String r = "";
for (int i = 1; i < input.length();i++)
{
for (int k = 1; k < list.length();k++)
{
if (input.charAt(i) != list.charAt(i))
{
r += input.charAt(i);
}
}
}
return r;
}
}
I guess you should use the method String.indexOf.
So:
public static String myTrim(String input, String list)
{
StringBuilder result = new StringBuilder();
char c;
for (int i = 0; i < input.length(); i++)
{
c = input.charAt(i);
if (list.indexOf(c) < 0)
result.append(c);
}
return result.toString();
}
Try using a flag to determine whether to character gets repeated or not:
String r = "";
for (int i = input.length() - 1; 0 <= i; i --) {
if (-1 == list.indexOf(input.charAt(i))) {
r += input.charAt(i);
}
}
OR
String r = "";
boolean found;
for (int i = input.length() - 1, j = list.length() - 1; 0 <= i; i--) {
found = false;
for (int k = j; 0 <= k; k--) {
if (list.charAt(k) == input.charAt(i)) {
found = true;
break;
}
}
if (!found) {
r += input.charAt(i);
}
}
We have to filter out the characters from input which appears in list.
Now we have to check whether each character of the input appears in the list or not.
The k value will be less then list.length() if the character of input present in the list string.
After the loop we check the k value and append it to the new string.
public static String myTrim(String input, String list)
{
String r = "";
for (int i = 0; i < input.length();i++)
{
int k = 0;
for (; k < list.length();k++)
{
if (input.charAt(i) == list.charAt(k))
{
break;
}
}
if(k == list.length())
r += input.charAt(i);
}
return r;
}
A nice one-liner solution would be to use Guava Charmatcher:
CharMatcher.anyOf(list).removeFrom(input);
I have tried this code and it's working fine with both of your inputs
for (int i = 0; i < S1.length(); i++) {
for(int j=0;j< S2.length();j++) {
if(S1.charAt(i)==S2.charAt(j)) {
char Temp= S2.charAt(j);
String Temp2=String.valueOf(Temp);
S1=S1.replace(Temp2, "");
}
}
}
This is code
import java.util.Scanner;
public class StringRemoveChar {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String S1, S2;
S1 = scanner.nextLine();
S2 = scanner.nextLine();
for (int i = 0; i < S1.length(); i++) {
for (int j = 0; j < S2.length(); j++) {
if (S1.charAt(i) == S2.charAt(j)) {
char Temp = S2.charAt(j);
String Temp2 = String.valueOf(Temp);
S1 = S1.replace(Temp2, "");
System.out.println(S1.length());
}
}
}
System.out.println(S1);
}
}
Input:
Miyazaki
you
Output:
Miazaki
We can use replaceAll and use one loop over ,this will make the solution simple
public static String myTrim(String input, String list)
{
for(int i=0;i<list.length();i++)
{
input=input.replaceAll(list.charAt(i)+"","");
}
return input;
}
Input: myTrim("Miyazaki","you")
Output: Miazaki
Full code for reference
package stackoverflow.string;
public class StringManipulation
{
public static void main(String[] args)
{
System.out.println(myTrim("University of Miami","city"));
}
public static String myTrim(String input, String list)
{
for(int i=0;i<list.length();i++)
{
input=input.replaceAll(list.charAt(i)+"","");
}
return input;
}
}
I'm trying to solve a palindrome problem that the input consists of Strings , if the concatenation of two strings represent a palindrome word(A palindrome is a word which can be read the same way in either direction. For example, the following
words are palindromes: civic, radar, rotor, and madam)
then save it into array to print it latter otherwise print "0"
but I'm having a problem in filling the null index with zeros , here I get Exception
for (int re = 0; re < result.length; re++) {
if (result[re].equals(null)) {
result[re] = "0";
}
}
"Exception in thread "main" java.lang.NullPointerException"
here is my full code
import java.util.Scanner;
public class Palindrome {
public static String reverse(String R2) {
String Reverse = "";
String word_two = R2;
int ln = word_two.length();
for (int i = ln - 1; i >= 0; i--) {
Reverse = Reverse + word_two.charAt(i);
}
return Reverse;
}
public static void main(String[] args) {
Scanner inpoot = new Scanner(System.in);
int stop = 0;
String pal1;
int Case = inpoot.nextInt();
String result[] = new String[Case];
String Final;
int NumberofWords;
for (int i = 0; i < Case; i++) {
NumberofWords = inpoot.nextInt();
String words[] = new String[NumberofWords];
for (int array = 0; array < words.length; array++) {
words[array] = inpoot.next();
}
for (int word1 = 0; word1 < NumberofWords; word1++) {
if (stop > Case) {
break;
}
for (int word2 = 0; word2 < NumberofWords; word2++) {
if (word1 == word2) {
continue;
}
Final = "" + words[word1].charAt(0);
if (words[word2].endsWith(Final)) {
pal1 = words[word1].concat(words[word2]);
} else {
continue;
}
if (pal1.equals(reverse(pal1))) {
result[i] = pal1;
stop++;
break;
} else {
pal1 = "";
}
}
}
}
// HERE IS THE PROBLEM
for (int re = 0; re < result.length; re++) {
if (result[re].equals(null)) {
result[re] = "0";
}
}
for (int x = 0; x < result.length; x++) {
System.out.println("" + result[x]);
}
}
}
A test such as anObject.equals(null) makes no sense. Indeed, if anObject is null, it will throw a NullPointerException (NPE), and if it is not, it will always return false.
To test if a reference is null, just use anObject == null.
If you want to check whether result[re] is null, you cannot use equals. Use the identity comparison:
if (result[re] == null) {
result[re] = "0";
}
I am looking for some help with a project i am working on. I am relatively new to java and am working to make a function to generate a password. There is probably alot of error in this or this might be completely wrong so please be nice to a newbie >.<
import java.util.Random;
public class StillTesting {
public static void main(String[] args) {
System.out.println("Your new password is: " + generateValidPassword());
}
static private String generateValidPassword() {
String numcase = "";
String lowcase = "";
String upcase = "";
String halfpass = numcase.concat(upcase);
String returnString = halfpass.concat(lowcase);
System.out.print(returnString);
Random r = new Random();
String loweralphabet = "abcdefghijklmnopqrstuvwxyz";
int n = loweralphabet.length();
String upperalphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
int N = upperalphabet.length();
int num = 0;
for (int i = 0; i < 3; i++) {
num = r.nextInt(9);
numcase = String.valueOf(num = r.nextInt(9));
return numcase;
}
for (int i = 0; i < 3; i++) {
lowcase = String.valueOf(loweralphabet.charAt(r.nextInt(n)));
return lowcase;
}
for (int i = 0; i < 3; i++) {
upcase = String.valueOf(upperalphabet.charAt(r.nextInt(N)));
return upcase;
}
return returnString;
}
}
You may want to try removing your return statements in your loop something like this:
static private String generateValidPassword()
{
String numcase = "";
String lowcase = "";
String upcase = "";
String halfpass = "";
String returnString = "";
System.out.print(returnString);
Random r = new Random();
String loweralphabet = "abcdefghijklmnopqrstuvwxyz";
int n = loweralphabet.length();
String upperalphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
int N = upperalphabet.length();
int num = 0;
for(int i=0;i<3;i++)
{
num=r.nextInt(9);
numcase = String.valueOf(num);
returnString += numcase;
}
for(int i=0;i<3;i++)
{
lowcase = String.valueOf(loweralphabet.charAt(r.nextInt(n)));
returnString += lowcase;
}
for(int i=0;i<3;i++)
{
upcase = String.valueOf(upperalphabet.charAt(r.nextInt(N)));
returnString += upcase;
}
return returnString;
}
This will give you output like 637xiqHMR. You will combine the letters generated from each loop into one string then return the whole string at the end instead of returning at first iteration of first loop.
Is this what you are looking for? The output of the following program is something like 433raeWPV and 675croJWV
public static void main(String[] args) {
System.out.println("Your new password is: " + generateValidPassword());
}
static private String generateValidPassword() {
String pswd = "";
Random r = new Random();
String loweralphabet = "abcdefghijklmnopqrstuvwxyz";
int n = loweralphabet.length();
String upperalphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
int N = upperalphabet.length();
int num = 0;
for (int i = 0; i < 3; i++) {
num = r.nextInt(9);
pswd += String.valueOf(num = r.nextInt(9));
}
for (int i = 0; i < 3; i++) {
pswd += String.valueOf(loweralphabet.charAt(r.nextInt(n)));
}
for (int i = 0; i < 3; i++) {
pswd += String.valueOf(upperalphabet.charAt(r.nextInt(N)));
}
return pswd;
}
Alright, indeed there are some mistakes:
You are setting halfpass and returnString values before assigning the values of numcase, upcase and lowcase
You are returning a value in the first iteration of every for loop, The first return statement will return the first numcase value. More info about how the return statement works here
at the end, the returnString statement is never reached.
Try something like this:
static private String generateValidPassword()
{
String numcase = "";
String lowcase = "";
String upcase = "";
Random r = new Random();
String loweralphabet = "abcdefghijklmnopqrstuvwxyz";
int n = loweralphabet.length();
String upperalphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
int N = upperalphabet.length();
int num = 0;
for(int i=0;i<3;i++)
{
num=r.nextInt(9);
numcase += String.valueOf( num = r.nextInt(9));
}
for(int i=0;i<3;i++)
{
lowcase += String.valueOf(loweralphabet.charAt(r.nextInt(n)));
}
for(int i=0;i<3;i++)
{
upcase += String.valueOf(upperalphabet.charAt(r.nextInt(N)));
}
String halfpass = numcase.concat(upcase);
String returnString = halfpass.concat(lowcase);
System.out.print(returnString);
return returnString;
}
}
Well, it looks like a few people spotted the bugs while I was working, but as I've tidied up the whole thing you might like to take a look at this working version which addresses most of the issues in the original:
import java.util.Random;
public class StillTesting {
public static void main( String[] args )
{
System.out.println("Your new password is: " + generateValidPassword());
}
static private String generateValidPassword()
{
StringBuilder password = new StringBuilder();
Random r = new Random();
final String loweralphabet = "abcdefghijklmnopqrstuvwxyz";
final String upperalphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
for(int i=0;i<3;i++)
{
password.append(String.valueOf(r.nextInt(10)));
}
for(int i=0;i<3;i++)
{
password.append(loweralphabet.charAt(r.nextInt(loweralphabet.length())));
}
for(int i=0;i<3;i++)
{
password.append(upperalphabet.charAt(r.nextInt(upperalphabet.length())));
}
return password.toString();
}
}
I have the below program for sorting Strings based on length. I want to print the shortest element first. I don't want to use Comparator or any API to do this. Where I am going wrong?
public class SortArrayElements {
public static void main(String[] args) {
String[] arr = new String[]{"Fan","dexter","abc","fruit","apple","banana"};
String[] sortedArr = new String[arr.length];
for(int i=0;i<sortedArr.length;i++)
{
sortedArr[i] = compareArrayElements(arr);
}
System.out.println("The strings in the sorted order of length are: ");
for(String sortedArray:sortedArr)
{
System.out.println(sortedArray);
}
}
public static String compareArrayElements(String[] arr) {
String temp = null;
for(int i=0;i<arr.length-1;i++)
{
temp = new String();
if(arr[i].length() > arr[i+1].length())
temp = arr[i+1];
else
temp = arr[i];
}
return temp;
}
}
If you really want to learn Java: use a Comparator. Any other way is bad Java code.
You can however rewrite the Comparator system if you want, it will teach you about proper code structuring.
For your actual code, here are some hints:
Using the proper algorithm is much more important than the Language you use to code. Good algorithms are always the same, no matter the language.
Do never do new in loops, unless you actually need to create new objects. The GC says "thanks".
Change the compareArrayElements function to accept a minimum size and have it return the smallest String with at least minimum size.
You could cut out those Strings that you have considered to be the smallest (set them to null), this will however modify the original array.
Use bubble sort, but instead of comparing ints, just compare String lengths.
I won't write the code for you. You will have to do a little bit of research on this algorithm. Google is your best friend as a programmer.
Good luck.
References:
Bubble sort in Java
Sorting an array of strings
Implement bubbleSort() and swap(). My implementations mutate the original array, but you can modify them to make a copy if you want.
public class SortArrayElements {
public static void main(String[] args) {
String[] arr = new String[]{"Fan", "dexter", "abc", "fruit", "apple", "banana"};
bubbleSort(arr);
System.out.println("The strings in the sorted order of length are: ");
for (String item : arr) {
System.out.println(item);
}
}
// Mutates the original array
public static void bubbleSort(String[] arr) {
boolean swapped = false;
do {
swapped = false;
for (int i = 0; i < arr.length - 1; i += 1) {
if (arr[i].length() > arr[i + 1].length()) {
swap(arr, i, i + 1);
swapped = true;
}
}
} while (swapped);
}
// Mutates the original array
public static void swap(String[] arr, int index0, int index1) {
String temp = arr[index0];
arr[index0] = arr[index1];
arr[index1] = temp;
}
}
Okay, there is the code completely based on loops and on bubble sort. No sets are there as you wanted it. This is a pure loop program so you could understand the nested loops, plus it doesn't change the index or something of the string
import java.util.*;
class strings {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
ArrayList<String> a = new ArrayList<String>(2);
System.out.println("Start entering your words or sentences.");
System.out.println("Type stop to stop.");
String b;
int c = 0, d;
do {
b = in.nextLine();
b = b.trim();
a.add(b);
c++;
}
while (!b.equalsIgnoreCase("stop"));
if (c > 1)
a.remove(a.size() - 1);
System.out.println("Choose the sort you want. Type the corresponding
number");
System.out.println("1. Ascending");
System.out.println("2. Descending");
int sc=in.nextInt();
switch(sc) {
case 1: {
int sag[] = new int[a.size()];
for (int jk = 0; jk < a.size(); jk++) {
b = a.get(jk);
c = b.length();
sag[jk] = c;
}
int temp;
for (int i = 0; i < a.size() - 1; i++) {
for (int j = 0; j < a.size() - 1; j++) {
if (sag[j] > sag[j + 1]) {
temp = sag[j + 1];
sag[j + 1] = sag[j];
sag[j] = temp;
}
}
}
ArrayList saga = new ArrayList();
for (int i = 0; i < sag.length; i++) {
saga.add(sag[i]);
}
for (int i = 0; i < saga.size(); i++) {
for (int j = i + 1; j < saga.size(); j++) {
if (saga.get(i).equals(saga.get(j))) {
saga.remove(j);
j--;
}
}
}
for (int i = 0; i < saga.size(); i++) {
for (int j = 0; j < a.size(); j++) {
String jl = a.get(j);
if (saga.get(i).equals(jl.length()))
System.out.println(jl);
}
}
break;
}
case 2: {
int sag[] = new int[a.size()];
for (int jk = 0; jk < a.size(); jk++) {
b = a.get(jk);
c = b.length();
sag[jk] = c;
}
int temp;
for (int i = 0; i < a.size() - 1; i++) {
for (int j = 0; j < a.size() - 1; j++) {
if (sag[j] < sag[j + 1]) {
temp = sag[j + 1];
sag[j + 1] = sag[j];
sag[j] = temp;
}
}
}
ArrayList saga = new ArrayList();
for (int i = 0; i < sag.length; i++) {
saga.add(sag[i]);
}
for (int i = 0; i < saga.size(); i++) {
for (int j = i + 1; j < saga.size(); j++) {
if (saga.get(i).equals(saga.get(j))) {
saga.remove(j);
j--;
}
}
}
for (int i = 0; i < saga.size(); i++) {
for (int j = 0; j < a.size(); j++) {
String jl = a.get(j);
if (saga.get(i).equals(jl.length()))
System.out.println(jl);
}
}
break;
}
}
}
}
For instance, the following:
ArrayList<String> str = new ArrayList<>(
Arrays.asList(
"Long", "Short", "VeryLong", "S")
);
By lambda:
str.sort((String s1, String s2) -> s1.length() - s2.length());
By static Collections.sort
import static java.util.Collections.sort;
sort(str, new Comparator<String>{
#Override
public int compare(String s1, String s2) {
return s1.lenght() - s2.lenght()
}
});
Both options are implemented by default sort method from List interface
Let's take a following array of String inputArray = ["abc","","aaa","a","zz"]
we can use Comparator for sorting the given string array to sort it based on length with the following code:
String[] sortByLength(String[] inputArray) {
Arrays.sort(inputArray, new Comparator<String>(){
public int compare(String s1, String s2){
return s1.length() - s2.length();
}
});
return inputArray;
}
//sort String array based on length
public class FirstNonRepeatedString {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Please Enter your String");
String str = in.nextLine();
String arrString[] = str.split("\\s");
arrString = sortArray(arrString);
System.out.println("Sort String ");
for(String s:arrString){
System.out.println(s);
}
}
private static String[] sortArray(String[] arrString) {
int length = arrString.length;
String s;
for (int i = 0; i < length ; i++) {
s= new String();
for(int j = 0; j < length; j++ ){
if(arrString[i].length()< arrString[j].length()){
s = arrString[i];
arrString[i] = arrString[j];
arrString[j] = s;
}
}
}
return arrString;
}
}
import java.util.*;
public class SortStringBasedOnTheirLength {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
System.out.println("Enter String:");
String str=sc.nextLine();
String[] str1=str.split("\\s");
for(int i=0;i<str1.length;i++)
{
for(int j=i+1;j<str1.length;j++)
{
if(str1[i].length()>str1[j].length())
{
String temp= str1[i];
str1[i]=str1[j];
str1[j]=temp;
}
}
}
for(int i=0;i<str1.length;i++)
{
System.out.print(str1[i]+" ");
}
}
}