How do I put all those indexes to a char Array? - java

I can't find a way to be to able to put the encryptedChar to a char Array so that I can out put the message on one line. If anyone could give me a simple solution to the problem or help me in any way that would be great!
import java.util.*;
public class MyClass {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
// can get the index without key. DONE
// encrypt message. finish equation.
int encryptKey, encryptedIndex;
int plainLetterIndex = 0;
int loadingBar = 3;
char encryptedChar;
char[] alphaArray = {'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'};
String redo, message;
System.out.println("Welcome to the encrypter and decrypter program. The program will take the message");
System.out.println("and either encrypt it or decrypt it. Depending on what you choose to do.");
System.out.println("");
do {
System.out.println("Please enter your message!");
message = sc.nextLine();
message = message.toUpperCase();
System.out.print("Would you like to re-enter your message? (Y/N)");
redo = sc.nextLine();
} while (redo.equals("Y") || redo.equals("y"));
// declaring arrays
char[] messageArray = message.toCharArray();
char[] encryptedMessageArray = new char[messageArray.length];
// asking for key
System.out.println("Please input the 'key' you would like to use to encrypt your message.");
while(true){
try{
encryptKey = Integer.parseInt(sc.nextLine());
break;
} catch (NumberFormatException ignore){
System.out.println("You have entered an incorrect number, please try again!");
}
}
System.out.println(" ");
for (int i = 0; i < messageArray.length; i++) {
//System.out.println(messageArray[i]);
for (int k = 0; k < alphaArray.length; k++) {
if (messageArray[i] == alphaArray[k]) {
plainLetterIndex = k;
encryptedIndex = (char)(plainLetterIndex + encryptKey) % 26;
encryptedChar = alphaArray[encryptedIndex];
//encryptedMessageArray = encryptedChar;
System.out.print(encryptedChar);
}
}
}
sc.close();
}
}

Use an index variable for encryptedMessageArray, increase it everytime you put a character into encryptedMessageArray
int index = 0;
for (int i = 0; i < messageArray.length; i++) {
//System.out.println(messageArray[i]);
for (int k = 0; k < alphaArray.length; k++) {
if (messageArray[i] == alphaArray[k]) {
plainLetterIndex = k;
encryptedIndex = (char)(plainLetterIndex + encryptKey) % 26;
encryptedChar = alphaArray[encryptedIndex];
encryptedMessageArray[index] = encryptedChar;
index++;
}
}
}
System.out.println();
System.out.println(encryptedMessageArray);

Add either the encrypted char or the original char to your encryptedMessageArray so you can decrypt the array end get the original message
for (int i = 0; i < messageArray.length; i++) {
boolean isCharEncrypted = false;
for (int k = 0; k < alphaArray.length; k++) {
if (messageArray[i] == alphaArray[k]) {
plainLetterIndex = k;
encryptedIndex = (char)(plainLetterIndex + encryptKey) % 26;
encryptedChar = alphaArray[encryptedIndex];
encryptedMessageArray[i] = encryptedChar;
isCharEncrypted = true;
}
}
if (!isCharEncrypted) {
encryptedMessageArray[i] = messageArray[i];
}
}
Here is an alternative solution to avoid the inner for-loop
for (int i = 0; i < messageArray.length; i++) {
char c = messageArray[i];
if (c >= 'A' && c <= 'Z') {
plainLetterIndex = c - 65; //A is ASCII 65
encryptedIndex = (char) (plainLetterIndex + encryptKey) % 26;
encryptedChar = alphaArray[encryptedIndex];
encryptedMessageArray[i] = encryptedChar;
} else {
encryptedMessageArray[i] = messageArray[i];
}
}

Related

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index out of bounds

I was getting this error while running the following code. I couldn't find out what was wrong with the code.
As far as I can see, there's some issue with my second character array. But couldn't find out what was wrong. First tried running the last loop before temp_count. Then also tried temp_count±1. Yet, I failed. I have also tried taking different array size. still no luck
import java.util.Scanner;
public class oop2
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
String str = new String();
int temp_count = 0;
//New input of string
str=sc.nextLine();
char[] c = str.toCharArray();
char[] temp = new char[temp_count];
//Converting uppercase to lower case for convenience
for(int i=0; i<str.length(); i++)
{
if (Character.isUpperCase(c[i]))
{
c[i]=(char) (c[i]+32);
}
}
//verifying whether the alphabet exists
for(char x = 'a'; x<='z'; x++)
{
int count=0;
for(int i=0; c[i]!='\0'; i++)
{
if (c[i]==x)
{
count++;
}
}
//if the alphabet is not found, then putting the alphabet in
if (count==0)
{
temp[temp_count]=x;
temp_count++;
}
}
//Verifying whether it's a pangram or not
if (temp_count==0)
{
System.out.println("Pangram");
}
else
{
//if not pangram then this part will execute
System.out.println("Not Pangram");
System.out.printf("Missing Characters: ");
//printing out the missing character
for(int i=0; i<temp_count-1; i++)
{
System.out.print(temp[i]+", ");
}
}
sc.close();
}
}
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String str = new String();
int temp_count = 0;
//New input of string
str = sc.nextLine();
char[] c = str.toCharArray();
char[] temp = new char[0];
//Converting uppercase to lower case for convenience
for (int i = 0; i < str.length(); i++) {
if (Character.isUpperCase(c[i])) {
c[i] = (char)(c[i] + 32);
}
}
//verifying whether the alphabet exists
for (char x = 'a'; x <= 'z'; x++) {
int count = 0;
for (int i = 0; c[i] != '\0'; i++) {
if (c[i] == x) {
count++;
}
}
//if the alphabet is not found, then putting the alphabet in
if (count == 0) {
char [] copy = new char[temp.length+1];
for (int i = 0; i < temp.length; i++) {
copy[i]=temp[i];
}
copy[copy.length-1] = x;
temp=copy;
}
}
//Verifying whether it's a pangram or not
if (temp_count == 0) {
System.out.println("Pangram");
} else {
//if not pangram then this part will execute
System.out.println("Not Pangram");
System.out.printf("Missing Characters: ");
//printing out the missing character
for (int i = 0; i < temp_count - 1; i++) {
System.out.print(temp[i] + ", ");
}
}
sc.close();
}
}
Blockquote

Array index out of bounds exception. Please help if you can [duplicate]

This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 5 years ago.
Extremely close to having this task finished but can't see which part of this is holding me back. If anybody could put me on the right track I'd be very thankful. the following is the error code that eclipse gives me each time I try to run this.
**Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -2
at lab01.EncodeDecode.backMap(EncodeDecode.java:162)
at lab01.EncodeDecode.Decode(EncodeDecode.java:68)
at lab01.EncodeDecode.(EncodeDecode.java:26)
at lab01.EncodeDecodeTester.main(EncodeDecodeTester.java:14)**
package lab01;
import java.util.*;
/**
*
* #author David Bierbrauer,
*
*/
public class EncodeDecode
{
//method declaration
static String[] originalList,encodedList,decodedList;
static int total;
public EncodeDecode(String[] oL)
{
//instance variable declaration
total = oL.length;
originalList = new String[total];
encodedList = new String[total];
decodedList = new String[total];
originalList = oL;
encodedList= Encode(originalList);
decodedList = Decode(encodedList);
}
public static String[] Encode (String[] originalList)
{
//declare control variables
String currentWord = "", codedWord = "";
char currentChar = ' ';
int i = 0, j = 0, stringLength = 0;
for (i=0; i < total ; i++)
{
currentWord = originalList[i];
stringLength = currentWord.length();
for (j = 0; j < stringLength; j++)
{
currentChar = currentWord.charAt(j);
codedWord = codedWord +forwardMap(currentChar);
}
encodedList[i] = codedWord;
codedWord = "";
}
return encodedList;
}
public static String[] Decode (String[] encodedList)
{
String currentWord = "", encodedWord = "";
char currentChar = ' ';
int i =0, j=0, stringLength = 0;
for(i = 0; i < total; i++)
{
currentWord = encodedList[i];
stringLength = currentWord.length();
for(j = 0; j < stringLength; j++)
{
currentChar = currentWord.charAt(j);
encodedWord = encodedWord + backMap(currentChar);
}
decodedList[i] = encodedWord;
encodedWord = "";
}
return decodedList;
}
public static char forwardMap(char currentChar)
{
char newChar = ' ';
int i = 0;
String encodeMapUpper = "CDEFGHIJKLMNOPQRSTUVWXYZAB";
String encodeMapLower = "cdefghijklmnopqrstuvwxyzab";
String encodeMapNumber = "2345678901";
char [] encodeArrayUpper = encodeMapUpper.toCharArray();
char [] encodeArrayLower = encodeMapLower.toCharArray();
char [] encodeArrayNumber = encodeMapNumber.toCharArray();
if(encodeMapUpper.indexOf(currentChar) != -1)
{
for( i = 0; i < encodeArrayUpper.length; i++)
{
if(currentChar == encodeArrayUpper[i])
{
newChar = encodeArrayUpper[(i+2) % 26];
}
}
}
else if(encodeMapLower.indexOf(currentChar) != -1)
{
for( i = 0; i < encodeArrayLower.length; i++)
{
if(currentChar == encodeArrayLower[i])
{
newChar = encodeArrayLower[(i+2) % 26];
}
}
}
else if(encodeMapNumber.indexOf(currentChar) != -1)
{
for( i = 0; i < encodeArrayNumber.length; i++)
{
if(currentChar == encodeArrayNumber[i])
{
newChar = encodeArrayNumber[(i+2) % 10];
}
}
}
else
{
//element is a special character
newChar = currentChar;
}
return newChar;
}
public static char backMap(char currentChar)
{
char newChar = ' ';
int i = 0;
String decodeMapUpper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
String decodeMapLower = "abcdefghijklmnopqrstuvwxyz";
String decodeMapNumber = "0123456789";
char[] decodeArrayUpper = decodeMapUpper.toCharArray();
char[] decodeArrayLower = decodeMapLower.toCharArray();
char[] decodeArrayNumber = decodeMapNumber.toCharArray();
if (decodeMapUpper.indexOf(currentChar) != -1)
{
for (i=0; i < decodeArrayUpper.length; i++)
{
if (currentChar == decodeArrayUpper[i])
{
newChar = decodeArrayUpper[(i - 2) % 26];
}
}
}
else if(decodeMapLower.indexOf(currentChar) != -1)
{
for (i=0; i < decodeArrayLower.length; i++)
{
if (currentChar == decodeArrayLower[i])
{
newChar = decodeArrayLower[(i - 2) % 26];
}
}
}
else if(decodeMapNumber.indexOf(currentChar) != -1)
{
for (i=0; i < decodeArrayNumber.length; i++)
{
if (currentChar == decodeArrayNumber[i])
{
newChar = decodeArrayNumber[(i - 2) % 10];
}
}
}
else
{
newChar = currentChar;
}
return newChar;
}
//get methods
public String[] getEncodedList() { return encodedList;}
public String[] getDecodedList() { return decodedList;}
}
This is the tester class bellow just in case.
package lab01;
public class EncodeDecodeTester
{
public static void main(String[] args)
{
EncodeDecode testEncoder;
int x = 0;
String[] output = new String[5];
String[] oL = new String[] {"catdog","24","keys","Duck","PIZZA!"};
//create encoder
testEncoder = new EncodeDecode(oL);
System.out.println("Encoded list:");
for( x = 0; x < output.length; x++)
{
output = testEncoder.getEncodedList();
System.out.println(output[x]);
}
System.out.println();
System.out.println("Decoded List:");
for(x = 0; x < output.length; x++)
{
output = testEncoder.getDecodedList();
System.out.println(output[x] + " ");
}
System.out.println();
System.out.println("End");
}
}
Please help I am completely lost for words on what I did wrong here.
The Java % operator doesn't always produce a number between 0 and the second operand. Replace (i - 2) % 26 (which can produce -2) with (i + 24) % 26 and similarly in other places.

Extract the particular portion from a String

I have the below String variable
String s = "abc,xyz,lmn,ijk";
I want to extract only the portion of the String (i.e - 'lmn')
And, Should not use in-built functions like, SubString(), Split(), IndexOf(). But I can use charArray()
And this question was asked in my interview.
I tried the below code,
But not sure how to proceed. Can any one please provide your thoughts?
String s = "abc,xyz,lmn,ijk";
int counter = 0;
char[] ch = s.toCharArray();
for (int i = 0; i < ch.length; i++) {
if (ch[i] == ',') {
counter++;
}
}
Here's one way:
public static void main(String[] args) {
String s = "abc,xyz,lmn,ijk";
char[] ch = s.toCharArray();
int counter = 0;
int place = 2;
for (int i = 0; i < ch.length-2; i++) {
if(ch[i] == ',') {
counter++;
}
if(counter == place && ch[i] != ',') {
System.out.print(ch[i]);
}
}
}
It prints everything after the second comma, but before the third one.
public static void main(String[] args) {
// TODO Auto-generated method stub
String s = "abc,xyz,lmn,ijk";
StringBuffer sb=new StringBuffer();
char[] ch = s.toCharArray();
for (int i = 0; i < ch.length; i++) {
if(','==(ch[i]))
{
if (sb.toString().equals("lmn")) {
System.out.println(sb.toString());
}
else
{
int length=sb.length();
sb.delete(0, length);
}
}
else
{
sb.append(ch[i]);
}
}
}
I would do it this way.
String s = "abc,xyz,lmn,ijk";
String x = "c,x"; // String to found
String r = "";
boolean coincidence = false;
int a=0; // Initial index if of the first character in x is found
int b=0; // Last index If it was possible to search for the last character of x
int c=0; // Index "iterator" on String x
char[] ch = s.toCharArray();
for (int i = 0; i < ch.length; i++) {
if(c == x.length())
break;
else{
if(ch[i] == x.charAt(c) && !coincidence){
a = i; b = i; c++;
coincidence = true;
}
else if(ch[i] == x.charAt(c) && coincidence){
b++; c++;
}else{
coincidence = false;
a = 0; b = 0; c = 0;
}
}
}
System.out.println("String: " + s);
System.out.println("String to find: " + x);
System.out.println("Was found? " + ((coincidence)? "Yes" : "No"));
if(coincidence){
System.out.println("Intervals indexes in String: ["+a + "," + b +"]");
// String extration
for (int i = a; i <= b; i++)
r += s.charAt(i);
System.out.println("String extracted: " + r);
}

How to move each "i" in a string to the next position in java

I want to shift each i in a given string one index to the right. How can I do that? For example:
"Chit Nyein Oo is nothing.";
becomes
"Chti Nyeni Oo si nothnig.";
If i occurs in the last index, it need not change its position.
Use string.replaceAll
string.replaceAll("i(.)", "$1i");
DEMO
EDIT: NOW it works for all conditions. Last letter in the String is 'i' or not, it works.
public class t4 {
public static void main(String[] args) {
String input = "Chit Nyein Oo is nothing.";
char o = 'i';
int indexes = 0;
if(input.charAt(input.length()-1) != 'i'){ //Test if last letter is not 'i'
for (int i = 0; i < input.length(); i++) {
if(input.charAt(i) == o){
indexes++;
}
}
int []positions = new int[indexes];
for (int i = 0; i < input.length(); i++) {
if(input.charAt(i) == o){
positions[indexes-1] = i;
indexes--;
}
}
char[] characters = input.toCharArray();
for (int i = 0; i < positions.length; i++) {
if(characters[input.length()-1] != 'i'){
char temp = characters[positions[i]];
characters[positions[i]] = characters[positions[i]+1];
characters[positions[i]+1] = temp;
} else {
continue;
}
}
String swappedString = new String(characters);
System.out.println(input);
System.out.println(swappedString);
} else { //so last letter is i
char t = input.charAt(input.length()-1);
String ha = input.substring(0, input.length()-1);
input = ha;
for (int i = 0; i < input.length(); i++) {
if(input.charAt(i) == o){
indexes++;
}
}
int []positions = new int[indexes];
for (int i = 0; i < input.length(); i++) {
if(input.charAt(i) == o){
positions[indexes-1] = i;
indexes--;
}
}
char[] characters = input.toCharArray();
for (int i = 0; i < positions.length; i++) {
if(characters[input.length()-1] != 'i'){
char temp = characters[positions[i]];
characters[positions[i]] = characters[positions[i]+1];
characters[positions[i]+1] = temp;
} else {
continue;
}
}
String swappedString = new String(characters);
swappedString = swappedString + Character.toString(t);
System.out.println(input);
System.out.println(swappedString);
}
}
}
You can do this using a StringBuilder.
class Test {
public static void main(String[] args) {
String input = "Chit Nyein Oo is nothingi";
int len = input.length();
StringBuilder sb = new StringBuilder();
// System.out.println(sb);
for(int i=0; i<len; i++) {
char charAti = input.charAt(i);
if(charAti == 'i' && i<len-1) {
sb.append(input.charAt(i+1));
sb.append(charAti);
i++;
}
else {
sb.append(charAti);
}
}
System.out.println(sb);
}
}

How can I avoid repetition of the same number?

This is what I want :
Let the user enter as many numbers as they want until a non number is entered (you may
assume there will be less than 100 numbers). Find the most frequently entered number. (If
there are more than one, print all of them.)
Example output:
Input: 5
Input: 4
Input: 9
Input: 9
Input: 4
Input: 1
Input: a
Most common: 4, 9
I have got to the point in my code where I have managed to find out which are the most common numbers. However, I don't want to print out the same number over and over again; example from above: Most common: 4, 9, 9, 4
What needs to be done?
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String[] input = new String[100];
System.out.print("Input: ");
input[0] = in.readLine();
int size = 0;
for (int i = 1; i < 100 && isNumeric(input[i-1]); i++) {
System.out.print("Input: ");
input[i] = in.readLine();
size = size + 1;
}
/*for (int i = 0; i < size; i++) { //testing
System.out.println(input[i]);
}*/
int numOccur;
int[] occur = new int[size];
for(int i = 0; i < size; i++) {
numOccur = 0;
for (int j = 0; j < size; j++) {
if(input[i].equals(input[j])) {
numOccur = numOccur + 1;
}
}
occur[i] = numOccur;
//System.out.println(numOccur); //testing
}
int maxOccur = 0;
for(int i = 0; i < size; i++) {
if(occur[i] > maxOccur) {
maxOccur = occur[i];
}
}
//System.out.println(maxOccur); //testing
for (int i = 0; i < size && !numFound; i++) {
if(occur[i] == maxOccur) {
System.out.println(input[i]);
}
}
}
//checks if s is an in, true if it is an int
public static boolean isNumeric (String s) {
try {
Integer.parseInt(s);
return true; //parse was successful
} catch (NumberFormatException nfe) {
return false;
}
}
Found the solution!
String[] mostCommon = new String[size];
int numMostCommon = 0;
boolean numFound = false;
for (int i = 0; i < size; i++) {
int isDifferent = 0;
if (occur[i] == maxOccur) {
for (int j = 0; j < size; j++) {
if (!(input[i].equals(mostCommon[j]))) {
isDifferent = isDifferent + 1;
}
}
if (isDifferent == size) {
mostCommon[numMostCommon] = input[i];
numMostCommon = numMostCommon + 1;
}
}
}
for (int i = 0; i < numMostCommon - 1; i++) {
System.out.print("Most common: " + mostCommon[i] + ", ");
}
System.out.println(mostCommon[numMostCommon - 1]);
you could use the hash table for this to store the frequenceis as the limit is very less i.e. less than 100.
pseudo code would be like:
vector<int> hash(101)
cin>>input
if(isnumeric(input))
hash[input]++
else{
max=max_element(hash.begin(),hash.end());
for(int i=0;i<100;i++)
if(hash[i]==max)
print i
}
Set<Integer> uniqueMaxOccur = new HashSet<Integer>();
for (int i = 0; i < size ; i++) {
if(occur[i] == maxOccur) {
//System.out.println(input[i]);
uniqueMaxOccur.add(input[i]);
}
}
and display the values in the set
You can use a Set and store the values already printed.
What about something like this?
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
Map<string,int> numberLookup = new HashMap<string,int>();
Boolean doContinue = true;
while (doContinue)
{
System.out.print("Input: ");
String input = in.readLine();
if (isNumeric(input))
{
if (!numberLookup.containsKey(input))
numberLookup.put(input,1);
else
numberLookup.put(input, numberLookup.get(input) + 1);
}
else
doContinue = false;
}
maxOccur = numberLookup.values().max();
System.out.print("These numbers were all entered " + maxOccur + " times:");
Iterator it = numberLookup.entrySet().iterator();
while (it.hasNext())
{
(Map.Entry)it.next();
System.out.println(pairs.getKey());
}
}
Sorry, I'm a C# person and don't have a Java compiler on me, so this might need some tweaking.

Categories