Java: Printing two dimensional array in grid format - java

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.

Related

How to hide characters using for loops, respectively?

I want to basically hide characters following three constant dots (...), the pattern goes like this:
Inputs a phrase from the user and outputs the phrase followed by three dots (...), then the phrase minus one character followed by three dots (...), then the phrase minus two characters followed by the dots, and so on until only one dot is left.
Note: This has to be done using nested for loops only
Sample input
1
disappear
Expected output:
disappear...
disappea...
disappe...
disapp...
disap...
disa...
dis...
di...
d...
...
..
.
This is my attempt:
Problem: I am unable to make it so the phrase decreases each time (minus 1 each time)
I tried using the charAt(); method, but it wouldn't work, I am sure that you would need a for loop separate for each of the dots or a whole set of dots, in this case.
import java.util.Scanner;
public class Dissappear{
public static void main(String[]args){
Scanner keyboard = new Scanner(System.in);
int option = keyboard.nextInt();
String phrase = keyboard.next();
if (option == 1){
for (int x = 0; x <= phrase.length(); x++){
System.out.print(phrase + "...");
for (int y = 0; y <= phrase.length(); y++){
char n = phrase.charAt(y);
System.out.print(n+"...");
}
}
}
}
}
This is how I got it to work:
public class Disappear {
public static void main(String... args) {
String word = "disappear";
int originalLength = word.length();
for(int i = 0; i < originalLength; i++) {
System.out.println(word.substring(0, originalLength - i) + "...");
}
for(int i = 0; i < 3; i++) {
for(int j = 0; j < 3 - i; j++) {
System.out.print(".");
}
System.out.println();
}
}
}
Without substring:
public class Disappear {
public static void main(String... args) {
String word = "disappear";
int originalLength = word.length();
for(int i = 0; i < originalLength; i++) {
for(int j = 0; j < originalLength - i; j++) {
System.out.print(word.charAt(j));
}
System.out.println("...");
}
for(int i = 0; i < 3; i++) {
for(int j = 0; j < 3 - i; j++) {
System.out.print(".");
}
System.out.println();
}
}
}
You can do it with StringBuilder:
StringBuilder stringBuilder = new StringBuilder(str);
System.out.println(str + "...");
for (int i = 0; i < length; i++) {
stringBuilder.deleteCharAt(stringBuilder.length() - 1);
System.out.println(stringBuilder.toString() + "...");
if (i == length - 1) {
for (int j = 0; j < 2; j++) {
for (int k = j; k < 2; k++) {
System.out.print(".");
}
System.out.println();
}
}
Ok! Nested for loops. But the outer one is only included to meet the requirement. Probably not in the spirit of the assignment though. Just keep decrementing k until it is zero and then latch it there until the StringBuilder length is 0 and the inner loop terminates.
StringBuilder sb = new StringBuilder("disappear...");
for (;;) {
for (int k = sb.length() - 4; sb.length() > 0;) {
System.out.println(sb);
sb.delete(k, k + 1);
k = k > 0 ? --k : 0;
}
break;
}

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.

printing v shape in java

I am a newbie to java programming and I am working on this excercise from my textbook. The goal is to print a V shape pattern of numbers. From the picture below, you can see what the output should look like. I am having trouble creating the other half of numbers. I have pasted my code down below for reference.
for (int i = 7; i >= 1; i--) {
for (int j = 1; j <= i; j++) {
System.out.print(" ");
}
System.out.print(i);
for (int k = 1; k >= i*2; k++) {
System.out.print(" ");
}
System.out.println(i);
Use the following code (just made a few modifications to your code, did not check its efficiency):
public static void main(String[] args) {
for (int i = 7; i >= 1; i--) {
for (int k = 7; k >= i; k--) {
System.out.print(" "); // Print 7-i number of spaces before start of each line
}
System.out.print(i); // Print i
for (int j = 1; j <= i*2; j++) {
System.out.print(" "); // Print i*2 number of spaces after printing i
}
System.out.println(i); // Print i
}
}
Rather then nesting loops (and iterating backwards), I would decompose the generating of white-space with a method to repeat a given String a given number of times. Like,
private static String repeat(String s, int n) {
return Stream.generate(() -> s).limit(n).collect(Collectors.joining());
}
Then I would prefer a StringBuilder and a single call to println like
public static void main(String[] args) {
int start = 6;
for (int i = 0; i < start; i++) {
int v = start - i;
StringBuilder sb = new StringBuilder();
sb.append(repeat(" ", i)).append(v);
sb.append(repeat(" ", 2 * v)).append(v);
System.out.println(sb);
}
}

nested for loop for alphabet increment

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
}
}
}
}

How to print a two dimensional array?

I have a [20][20] two dimensional array that I've manipulated. In a few words I am doing a turtle project with user inputting instructions like pen up = 0 and pen down = 1. When the pen is down the individual array location, for instance [3][4] is marked with a "1".
The last step of my program is to print out the 20/20 array. I can't figure out how to print it and I need to replace the "1" with an "X". The print command is actually a method inside a class that a parent program will call. I know I have to use a loop.
public void printGrid() {
System.out.println...
}
you can use the Utility mettod. Arrays.deeptoString();
public static void main(String[] args) {
int twoD[][] = new int[4][];
twoD[0] = new int[1];
twoD[1] = new int[2];
twoD[2] = new int[3];
twoD[3] = new int[4];
System.out.println(Arrays.deepToString(twoD));
}
public void printGrid()
{
for(int i = 0; i < 20; i++)
{
for(int j = 0; j < 20; j++)
{
System.out.printf("%5d ", a[i][j]);
}
System.out.println();
}
}
And to replace
public void replaceGrid()
{
for (int i = 0; i < 20; i++)
{
for (int j = 0; j < 20; j++)
{
if (a[i][j] == 1)
a[i][j] = x;
}
}
}
And you can do this all in one go:
public void printAndReplaceGrid()
{
for(int i = 0; i < 20; i++)
{
for(int j = 0; j < 20; j++)
{
if (a[i][j] == 1)
a[i][j] = x;
System.out.printf("%5d ", a[i][j]);
}
System.out.println();
}
}
Something like this that i answer in another question
public class Snippet {
public static void main(String[] args) {
int [][]lst = new int[10][10];
for (int[] arr : lst) {
System.out.println(Arrays.toString(arr));
}
}
}
public static void printTwoDimensionalArray(int[][] a) {
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a[i].length; j++) {
System.out.printf("%d ", a[i][j]);
}
System.out.println();
}
}
just for int array
Well, since 'X' is a char and not an int, you cannot actually replace it in the matrix itself, however, the following code should print an 'x' char whenever it comes across a 1.
public void printGrid(int[][] in){
for(int i = 0; i < 20; i++){
for(int j = 0; j < 20; j++){
if(in[i][j] == 1)
System.out.print('X' + "\t");
else
System.out.print(in[i][j] + "\t");
}
System.out.print("\n");
}
}
You should loop by rows and then columns with a structure like
for ...row index...
for ...column index...
print
but I guess this is homework so just try it out yourself.
Swap the row/column index in the for loops depending on if you need to go across first and then down, vs. down first and then across.
How about trying this?
public static void main (String [] args)
{
int [] [] listTwo = new int [5][5];
// 2 Dimensional array
int x = 0;
int y = 0;
while (x < 5) {
listTwo[x][y] = (int)(Math.random()*10);
while (y <5){
listTwo [x] [y] = (int)(Math.random()*10);
System.out.print(listTwo[x][y]+" | ");
y++;
}
System.out.println("");
y=0;
x++;
}
}
If you know the maxValue (can be easily done if another iteration of the elements is not an issue) of the matrix, I find the following code more effective and generic.
int numDigits = (int) Math.log10(maxValue) + 1;
if (numDigits <= 1) {
numDigits = 2;
}
StringBuffer buf = new StringBuffer();
for (int i = 0; i < matrix.length; i++) {
int[] row = matrix[i];
for (int j = 0; j < row.length; j++) {
int block = row[j];
buf.append(String.format("%" + numDigits + "d", block));
if (j >= row.length - 1) {
buf.append("\n");
}
}
}
return buf.toString();
I am also a beginner and I've just managed to crack this using two nested for loops.
I looked at the answers here and tbh they're a bit advanced for me so I thought I'd share mine to help all the other newbies out there.
P.S. It's for a Whack-A-Mole game hence why the array is called 'moleGrid'.
public static void printGrid() {
for (int i = 0; i < moleGrid.length; i++) {
for (int j = 0; j < moleGrid[0].length; j++) {
if (j == 0 || j % (moleGrid.length - 1) != 0) {
System.out.print(moleGrid[i][j]);
}
else {
System.out.println(moleGrid[i][j]);
}
}
}
}
Hope it helps!
more simpler approach , use java 5 style for loop
Integer[][] twoDimArray = {{8, 9},{8, 10}};
for (Integer[] array: twoDimArray){
System.out.print(array[0] + " ,");
System.out.println(array[1]);
}

Categories