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));
Related
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
I'm having difficulty figuring out the code to print a two dimensional array in grid format.
public class TwoDim {
public static void main (String[] args) {
int[][] ExampleArray = new int [3][2];
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 2; j++)
{
ExampleArray[i][j] = i * j;
System.out.println(j);
}
System.out.println(i);
}
}
}
System.out.println(s) prints s, then prints a line return character. So if you want multiple print calls to end up on the same line, you should use System.out.print(s) instead.
Additionally, you can use System.out.println() (with no argument) to print nothing, but move to the next line. Bringing all of that together:
public class TwoDim {
public static void main (String[] args) {
int[][] ExampleArray = new int [3][2];
for (int i = 0; i < 3; i++){
for (int j = 0; j < 2; j++){
ExampleArray[i][j] = i * j;
System.out.print(j + " ");
}
System.out.println();
}
}
}
When you use System.out.println(...);, it prints a newline char ('\n') after the string you intended to print. This should only happen if your line is over (i.e., outside the innest for statement). So, your for loops should be:
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 2; j++)
{
ExampleArray[i][j] = i * j;
System.out.print(ExampleArray[i][j] + ' '); //You can replace ' ' by '\t', if
//you want a tab instead of a space
}
System.out.println("");
}
Hope that helps.
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);
I have searched everywhere and I cannot figure out how to create this output using a nested for loop in java:
"a
ab
abc
abcd"
continued until z
this is what I have tried
String alphabet = "abcdefghijklmnopqrstuvwxyz";
for(int i = 0; i <= 25; i++)
{
for(char j = (char)(alphabet.charAt(i)); j<=i; j++)
{
System.out.print(j);
}
System.out.println();
}
Please help me!
Here is the answer:
for (int x = 'a'; x <= 'z'; x++) { /* Loop from 'a' to 'z' */
for (int i = 'a'; i<=x; i++){ /* Loop from 'a' to int x */
System.out.print((char)i);
}
System.out.println(); /* New Line */
}
The outer loop switches from one row to another while the inner loop prints the characters ('a' to x)for that particular row.
Here you go !
print capital Alphabet
public class Main
{
public static void main(String[] args)
{
int i, j;
for(i = 1; i<=26; i++) {
for(j = 1; j <= 1-i; j++) {
System.out.print(" ");
for(j = 1; j <= i; j++)
System.out.print((char)(char)(i+64)+" ");
System.out.println(); //for line break
}
}
}
here you go!!
class nested_loop {
void display () {
char i,j;//i loop controls number of lines and j controls number of times in each line
for(i='A';i<='E';i++) {
{
for(j='A';j<='E';j++) {
System.out.print(j);
}
System.out.println();//blank print statement takes control to the next line
}
}
}
}
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