Populating Multidimensional Arrays in Java - java

So I am trying to populate a 2D array from two strings, as seen below.
However, when I go to compile my code, I get a
"java: incompatible types: char[] cannot be converted to char"
error. What am I doing wrong?
public static void main(String[] args) {
String alphabet = ("ABCDEFGHIJKLMNOPQRSTUVWXYZ");
String iAlphabet = ("ZYXWVUTSRQPONMLKJIHGFEDCBA");
char alphabetArray [][] = {{alphabet.toCharArray()},{iAlphabet.toCharArray()}};
System.out.print(alphabetArray[4][4]);
}
}
(New to Java, and am just bashing my head against a wall on this one)

I guess you want to be able to translate the character from one string to the other one at the same position:
public static void main(String[] args) {
String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
String iAlphabet = "ZYXWVUTSRQPONMLKJIHGFEDCBA";
char alphabetArray [][] = {alphabet.toCharArray(),iAlphabet.toCharArray()};
System.out.print("3rd character: " + alphabetArray[0][2] + " -> " + alphabetArray[1][2]);
}
This prints:
3rd character: C -> X
An example of ussage as translate would be:
public static void main(String[] args) {
String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
String iAlphabet = "ZYXWVUTSRQPONMLKJIHGFEDCBA";
char alphabetArray [][] = {alphabet.toCharArray(),iAlphabet.toCharArray()};
String test = "HELLO WORLD";
StringBuffer translated = new StringBuffer();
for (int i = 0; i < test.length(); i++) {
int index = alphabet.indexOf(test.charAt(i));
if (index > 0) {
translated.append(alphabetArray[1][index]);
} else {
translated.append(test.charAt(i));
}
}
System.out.println("original sentence: " + test);
System.out.println("translated sentence: " + translated.toString());
}
which prints:
original sentence: HELLO WORLD
translated sentence: SVOOL DLIOW

Declare the arrays as shown below. And remember it's not a 26 x 26 array. It is a 2 x 26 array.
String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
String iAlphabet = "ZYXWVUTSRQPONMLKJIHGFEDCBA";
char alphabetArray [][] = {alphabet.toCharArray(),iAlphabet.toCharArray()};
Print V from the second.
System.out.print(alphabetArray[1][4]);
Print E from the first.
System.out.print(alphabetArray[0][4]);

You are putting an array of char where you need to place the only char. So remove the curly braces and simply put an array of char
Your Code should be like this
public static void main(String[] args) {
String alphabet = ("ABCDEFGHIJKLMNOPQRSTUVWXYZ");
String iAlphabet = ("ZYXWVUTSRQPONMLKJIHGFEDCBA");
char[] charArray = alphabet.toCharArray();
char[] charArray2 = iAlphabet.toCharArray();
char alphabetArray[][] = { charArray, charArray2 };
System.out.println(alphabetArray[0][23]);
}

you could also take advantage of the fact that the letters 'A'-'Z' are in order
for example: if you want to translate a number to a letter in the alphabet you can just say
char a = 'A';
a+=num;
or if you want it to go backwards
char a = 'Z';
a-=num;
num being the equivelent index you would've given.
this is assuming that you want to make the array read-only of course, and some sort of validation before performing these operations would be recommended. (Verifying the number is positive and less than 26)
if this works in your case, then that's great.

If you want to do a ceaser cipher: IE translate any character by any offset, you can do the following:
private static char offsetChar(char chr, int offset){
chr = Character.toUpperCase(chr);
//value from 0-25 representing letter
int val = chr - 'A';
//make sure that the offset doesn't make it overflow past 26
val = (val + offset) % 26;
// convert back to letter from number 0-25
return (char)('A' + val);
}
also note that this will auto-capitalize the letter, if you don't want that to happen you can test if it is uppercase and return it in the correct state at the end using
Character.isUpperCase and Character.toUpperCase and Character.toLowerCase

Related

How do I convert an alphabetic string to int and do arithmetic on it?

Everywhere I look trying to find out how to convert a String to an int, the examples use a numeric string, i.e. they show how to change "123" into 123. That is not at all what I am trying to do. My string is alphabetic. I know this because the two previous methods required me, first, to check whether it contained uppercase characters, and then, convert it to all uppercase characters. I succeeded in doing both of these. Now the third method calls for converting it to an int, and performing an arithmetic function on it, and now I am stuck. I tried using .valueOf(), that is, the ascii numeric values of the characters, but it keeps throwing errors.
public class ChangeCase {
String stringToCheck;
public int convertToIntPlusTen() {
// Create new field for the converted string
String asciiValue = "";
// Break original string down to char array
final char[] chars = stringToCheck.toCharArray();
// Find the ascii value of each character and add it to the new field
for (int i = 0; i < chars.length; i++) {
asciiValue += String.valueOf((int) chars[i]);
}
// Convert string of numeric characters to int
int asciiInt = Integer.parseInt(asciiValue);
// Add ten to the resulting int
asciiInt += asciiInt + 10;
StringBuilder sbf
= new StringBuilder("");
sbf.append(asciiInt);
return asciiInt;
}
}
public class AppDriver {
public static void main(String[] args) {
ChangeCase changeCase = new ChangeCase();
changeCase.stringToCheck = "Foxes";
changeCase.convertToIntPlusTen();
}
}
Now since the ascii values of the characters are 'F' = 070, 'o' = 111, 'x' = 120, 'e' = 101, and 's' = 115, then I expected it to produce the numeric string "070111120101115," which would then become the int 070111120101115. Adding ten would make it 070111120101125, which is the expected output.
Instead I get:
Exception in thread "main" java.lang.NumberFormatException: For input string: "70111120101115"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:583)
at java.lang.Integer.parseInt(Integer.java:615)
at mainpackage.SubChangeCase.convertToIntPlusTen(SubChangeCase.java:45)
at mainpackage.AppDriver.main(AppDriver.java:133)
I'm thinking that maybe this is more of a logical error than an operational one, i.e. I may have approached the problem incorrectly in the first place. Because I see my stack trace does have the expected input string. Unfortunately, since almost every code example out there in internet world is about converting numeric strings, I have not found anything to help with this.
70111120101115 is too big for an integer. You have to store it in a long
You also made a typo - you instantiated the wrong class. It's ChangeCase, not SubChangeCase
Therefore, your class should be:
public long convertToIntPlusTen() {
// Create new field for the converted string
String asciiValue = "";
// Break original string down to char array
final char[] chars = stringToCheck.toCharArray();
// Find the ascii value of each character and add it to the new field
for (int i = 0; i < chars.length; i++) {
asciiValue += String.valueOf((int) chars[i]);
}
// Convert string of numeric characters to int
long asciiInt = Long.parseLong(asciiValue);
asciiInt += asciiInt + 10;
StringBuilder sbf
= new StringBuilder("");
sbf.append(asciiInt);
return asciiInt;
}
So your final code should be:
public class ChangeCase {
String stringToCheck;
public long convertToIntPlusTen() {
// Create new field for the converted string
String asciiValue = "";
// Break original string down to char array
final char[] chars = stringToCheck.toCharArray();
// Find the ascii value of each character and add it to the new field
for (int i = 0; i < chars.length; i++) {
asciiValue += String.valueOf((int) chars[i]);
}
// Convert string of numeric characters to int
long asciiInt = Long.parseLong(asciiValue);
asciiInt += asciiInt + 10;
StringBuilder sbf
= new StringBuilder("");
sbf.append(asciiInt);
return asciiInt;
}
}
public class AppDriver {
public static void main(String[] args) {
ChangeCase changeCase = new ChangeCase();
changeCase.stringToCheck = "Foxes";
changeCase.convertToIntPlusTen();
}
}

java program that takes a word and randomizes the letters and creates an anagram

I need to create a program that will take a word without spaces, punctuation, and all lowercase, and rearranges the letters randomly. It needs to have substrings or charAt, I cannot use an array since we have not learned them yet. It also hsa to be different everytime, really n! times I think. This is what I have so far-
public static void main(String[] args) {
Scanner kboard = new Scanner(System.in);
System.out.println("Enter a word that is less than 11 lowercase letters and has no punctuation or spaces: ");
String word = kboard.next();
while(word.length()>1)
{
System.out.print(word.charAt(1));
System.out.print(word.charAt(0));
word = word.substring(2);
}
System.out.println(word);
}
This rearranges the words, but it does not do it random every time. I thought I could do something like this, but I think it is messy and doesn't make much sense.
public static void main(String[] args) {
Scanner kboard = new Scanner(System.in);
String word, pt1 = "", pt2 = "", pt3 = "";
System.out.println("Enter a word that is less than 11 lowercase letters and has no punctuation or spaces: ");
word = kboard.nextLine();
int num1 = 0, num2 = 0, thing = 0;
while(thing<4)
{
thing = thing + 1;
num1 = (int)(word.length() * Math.random() + 1);
num2 = (word.length() - (word.length() % num1));
}
pt1 = word.substring(num1, num2);
pt2 = word.substring(num1, num2);
pt3 = word.substring(num1, num2);
System.out.print(pt1);
System.out.print(pt2);
System.out.print(pt3);
So what can I do to randomize the letters?
A simple solution to all "how do I randomize" a fixed set of elements is: shuffling.
Simply turn your String into a List of Character, to then shuffle that list.
( creating that list boils down to new ArrayList<>(yourWord.toCharArray() ).
GhostCat beat me in a few seconds :)
char[] arr = "abcdefg".toCharArray();
List<Character> list = new LinkedList<>(); // copy the chars to a list
for (int i = 0; i < arr.length; i++) {
list.add(arr[i]);
}
Collections.shuffle(list); // use to shuffle
for (int i = 0; i < arr.length; i++) { // copy the shuffled chars back to the array
arr[i] = list.get(i);
}
System.out.println(new String(arr));
This could be implemented very easily using standard libraries,
but it seems you cannot use arrays and lists,
which makes this exercise a bit harder than it needs to be.
You can implement the following algorithm:
Initialize the output as an empty string
while the word is not empty
Pick a character randomly
Append the character to the output
Remove the selected character from the word, by replacing word with the part before the index + the part after the index
This can be implemented reasonably efficiently using a StringBuilder:
String shuffled(Random random, String word) {
StringBuilder result = new StringBuilder(word.length());
StringBuilder rest = new StringBuilder(word);
while (rest.length() > 0) {
int index = random.nextInt(rest.length());
result.append(rest.charAt(index));
rest.deleteCharAt(index);
}
return result.toString();
}
If you cannot use a StringBuilder,
then you can work with strings,
but this will be less efficient,
and normally not recommended in Java.
(Because it involves many string concatenations, which is inefficient.)
String shuffled(Random random, String word) {
String result = "";
String rest = word;
while (!rest.isEmpty()) {
int index = random.nextInt(rest.length());
result += rest.charAt(index);
rest = rest.substring(0, index) + rest.substring(index + 1);
}
return result;
}
You can call this with:
String shuffled = shuffled(new Random(), word);
What about this :
public static void main(String[] args) {
String test = "onetwothree";
Random random = new Random();
for (int i=0;i<test.length();i++){
int randomCharacterPosition = random.nextInt(test.length());
String start = test.substring(0,randomCharacterPosition);
String end = test.substring(randomCharacterPosition);
test = end.concat(start);
}
System.out.println(test);
}
Basically you getting a string, randomly choose a position in string.
Using this position you dividing input string into two strings and swaping them.
Nothing more than random, substring and concat (which can be replaced with + operator)

Binary String to ASCII 6bit char in Java

I have a long String with 48bit in Java. This string will be divided into 8 strings with a length of 6bit. Every string should be converted to an ASCII char. Therefore the Sixbit ASCII Code should be used.
Now I have a table with all the possible chars and the binary code for it. My first idea was to convert the binary string to the char by using a switch case and define a rule for every possibility, but this can't be the best option.
Is there some kind of a function, which I can use to convert this automatically and that I don't have to write a method with the switch?
public byte sixBitFromAscii(char asciiChar) {
if (asciiChar >= 0x60) {
System.out.println("Invalid character " + asciiChar);
return 0;
}
else {
return (byte)(asciiChar - 0x20);
}
}
public char asciiFromSixBit(byte sixBit) {
return (char) (sixBit + 0x20);
}
Ok, thanks to the clarification, and your posting the actual table, this becomes really simple. With the charset sorted, we can just convert directory and index into the array. Keep in mind, if you input was a String of 0/1s, you'd have to do some bit twiddling to get value (named n in this code). Otherwise, it would be the same.
public class sixbit {
static final char[] CHARSET =
{'#','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','[','\\',']','^',
'_',' ','!','"','#','$','%','&','\'','(',')','*','+',',','-',
'.','/','0','1','2','3','4','5','6','7','8','9',':',';','<',
'=','>','?'};
public static void main(String[] args) {
// Sample String of length 48, maybe up of 1s and 0s
String input = "010011010100000001000011001011001111010110010010" ;
System.out.println(input);
String[] parts = splitInput(input); // Split into 6-bit pieces
for(String sixbit: parts) {
int n = Integer.parseUnsignedInt(sixbit, 2);
System.out.printf("%s -> %c \n", sixbit,CHARSET[n]);
}
}
private static String[] splitInput(String input) {
String[] parts = new String[8]; // 48 bits, 6 bits each means we get 8 characters;
int current_part = 0;
int current_bit = 0;
StringBuilder sb;
while(current_bit < 48) {
sb = new StringBuilder();
for(int i=0; i < 6; i++) {
sb.append(input.charAt(current_bit));
current_bit++;
}
parts[current_part] = sb.toString();
current_part++;
}
return parts;
}
}
old version
Other than the loadLookupTable() method only including some randomly tossed together entries your table, this should do what you want.
import java.util.*;
public class sixbit {
static Map<String,Character> lookup = new HashMap<String,Character>();
public static void main(String[] args) {
loadLookupTable();
// Sample String of length 48, maybe up of 1s and 0s
String input = "111000111001100110101000110000110100111011110111" ;
System.out.println(input);
String[] parts = splitInput(input); // Split into 6-bit pieces
for(String sixbit: parts) {
char ch = lookup.get(sixbit); // Lookup each 6-bit String to get the corresponding character.
System.out.printf("%s -> %c \n", sixbit, ch);
}
}
private static String[] splitInput(String input) {
String[] parts = new String[8]; // 48 bits, 6 bits each means we get 8 characters;
int current_part = 0;
int current_bit = 0;
StringBuilder sb;
while(current_bit < 48) {
sb = new StringBuilder();
for(int i=0; i < 6; i++) {
sb.append(input.charAt(current_bit));
current_bit++;
}
parts[current_part] = sb.toString();
current_part++;
}
return parts;
}
private static void loadLookupTable() {
/* For each bit string you have in your table, add the corresponding character. It would be shorter code,
* and a touch faster to load this from an array, but it would take a bit of thought and wouldn't be as clear.
* Grab enough to work for this example, so that this program works. Just need to make sure the full lookup is loaded
* properly.
*/
lookup.put("100110", 'a');
lookup.put("100111", 'b');
lookup.put("101000", 'c');
lookup.put("110000", 'k');
lookup.put("110100", 'o');
lookup.put("110111", 'r');
lookup.put("111000", 's');
lookup.put("111001", 't');
// and so on...
lookup.put("111011", 'v');
lookup.put("111100", 'w');
lookup.put("111101", 'x');
lookup.put("111110", 'y');
lookup.put("111111", 'z');
}
}
Break the String into bytes (6-bits each with 2 bits of padding). Then just use an array mapping the byte values to the ASCII char value.
edit Ok, I misunderstood your question as you having raw binary data. Apparent you have a String of 1s and 0s, like "1010111" of length 48. The actual implementation is very different (and a lot easier). See my other answer. Sorry for the confusion.

Hex to Binary String Java

I'm making Encryption now, and on the step 7 which i need to make the HEX String Array(which I have transferred from ASCII into a String Array) into Binary String.
public static void main(String[] args) {
System.out.println("HEX to Binary: ");
String[] stringHextoBinary = new String[HS.length]; //HS is the String Array for Hex numbers that i save from last step
StringBuilder builder = new StringBuilder();
int l = 0;
for(String s : HS) {
builder.append(s);
if (s.length()<=1){
stringHextoBinary[l] = HexToBinary(s.charAt(0));
l++;
System.out.print(HexToBinary(s.charAt(0)) + ",");
}else{
stringHextoBinary[l] = HexToBinary(s.charAt(0))+HexToBinary(s.charAt(1));
l++;
System.out.print(HexToBinary(s.charAt(0))+HexToBinary(s.charAt(1))+",");
}
public static String HexToBinary(char Hex) {
int i = Integer.parseInt(Character.toString(Hex), 16);
String Bin = Integer.toBinaryString(i);
return Bin;
}
}
the if statement can be work with HEX when it has one digit or two digits.
But my problem is here that it prints out
HEX to Binary:
11100,111,111,10111,11101,
its losing 0 in it. :(
so that when i encrypt word "apple" , and decrypt it with same code will come back with word "pppxl" :(
Hope I can get answer ASAP and thanks a lot!
Use this method of the Apache commons StringUtils class
public String leftPad(String str, int size, char padding);
after you've converted your number to 0s and 1s. It might look like
String paddedBin = StringUtils.leftPad(bin, 8, '0');
for example. Not sure how many digits you actually want to pad it to.
Instead of your method taking in chars, you can simply have it take in a string and convert it to binary using:
public static void main(String[] args) {
System.out.println("HEX to Binary: ");
String[] stringHextoBinary = new String[HS.length]; //HS is the String Array for Hex numbers that i save from last step
// creates the string builder, count, and declaration
StringBuilder builder = new StringBuilder();
int l = 0;
string binaryDigits;
// iterates through string array and appends to string that's being built
// (for whatever reason)
for(String s : HS) {
builder.append(s);
binaryDigits = HexToBinary(s);
stringHextoBinary[l++] = binaryDigits;
System.out.print(binaryDigits);
}
// transforms hex string to binary string without losing 0's
public static String HexToBinary(String Hex) {
string toReturn = new BigInteger(Hex, 16).toString(2);
return String.format("%" + (Hex.length*4) + "s", toReturn).replace(' ', '0')
}
You don't need to combine code, as this is all the code that you need to convert a string to a binary string separated by spaces. It will iterate through and change every string to a binary string.
Try this method implementation:
public static String hexCharToBinary(char c) {
final int v;
if (c >= '0' && c <= '9') {
v = c - '0';
} else if (c >= 'A' && c <= 'F') {
v = 10 + c - 'A';
} else if (c >= 'a' && c <= 'f') {
v = 10 + c - 'a';
} else {
throw new IllegalArgumentException();
}
return String.format("%4s", Integer.toBinaryString(v & 0xFF)).replace(' ', '0');
}
Try this out:
stringHextoBinary[l] = new BigInteger(s,16).toString(2);
What this is doing is creating a new Integer with radix of 16 for you hex numbers and then converting that to a string of base 2 (binary). Haven't tested this out since I am not near a computer with a jvm installed but this is just an idea since you seem to need ideas in a hurry.
This should work too:
stringHextoBinary[l] = Integer.toBinaryString(Integer.parseInt(s, 16));

Replace content of one string with another?

How could I replace the letters in a String such as "Hello", with the letters here?
String bubbled = "ⓐⓑⓒⓓⓔⓕⓖⓗⓘⓙⓚⓛⓜⓝⓞⓟⓠⓡⓢⓣⓤⓥⓦⓧⓨⓩⒶⒷⒸⒹⒺⒻⒼⒽⒾⒿⓀⓁⓂⓃⓄⓅⓆⓇⓈⓉⓊⓋⓌⓍⓎⓏ";
I was initially just doing a replaceAll ("a","ⓐ"), but I feel like there has to be a more efficient way of doing this.
Split bubbled into lowercase and uppercase. Make a new StringBuilder, iterate over each char of source, and if chr >= 'a' && chr <= 'z' append lowercaseBubbled[chr - 'a'], if it's in uppercase range do similar, else just append chr. At the end, use toString on the builder.
Or you could use a slightly less efficient method, replaceChars (since it has to use indexOf) found in Apache Commons. Pro: it's a library, so no extra work for you.
You could use the characters a and ⓐ to determine the offset values for the alphabet. In combination with a StringBuilder it should be rather efficient. Of course you would likely have to be very strict about the input string being only alphabet characters.
This is the code for what I described above:
public class Bubbled {
public static void main(String[] args) {
char bubbledA = 'ⓐ';
int lowerCaseOffset = bubbledA - 'a';
int upperCaseOffset = bubbledA - 'A';
String input = "Hello";
StringBuilder bubbledOutput = new StringBuilder();
for (Character c : input.toCharArray()) {
if (Character.isUpperCase(c)) {
bubbledOutput.append((char)(c + upperCaseOffset));
} else {
bubbledOutput.append((char)(c + lowerCaseOffset));
}
}
System.out.println(bubbledOutput.toString());
}
}
Output
ⓗⓔⓛⓛⓞ
Here is a code snipp that does it. It wont create a zillion String objects. I have only a smaller set of bubble chars just for demo purpose. Please tweak to your liking and no error handling has been done.
public class StackOverFlow {
private static int[] bubbled = {'ⓐ', 'ⓑ', 'ⓒ', 'ⓓ', 'ⓔ'};
private static int [] plain = {'a', 'b', 'c', 'd', 'e'};
private static Map<Integer, Integer> charMap = new HashMap<>();
public static void main(String[] args) {
String test = "adcbbceead";
for(int i=0; i<plain.length; i++) {
charMap.put(plain[i], bubbled[i]);
}
replaceWithBuffer(test);
}
private static void replaceWithBuffer(String test) {
System.out.println("Oginal String = " + test);
StringBuilder sb = new StringBuilder(test);
for(int i =0; i<test.length(); i++) {
int ch = sb.charAt(i);
char buubledChar = (char)charMap.get(ch).intValue();
sb.setCharAt(i, buubledChar);
}
System.out.println("New String = " + sb.toString());
}
}
Output:
Hope this helps :)
Use a for loop:
for (char i='a';i<'z';i++)
str = str.replaceAll(i,bubbled[i-'a']);
for (char i='A';i<'Z';i++)
str = str.replaceAll(i,bubbled[i-'A'+26]);
Of course, this wouldn't be too efficient, since Strings are immutable.

Categories

Resources