I need the pattern to be printed in the form
ABCDEF FEDCBA
ABCDE EDCBA
ABCD DCBA
ABC CBA
AB BA
A A
Below is my code :
public static void main(String args[])
{
char[] c = {'A','B','C','D','E','F','G'};
int i, j;
for(j = 5; j >= 0; j--)
{
for(int k = 0; k <= j; k++)
{
System.out.print(c[k]);
}
for(i = j; i >= 0; i--)
{
System.out.print(c[i]);
}
System.out.println();
}
}
Which gives me the output as
ABCDEFFEDCBA
ABCDEEDCBA
ABCDDCBA
ABCCBA
ABBA
AA
It was fairly easy to reach to this output. However, i haven't been able to provide spaces. I know the loop to produce the space will come in between both the for loops but i couldn't figure out how to do it. Its bugging me for a while.
I give you hint, count the spaces :
For line 1 : 1 spaces
For line 2 : 3 spaces
For line 3 : 5 spaces
For line 4 : 7 spaces
etc., see the pattern? :)
And yes, put one more "space for cycle" between existing for cycles.
Spoiler ALERT, here is Java solution, but try to do it without it.
This is fully working code, it also works with any size of array :
public static void main(String args[]) {
char[] c = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'Y', 'Z'};
int i, j;
for (j = c.length-1; j >= 0; j--) {
for (int k = 0; k <= j; k++) {
System.out.print(c[k]);
}
for (int k = 0; k < (c.length-j)*2 - 1; k++) {
System.out.print(" ");
}
for (i = j; i >= 0; i--) {
System.out.print(c[i]);
}
System.out.println();
}
}
Sample output :
ABCDEFGYZ ZYGFEDCBA
ABCDEFGY YGFEDCBA
ABCDEFG GFEDCBA
ABCDEF FEDCBA
ABCDE EDCBA
ABCD DCBA
ABC CBA
AB BA
A A
char[] c = {'A','B','C','D','E','F','G'};
int i, j,n,p=1;
for(j = 5; j >= 0; j--)
{
for(int k = 0; k <= j; k++)
{
System.out.print(c[k]);
}
for(n = 1; n <= p; n++)
System.out.print(" ");
p+=2;
for(i = j; i >= 0; i--)
{
System.out.print(c[i]);
}
System.out.println();
}
Even though there are some (already) answered solutions, too many loops increase the complexity:
char[] c = { 'A', 'B', 'C', 'D', 'E', 'F', 'G' };
for (int i = 0; i < c.length; i++) {
String tmp = String.valueOf(c).substring(0, c.length - i);
System.out.printf("%s %" + (c.length + i) + "s%n", tmp, new StringBuilder(tmp).reverse());
}
OUTPUT
ABCDEFG GFEDCBA
ABCDEF FEDCBA
ABCDE EDCBA
ABCD DCBA
ABC CBA
AB BA
A A
Your char array can be increased any time, the output would be "the same" (in terms of formatting).
Each row of your pattern is of fixed width: 13 characters. That means that if you print j characters (index of your outer loop), you need to print 13-2*j spaces.
for (int k=0; k<13-2*j; k++){
System.out.print(" ");
}
Here I use a new variable max to set up j initially. This variable is used for the len calculation for the spaces.
char[] c = {'A','B','C','D','E','F','G'};
int i, j;
int max = 5; //your max output (could be 6)
for(j = max; j >= 0; j--)
{
for(int k = 0; k <= j; k++)
{
System.out.print(c[k]);
}
int len = max*2+1; //length calculation
for(int x = 0; x < len-2*j; x++){ //space loop
System.out.print(" ");
}
for(i = j; i >= 0; i--)
{
System.out.print(c[i]);
}
System.out.println();
}
Please use proper names for your variables. Java is not Basic, so you can use up to 65,535 characters in a variable name if you wish.
Documentation through code helps people who have to maintain code in the future.
public class PrintChars {
public static void main(String args[]) {
char[] chars = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H' };
int length = chars.length;
for (int row = length; row > 0; row--) {
for (int left = 0; left < row; left++) {
System.out.print(chars[left]);
}
for (int space = 0; space < (length-row)*2+1; space++) {
System.out.print(' ');
}
for (int right = row-1; right >= 0; right--) {
System.out.print(chars[right]);
}
System.out.println();
}
}
}
Output:
ABCDEFGH HGFEDCBA
ABCDEFG GFEDCBA
ABCDEF FEDCBA
ABCDE EDCBA
ABCD DCBA
ABC CBA
AB BA
A A
Related
I'm working on a Caesar cipher and I've gotten the majority of the code to work as planned.
the code is supposed to
remove all special characters and spaces
bring everything to uppercase
add spaces at an inputted interval any additional leftover spaces with x's
so for example if i were to type
plaintext: Hi im Doug
key: 1
buffer: 3
my output should be
IJJ NEP VHX
now I've gotten everything to work but the buffer part
this is my code in its entirety
import java.util.Scanner;
import java.lang.String;
public class Main {
public static void main(String[] args) {
System.out.print("Enter plaintext: ");
Scanner pTextInp = new Scanner(System.in);
String pText = pTextInp.nextLine();
System.out.print("Enter key value: ");
Scanner kInp = new Scanner(System.in);
int key = kInp.nextInt();
pText = normalizeText(pText);
pText = caesarify(pText, key);
System.out.print("Enter desired grouping number: ");
Scanner grpInp = new Scanner(System.in);
int grpInt = grpInp.nextInt();
pText = groupify(grpInt, pText);
System.out.println(pText);
}
// CONVERT STRING TO A CHAR ARRAY
public static char[] sArray(String s) {
int sLen = s.length();
char[] sChar = new char[sLen + 1];
for (int i = 0; i < sLen; i++){
sChar[i] = s.charAt(i);
}
return sChar;
}
public static String caesarify(String s, int k) {
int sLen = s.length();
char cText[] = sArray(s);
for (int i = 0; i < sLen; i++){
int j = cText[i] - 65;
int l = (((j + k) % 26) + 65);
cText[i] = (char) l;
}
s = new String(cText);
return s;
}
// normalizes text (removes all spaces and special characters)
public static String normalizeText(String s) {
int sLen = s.length();
char[] t1 = s.toCharArray();
for (int i = 0; i < sLen; i++ ){
if(t1[i] < 'A' || t1[i] > 'z' || (t1[i] > 'Z' && t1[i] < 'a')) {
t1[i] = ' ';
}
else{
t1[i] = s.charAt(i);
}
}
String t = new String(t1);
t = t.replaceAll(" ", "" );
t = t.toUpperCase();
return t;
}
public static String groupify(int i , String s){
int sLen = s.length();
char[] t = new char[sLen];
for (int j = 0; j < s.length(); j++){
t[j] = s.charAt(j);
if ( j % i == 0) {
t[j] = ' ';
sLen++;
}
}
s = new String(t);
return s;
}
and this is the section in particular that i think is the issue
public static String groupify(int i , String s){
int sLen = s.length();
char[] t = new char[sLen];
for (int j = 0; j < s.length(); j++){
t[j] = s.charAt(j);
if ( j % i == 0) {
t[j] = ' ';
sLen++;
}
}
s = new String(t);
return s;
}
with this this if i input
Hi Im Doug
I get
JJ EP H
as output
Thanks a bunch
Currently your code t[i] += ' ' is adding the space character's value to value in the array. That's not what you want. Rather you want to be storing a space in next position. I also suggest that you use better names for your variable - single character variables should generally only be used for indexes.
int pos = 0;
for (int j = 0; j < input.length(); j++)
result[pos++] = input.charAt(j);
if ( j % group == 0) {
result[pos++] = ' ';
}
}
For the code You have highlighted you are missing curly brackets after the for Loop. Try to define j outside the for-loop and assign the value 0 to j in the for-loop. It would be a better practice if you Store the size of your new Char-Array in a separate variable as it is easier to read when finding bugs in the code.
Input: {a, b, c, d} (Character Array)
I want to generate below sequence using above character array as Input
Output:
a bcd
ab cd
abc d
abcd
a b c d
ab c d
a bc d
a b cd
You can try,
char[] a = { 'a', 'b', 'c', 'd' };
for (int i = 0; i < (a.length*2); i++) {
if (i < a.length) {
for (int j = 0; j < a.length; j++) {
System.out.print(a[j]);
if (j == i)
System.out.print(" ");
}
System.out.println("");
} else {
for (int k = 0; k < a.length; k++) {
System.out.print(a[k]);
if (k != (i - (a.length + 1)))
System.out.print(" ");
}
System.out.println("");
}
}
import org.apache.commons.lang3.StringUtils;
public class Demo2 {
public static void main(String...args){
char [] a = {'a','b','c','d'};
String str = String.valueOf(a);//convert to
String[] input = str.split("");//string array
String str1 = StringUtils.join(input,""); // join to "abcd" for the first half of output
String str2 = StringUtils.join(input," "); // join to "a b c d" for the second half of output
for(int i = 1; i<str1.length()+1; i++){
System.out.println(str1.substring(0, i)+" "+str1.substring(i, str1.length())); //insert " "at index i
}
System.out.println(str2);
for(int i = 1; i<str2.length()-1; i=i+2){
System.out.println(str2.substring(0, i)+""+str2.substring(i+1, str2.length())); //remove " " at index i
}
}
}
for (int i = (1 << (a.length - 1)) - 1; i >= 0; --i) {
System.out.print(a[0]);
for (int j = 0; j < a.length - 1; ++j) {
if ((i & (1 << j)) == 0)
System.out.print(" ");
System.out.print(a[j + 1]);
}
System.out.println();
}
this code works for the above given output,
for(i=0;i<(2*a.length);i++){
if(i<a.length){
for(j=0;j<a.length;j++){
System.out.print(a[j]);
if(j==i)
System.out.print(" ");//for white spaces
}
System.out.println(""); //new line
}
else{
for(k=0;k<a.length;k++){
System.out.print(a[k]);
if(k!=(i-(a.length+1)))
System.out.print(" ");
}
System.out.println("");
}
}
But, i think your code doesn't give the expected output, not even the first few lines as you said.
public class Reverse {
public static void main(String args[]) {
char array[] = { 'a', 'x', 'y', 'd', 'd' };
int length = array.length;
for (int i = length - 1; i <= 0; i--) {
System.out.println(array[i] + " ");
}
}
}
//Above is the code i am runnig and see the message as "Reverse[Java Application]"
<terminated> is just the status of the program.
Here, your code terminates because we never enter your loop since i is never <= 0
Correction
char array[] = { 'a', 'x', 'y', 'd', 'd' };
int length = array.length;
for (int i = length - 1; i >= 0; i--) {
System.out.println(array[i] + " ");
}
You aren't getting anything (<Terminated>) because it is never running. Replace <= with >=.
the login in the for is blocking the code to loop
change this:
for (int i = length - 1; i <= 0; i--) {
for this
public static void main(String[] args) {
char array[] = { 'a', 'x', 'y', 'd', 'd' };
int length = array.length;
for (int i = 0; i <length; i++) {
System.out.println(array[i] + " ");
}
System.out.println(" now in reverse order:" );
//reverse order:
for (int i = length-1; i >=0; i--) {
System.out.println(array[i] + " ");
}
}
I am coding in java for four months now - still a newbie! I want to create a randomised no-repeating array in Java with a frame to find coordinates. I have initialized the chars that I would like in the array however I persistently get stops, dashes and brackets etc in the print out. What am I missing? I do not want to go down the employing of libraries route.
final char[] randomSquare = {'C', 'O', 'D', 'I', 'N', 'G'};
// the Grid used that will be randomly filled
char[][] grid;
int A = 65;
int Z = 90;
int num0 = 48;
int num9 = 57;
// create a Random numbers generator
Random ran = new Random();
grid = new char[randomSquare.length][randomSquare.length];
// loop to print randomSquare header for grid array
for (int j = 0; j < 1; j++) {
System.out.print(" ");
System.out.print(randomSquare);
}
System.out.println();
// print randomSquare at position 0 all the way down
for(int i = 0; i < randomSquare.length; i++) {
// the letter at the beginning of the row
System.out.print(randomSquare[i] + " ");
// the Grid contents for that line
int index = 0;
for(int j = 0; j < randomSquare.length; j++) {
if (A >= 65 && A <= 90){
index = ran.nextInt(A + Z);
}
if (num9 <= 57 && num9 >= 48) {
index = ran.nextInt(num0 + num9);
}
System.out.print("" + (char)index);
}
System.out.println();
index++;
}
return grid;
below fix your problem with chars outside A-Z and 0-9
for(int i = 0; i < randomSquare.length; i++) {
// the letter at the beginning of the row
System.out.print(randomSquare[i] + " ");
// the Grid contents for that line
int index = 0;
for(int j = 0; j < randomSquare.length; j++) {
if(ran.nextBoolean()){
if (A >= 65 && A <= 90){
index = A + ran.nextInt(Z - A);
}
}else
if (num9 <= 57 && num9 >= 48) {
index = num0 + ran.nextInt(num9 - num0);
}
System.out.print("" + (char)index);
}
System.out.println();
index++; }
for(int i = 0; i < randomSquare.length; i++) {
// the letter at the beginning of the row
System.out.print(randomSquare[i] + " ");
// the Grid contents for that line
int index = 0;
for(int j = 0; j < randomSquare.length; j++) {
if(ran.nextBoolean()){
if (A >= 65 && A <= 90){
index = A + ran.nextInt(Z - A);
}
}else
if (num9 <= 57 && num9 >= 48) {
index = num0 + ran.nextInt(num9 - num0);
}
System.out.print("" + (char)index);
}
System.out.println()
;
index++; }
I don't think this does what you expect it to do and it's unclear what you desire. I'm going to rework your code to generate random numbers or letters, but you will probably need to carefully consider your code.
// the Grid contents for that line
//perhaps index isn't the best name
int index = 0;
for(int j = 0; j < randomSquare.length; j++) {
//keep generating new indexe until we get one within desired range
while (!(index >= 65 && index <= 90 || index <= 57 && index >= 48))
index = ran.nextInt(Z-num0)+num0; // gives numbers in a range from num0 to Z (48 to 90)
System.out.print("" + (char)index);
}
System.out.println();
//not sure why this would be necessary
index++;
From what I understood you want to populate a random array from letters and numbers avoiding duplicates, well just try the fiollowing:
//The array containing letters and numbers.
char[] lettersAndNumbers = {'0','1','2','3','4','5','6','7','8','9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'U','V','W','X','Y','Z'};
// the new list to populate
List<String> lc=new ArrayList<String>();
Random ran = new Random();
int i=0;
while(i<20) {
//Choose a random index for to take an element from the array
int rand=ran.nextInt(lettersAndNumbers.length);
//put this element in the list if it doesn't exist
if(!lc.contains(String.valueOf(lettersAndNumbers[rand]))) {
lc.add(String.valueOf(lettersAndNumbers[rand]));
i++;
}
}
//Convert your list to an array
Object[] myArray=lc.toArray();
for (int j=0;j<myArray.length;j++){
System.out.println(myArray[j]);
}
Create a char array that contains all letters and numbers.
Create a List and populate it with random elements from this array (if they don't exist already in the list).
Convert your list to an array.
I'm not sure I understood correctly what you're trying to do. But if you want a Collection of something that contains unique references, don't use a List or an Array, use a HashSet.
I have a two-dimensional character array board[row][col], which is designed to simulate a game board for a game of Xs and Os. (For reference, each element in the array is either an X, an O, or ' ', a space to signify no move in that square.)
I am trying to get a string of all characters in the array, row by row. That is, the first row will be printed to string, then the second row will be appended to that string, until all rows are traversed. In the end, the result should look like a string of symbols such as "XXO X OOX" for this game board:
X X O
X
O O X
How can this be done?
try:
StringBuilder str = new StringBuilder();
for (int i = 0; i < 3; i++)
for (int j = 0; j < 3; j++)
str.append(board[i][j]);
you could find more data about StringBuilder here.
I think better sulution will be like this
char [][] board = new char[][]{{'x','x','o',},{'x',},{'o','o','x',}};
StringBuilder builder = new StringBuilder();
for (char[] aBoard : board)
builder.append(String.valueOf(aBoard)).append(" ");
System.out.println(builder.toString());
out
xxo x oox
You can try something along these lines:
char[][] board = {{'X', 'O', 'X'}, {0, 'O', 0}, {'X', 'O', 'X'}};
String s = "";
for (char[] row : board) {
for (char c : row)
s += c == 0 ? " " : c;
s += "\n";
}
System.out.println(s);
Output:
XOX
O
XOX
Edit: If you want the output to be spaced out, you could use
for (char[] row : board) {
for (char c : row)
s += c == 0 ? " " : c + " ";
s += "\n";
}
Output:
X O X
O
X O X
for(int i=0; i< board.length; i++){
for(int j=0; i< board[i].length; j++){
System.out.print(""+board[i][j]); //<- use print() here
}
System.out.println(); //<- use println() here
}
Have nested loops like so:
for (int i = 0; i < board.length; i++)
{
for (int j = 0; j < board[0].length; j++)
{
System.out.print(board[i][j] + " ");
}
System.out.println();
}
The first print statement will add all the characters from one row together and then the next print statement, outside of the second loop, will append a newline.
String[][] board = {{"X", "X","O"},{" ", "X", " "},{"O", "O", "X"}};
for(int i = 0; i < board.length; i++) {
for(int j = 0; j < board[0].length; j++) {
System.out.print(board[i][j] + " ");
}
System.out.println();
}