Changing more than one Ascii number to characters - java

I have been trying to make a simple encryption program that changes a string into ascii numbers, minusing one to the value of each number, and then printing out the string by converting the ascii numbers back to letters.
I am wondering what code can be used do be able to achieve this.
for(int i= 0; i < textToEncrypt.length (); ++i) {
char c = textToEncrypt.charAt(i);
int j = (int)c - 1;
System.out.println(j);
}
so far i have been able to do the first part but not the second.
Thanks.

You don't need to use integer, just simply decrement your character.
You can write this:
for(int i= 0; i < textToEncrypt.length (); ++i) {
char c = textToEncrypt.charAt(i);
c--;
System.out.print(c);
}

You can use the following code to decript the text
Integer[] arr = new Integer[100];
for (int i = 0; i < textToEncrypt.length(); ++i) {
char c = textToEncrypt.charAt(i);
int j = (int) c - 1;
System.out.println(j);
arr[i] = j;
}
StringBuffer decriptText = new StringBuffer();
for (int i = 0; i < textToEncrypt.length(); ++i) {
decriptText.append(Character.toString((char) (arr[i] + 1)));
}
System.out.println(decriptText);

Related

How to add Alphabetical numeration? Test provided

Update: I solved it on my own. Will try to share solution later. Thanks.
Need to order a series of characters using an alphabetical list. [See test below, it is quite self-explanatory] I have problems with it because I don't know where to add the loop (I tried different options but could not find the right one).
I'm trying to add an alphabetic list, like the following one. But replacing the numbers for letters.
Name:
| Something
| Something
| Something
TEST:
expected: <1234
a|v·~·
b|╔╗═┃
c|╚·╚╗
d|·M·^>
but was: <1234
abcdefghijklmnopqrstuvwxyz|v·~·
|╔╗═┃
|╚·╚╗
|·M·^>
Code:
public String toString() {
StringBuilder response = new StringBuilder();
for(int i = 1; i <= size; i++) {
response.append("" + i);
}
response.append("\n");
for(char alphabet = 'a'; alphabet <= 'z'; alphabet++){
response.append(alphabet);
}
for(int i = 0; i < size; i++){
response.append("|");
for (int j = 0; j < size; j++){
response.append(board[i][j].getType().getUnicodeRepresentation());
}
response.append("\n");
}
return response.toString();
}
Adding another try:
TEST
expected: <1234
a|v·~·
b|╔╗═┃
c|╚·╚╗
d|·M·^>
but was: <1234
a|v·~·╔╗═┃╚·╚╗·M·^
b|v·~·╔╗═┃╚·╚╗·M·^
c|v·~·╔╗═┃╚·╚╗·M·^
d|v·~·╔╗═┃╚·╚╗·M·^>
Code:
public String toString() {
StringBuilder response = new StringBuilder();
for(int i = 1; i <= size; i++) {
response.append("" + i);
}
response.append("\n");
for(char alphabet = 'a'; alphabet <= 'd'; alphabet++){
response.append(alphabet);
response.append("|");
for (int i = 0; i < size; i++){
for (int j = 0; j < size; j++){
response.append(board[i][j].getType().getUnicodeRepresentation());
}
}
response.append("\n");
}
return response.toString();
}
Not sure I understood what you're trying to do, but you can try:
for(int i =0, char alphabet = 'a'; alphabet <= 'z'; alphabet++, i++){
response.append(alphabet);
response.append("|");
for (int j = 0; j < size; j++){
response.append(board[i][j].getType().getUnicodeRepresentation());
}
response.append("\n");
}
There might be problems with the indexing(specifically i) because you didn't provide any info about board or size or your intention in general. i will probabily be out of bounds, because something doesn't make sense. From your example it looks like size is 4, but your first loop runs all the way from a to z, so for e, which cells from board should you concat to the string?
One approach would be to index the alphabet and then assign each series of characters to the corresponding index.
The new code would be:
public String toString() {
StringBuilder response = new StringBuilder();
for(int i = 1; i <= size; i++) {
response.append("" + i);
}
response.append("\n");
String[] lines = new String[size];
for(int i = 0, char alphabet = 'a'; alphabet <= 'z' && i < size; alphabet++, i++){
lines[i] = alphabet + "";
}
for(int i = 0; i < size; i++){
lines[i] += ("|");
for (int j = 0; j < size; j++){
lines[i] += board[i][j].getType().getUnicodeRepresentation();
}
}
for(int i = 0; i < size; i++) {
response.append(lines[i]);
response.append("\n");
}
return response.toString();
}

How to print ASCII patterns in C# but using Java syntax?

Code below is for pattern a, feel like once I get a I could get the others.
I like the array[int].length syntax in Java and was helpful to get the pattern to print as shown in the picture. But I do not think such a thing exists in C#.
class Main {
public static void main(String[] args)
{
char[][] arr = new char[10][10];
int starCount = 10;
for(int i = 0; i < arr.length; i++)
{
for(int j = 0; j < starCount; j++)
{
arr[i][j] = '*';
}
for(int k = starCount; k < arr[i].length; k++)
{
arr[i][k] = '-';
}
starCount--;
}
for(int a = 0; a < arr.length; a++)
{
for(int b = 0; b < arr[a].length; b++)
{
System.out.print(arr[a][b]);
}
System.out.println();
}
}
}
This code prints the * in a decreasing fashion but I am struggling with how to replace the empty elements of the array with the - character as shown in the image.
class MainClass {
public static void Main (string[] args)
{
char[ , ] arr = new char[10,10];
int starCount = 10;
for(int i = 0; i < arr.Length; i++)
{
for (int j = 0; j < starCount; j++)
{
arr[i , j] = '*';
}
for (int k = 0; ) //IDK WHAT TO DO TO ASSIGN ARR[I , K] = '-';
starCount--;
}
for (int i = 0; i < 10; i++)
{
for (int j = 0; j < 10; j++)
{
Console.Write(arr[i , j]);
}
Console.WriteLine();
}
}
}
You can use two nested for loops and one if else statement to print all of these patterns. This is Java code, but I think it can be easily converted to C#:
int n = 5;
for (int i = -n; i <= n; i++) {
for (int j = -n; j <= n; j++) {
// a) if (i + j <= 0)
// b) if (i + j >= 0)
// c) if (i <= j)
// d) if (Math.abs(i) + Math.abs(j) <= n)
if (i + j <= 0)
System.out.print("*");
else
System.out.print("-");
}
System.out.println();
}
Output (combined):
a) b) c) d)
*********** ----------* *********** -----*-----
**********- ---------** -********** ----***----
*********-- --------*** --********* ---*****---
********--- -------**** ---******** --*******--
*******---- ------***** ----******* -*********-
******----- -----****** -----****** ***********
*****------ ----******* ------***** -*********-
****------- ---******** -------**** --*******--
***-------- --********* --------*** ---*****---
**--------- -********** ---------** ----***----
*---------- *********** ----------* -----*-----
See also: Output an ASCII diamond shape using loops
Here's a different approach to the original problem, which might be easier for you to convert.
Build a string of 10 stars and 9 dashes, e.g. hard-coded that would be:
String line = "**********---------";
Now print a 10 rows with substrings of that string:
for (int i = 0; i < 10; i++)
System.out.println(line.substring(i, i + 10));
Output
**********
*********-
********--
*******---
******----
*****-----
****------
***-------
**--------
*---------
If the size is dynamic, based on an int value in variable starCount, then in Java 11+ you can use the repeat() method:
String line = "*".repeat(starCount) + "-".repeat(starCount - 1);
for (int i = 0; i < starCount; i++)
System.out.println(line.substring(i, i + starCount));
That one should be easy to do in C#. See: Best way to repeat a character in C#.
In versions of Java below 11, you can build a char[]:
char[] line = new char[2 * starCount - 1];
Arrays.fill(line, 0, starCount, '*');
Arrays.fill(line, starCount, line.length, '-');
for (int i = 0; i < starCount; i++)
System.out.println(new String(line, i, starCount));
The easiest way would be to look at the C# documentation for the Array class. There you would find that the Array class has a GetLength() method, that returns what the length property of a Java array returns.
Using that method you can change your code to
class MainClass {
public static void Main (string[] args)
{
char[ , ] arr = new char[10,10];
int starCount = 10;
for(int i = 0; i < arr.GetLength(0); i++)
{
for (int j = 0; j < starCount; j++)
{
arr[i , j] = '*';
}
for (int k = starCount; k < arr.GetLength(1); k++)
{
arr[i , k] = '*';
}
starCount--;
}
for (int i = 0; i < arr.GetLength(0); i++)
{
for (int j = 0; j < arr.GetLength(1); j++)
{
Console.Write(arr[i , j]);
}
Console.WriteLine();
}
}
}
For some reason when you switched from java to C# you went from using jagged arrays:
//java
char[][] arr = new char[10][10];
To rectangular arrays:
//c#
char[ , ] arr = new char[10,10];
This undoubtedly makes your life more hard work because it means a lot more has to change. C# supports jagged arrays in exactly the same way Java does, and in fact if I hadn't written "//java" above you wouldn't have been able to tell whether it was C# or java because they're the same
I like the array[int].length syntax in Java ... But I do not think such a thing exists in C#.
It absolutely does, and you need to change just one single character to get it: properties in C# are named in Pascal case, so you want Length, not length
In fact, the logic of that entire block of java you have will work just fine in C# - just paste it in and change the following minor changes:
length -> Length
System.out.print -> Console.Write
System.out.println -> Console.WriteLine

How to make two char rows alternate in order to make a rectangle JAVA

My code takes 2 input numbers to create the rows and columns of a rectangle. In that rectangle, the user chooses 2 letters for the rectangle body but they have to alternate, like this: (without the dashes ofc)
-xxxxx
-r r r r r
-xxxxx
-r r r r r
Whenever I try to make them alternate, the rows usually end up like "xrxrx" or "xrrrr" instead of a single letter. I've tried adding them "filler.append(firstLetter + secLetter);" but it just results in numbers. This probably has a really easy solution but I just don't see it ha ha...(・_・;) Any hints would be greatly appreciated, thank you!
public static void recDraw ( int rows, int columns, char firstLetter, char secLetter){
StringBuilder filler = new StringBuilder();
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
filler.append(firstLetter);
filler.append(secLetter);
}
filler.append('\n');
}
System.out.println(filler);
}
Inside inner loop (with counter j), before appending the letter to StringBuilder filler, check whether it is Fistletter line or SecondLetter line by using modulus operation on i value. 'i' value is used because it represents the line/row.
public static void recDraw ( int rows, int columns, char firstLetter, char secLetter){
StringBuilder filler = new StringBuilder();
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
if(i%2 == 0){
filler.append(firstLetter);
} else{
filler.append(secLetter);
}
}
filler.append('\n');
}
System.out.println(filler);
}
Try printing the value of i and j, you will get where you are getting wrong.
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
filler.append(firstLetter);
filler.append(secLetter);
}
filler.append('\n');
}
In your above code snippet add a check if
i is even, then add firstLetter
i is odd, then add secondLetter
public static void rectDraw(String ch1, String ch2, int cols, int rows) {
String rect = "";
for (int i = 0; i < rows; i++) {
String line = "";
for (int j = 0; j < cols; j++) {
if (i % 2 == 0) {
line += ch1;
}
else {
line += ch2;
}
}
rect += line + "\n";
}
System.out.println(rect);
}
This solves your problem. You will want to look into the modulus operator for more information about why this works. You can take a look here.

Java save alphabet to array

I try save alphabet A-Z to my array, but I don't understand, why I get only this output: Z.
public class Main {
public static void main(String[] args) {
char []tab = new char[25];
for (int i = 0; i<25; i++) {
for (int j=65; j<91; j++) {
tab[i] = (char)j;
}
}
for (int i=0; i<25; i++) {
System.out.println(tab[i]);
}
}
}
Your algorithm is wrong.
Check this simpler solution:
public static void main(String[] args)
{
char []tab = new char[25];
for (int i = 0; i<25; i++) {
tab[i] = (char)(i+65);
}
for (int i=0; i<25; i++) {
System.out.println(tab[i]);
}
}
Your code puts all the letters from A to Z in each slot of the tab array, when executing the 'j' loop, that's why you have only Zs.
You don't need nested loop, try this:
char[] tab = new char[26];
for (int i = 0, j = 65; j < 91; j++, i++) {
tab[i] = (char) j;
}
for (int i = 0; i < 26; i++) {
System.out.println(tab[i]);
}
Also, array size should be 26 not 25.
Lets see how your code works:
for (int i = 0; i<25; i++) { //1
for (int j=65; j<91; j++) { //2
tab[i] = (char)j; //3
} //4
} //5
1) Outer loop sets i=0,
2) Inner loop sets j=65
3) (char)65 represents 'A' ant is placed in tab[0]
2) Inner loop sets j=66
3) (char)66 represents 'B' and is also placed in tab[0]
Here you should notice the problem, which is that inner loop is working on same i, so while iterating over A...Z it is modifying same array location, which means that location will hold last value placed there, which is 'Z'.
(BTW i<25 should be i<26)
Possible solution
don't use inner loop, you can calculate value which should be placed at index by adding i to 65 which in Unicode Table is codepoint of 'A'
for (int i=0; i<26; i++)
tab[i] = (char)(65+i);
BTW you can farther improve readability of this code by avoiding magic numbers (more info: What is a magic number, and why is it bad?). So this code can be rewritten into something like:
int amountOfLetters = 'Z' - 'A' + 1;
char[] tab = new char[amountOfLetters];
int i = 0;
for (char ch = 'A'; ch <= 'Z'; ch++) {
tab[i++] = ch;
}
System.out.println(new String(tab));

Converting 1-D String array to 2-D char array

I'm working on a program that requires me to take in a 1-D String array from a file and turn it into a 2-D array. Taking in the array from the file works fine, but I can't get the second part to work.
The code I'm working with is:
char[][] array2 = new char [7][5];
for (int i = 0; i < array1.length; i++)
{
array2[i]= array[i].toCharArray();
}
for (int i = 0; i < 5; i++)
{
for (int j = 0; j < 7; j++)
{
System.out.println(array2[i][j]);
}
}
The array is supposed to print in a grid format, but is printing downward.
Any help is appreciated, thanks.
Use print instead of println in inner loop and after each loop print a blank line with println.
for (int i = 0; i < 7; i++) // see changes 5/7. You did "new char[7][5]" not [5][7]
{
for (int j = 0; j < 5; j++) // see changes 7/5
{
System.out.print(array2[i][j]);
}
System.out.println();
}
Update:
Following is a program that convert String array to 2D char array.
public class StringToChar {
public static void main(String[] args) {
String[] strArr = { "HELLO", "WORLD" };
char[][] char2D = new char[strArr.length][];
for (int i = 0; i < strArr.length; i++) {
char2D[i] = strArr[i].toCharArray();
}
for (char[] char1D : char2D) {
for (char c : char1D)
System.out.print(c + " ");
System.out.println();
}
}
}
few suggestions,
replace char[][] array2 = new char [7][5]; with char[][] array2 = new char [array1.length][]; (where array1 holds your strings), so your 2d array will have as many rows as you have strings
your loop
for (int i = 0; i < 5; i++)
{
for (int j = 0; j < 7; j++)
....
}
change to
for (int i = 0; i < array2.length; i++)
{
for (int j = 0; j < array2[i].length; j++)
....
another thing is if you want your string printed in rows, use System.out.print, and whenever you finished inner loop, print out'\n' character
You are using println, which is why each character is printed on its own line. You must use print instead.
Note that your initialization with
new char [7][5];
doesn't work as you expect because the inner arrays will be overwritten. Use
new char[7][]
for the same result, but more clarity as to your intent. Here
for (int i = 0; i < 5; i++)
for (int j = 0; j < 7; j++)
you have apparently reversed the order of indices: you are iterating only through 5 outer arrays, but you have allocated 7. What you should do instead is check against the actual array length and not a hardcoded number. The inner array may be of any size, after all (it depends on the string length).
Have a look at the String.toCharArray()
If it is printing downwards then change
for (int i = 0; i < 7; i++) //row loop
{
for (int j = 0; j < 5; j++) //column loop
{
System.out.print(array2[i][j]);
}
System.out.println(); //add here
}
Have a look at
formatting
print vs println

Categories