I have an x by y board of numbers stored in a two dimensional array in java that I would like to print out to the user in a nice formatted manner. Would there be an easy way to do this in java?
Here is how I build my board:
board = new int[TotRow][TotCol];
You might prefer the one line, because it's easy, Arrays.deepToString(Object[]) the Javadoc says (in part),
This method is designed for converting multidimensional arrays to strings.
System.out.println(Arrays.deepToString(board));
If you want the number to be padded properly as well use String.format(),
for (int i = 0; i < TotRow; i++) {
for (int j = 0; j < TotCol; j++) {
System.out.print(String.format("%3d", board[i][j]) + "\t");
}
System.out.println();
}
Notice that I have used %3d for formatting, you can use format as required by you
You can print the board two dimensional array like this
for (int i = 0; i < board.length; i++) {
for (int j = 0; j < board[i].length; j++) {
System.out.print(board[i][j] + "\t");
}
System.out.println();
}
Since I don't like relying on tabs, I'd like to mention some approaches that don't rely on them.
If you know that all of the numbers in the table are nonnegative numbers of, say, 4 digits or less, you can use String.format in a manner similar to Nitin's answer:
for (int i = 0; i < TotRow; i++) {
for (int j = 0; j < TotCol; j++) {
System.out.print(String.format("%4d ", board[i][j]));
}
System.out.println();
}
The %4d means to format the number using a width of 4 characters, and pad with blanks on the left if the number takes fewer than 4 characters to print. Thus, if there aren't any 5-digit or longer numbers, each print will print exactly 5 characters--a 4-character field for the number, and a space after the number. This will make everything line up, as long as none of the numbers is too large. If you do get a number that takes more than 4 characters, the formatting will get messed up.
Here's a way to adjust the column width so that it's just large enough to hold all the values in the table, and works fine if there are negative numbers:
int maxWidth = 0;
for (int i = 0; i < TotRow; i++) {
for (int j = 0; j < TotCol; j++) {
maxWidth = Math.max(maxWidth, Integer.toString(board[i][j]).length());
}
}
String format = "%" + maxWidth + "d ";
for (int i = 0; i < TotRow; i++) {
for (int j = 0; j < TotCol; j++) {
System.out.print(String.format(format, board[i][j]));
}
System.out.println();
}
Note: not tested
for (int i = 0; i < x; i++) {
for (int j = 0; j < y; j++) {
System.out.print(board[i][j] + "\t");
}
System.out.println();
}
You basically just use a nested loop.
for (int i = 0; i < board.length; i++) {
for (int j = 0; j < board[i].length; j++) {
System.out.print(board[i][j] + " ");
}
System.out.println();
}
Related
I need to print a table that looks like this if the user entered a 5 using nested for loops:
****5
***45
**345
*2345
12345
I've been working on this for hours and the closest I got was:
int size = scan.nextInt();
for (int i = 1; i <= size; i++)
{
for (int star = size-1; star >= i; star--)
System.out.print("*");
for (int k = 1; k <= i; k++)
System.out.print(i);
System.out.println();
}
Which outputs this:
****1
***12
**123
*1234
12345
You have too many loops; I find it easier to reason about zero based looping so I'm going to use that. Iterate i and j from 0 to size. If j + 1 is greater than size - i - 1 then we want to print j + 1. Otherwise, we want a star. Like,
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
if (j + 1 > size - i - 1) {
System.out.print(j + 1);
} else {
System.out.print('*');
}
}
System.out.println();
}
For size = 5 that outputs (as requested)
****5
***45
**345
*2345
12345
If you simply must have one based indices, that would be
for (int i = 1; i <= size; i++) {
for (int j = 1; j <= size; j++) {
if (j > size - i) {
System.out.print(j);
} else {
System.out.print('*');
}
}
System.out.println();
}
If you want to keep your loops and avoid if statements, you can tweak last loop by changing
for (int k = 1; k <= i; k++)
into
for (int k = 1+size-i; k <= size; k++)
Btw I also find it way easier to start loops from 0, so updated code would look like this:
int size = scan.nextInt();
for (int i = 0; i < size; i++)
{
for (int star = size-1; star > i; star--)
System.out.print("*");
for (int k = size-i; k <= size; k++)
System.out.print(k);
System.out.println();
}
I hope it helps
This assignment involves a 'matrix.txt' file that is to be imported into the program. This file can have a matrix of any size. The prof has furnished a working program to properly import this file, and has set the task of the students to determine if this file is a Magic Square. I know this means getting the sum of each row and each column and then comparing the values to see if they are equal. My problem is that I do not know how to specify a single rows' value that does not have to be immediately printed out, thereby losing the value when the loop repeats. I would like a way that will store each value so they can be checked for equality after the loop has iterated over all the possible rows and columns. since I have no idea what the size of the array will be, I cannot 'hard code' values, and would have to use stuff like:
sum = 0;
for (i = 0; i < matrix.length; i++)
{
for (j = 0; j < matrix[i].length; j++)
I am looking for a way to individualize the values of each row and column so I can compare them later. Then I would print out "The matrix is a magic square", or "The matrix is not a magic square"
Would some code like this work?
boolean isMagicSquard = true;
int sum = -1;
for (int i = 0; i < matrix.length; i++){
// Calculate the sum for each row
int rowsum = 0;
for (int j = 0; j < matrix[i].length; j++){
rowsum += matrix[j][i];
}
if (sum == -1){
sum = rowsum;
}else if (sum != rowsum){ // If the sum differs from the
// first-row sum, it is no magic squaree
isMagicSquard = false; break;
}
}
// The same code with rows and column swaped
for (int i = 0; i < matrix[0].length; i++){
int columnsum = 0;
for (int j = 0; j < matrix.length; j++){
columnsum += matrix[i][j];
}
if (sum != columnsum ){
isMagicSquard = false; break;
}
}
System.out.println(isMagicSquare);
I am trying to make my code print out the Asterisk in the image, you see below. The Asterisk are align to the right and they have blank spaces under them. I can't figure out, how to make it go to the right. Here is my code:
public class Assn4 {
public static void main(String[] args) {
for (int i = 0; i <= 3; i++) {
for (int j = 0; j <= i; j++) {
System.out.print("*");
}
for (int x = 0; x <= 1; x++) {
System.out.println(" ");
}
for (int j = 0; j <= i; j++) {
System.out.print("*");
}
}
System.out.println();
}
}
Matrix problems are really helpful to understand loops..
Understanding of your problem:
1) First, printing star at the end- That means your first loop should be in decreasing order
for(int i =7;i>=0; i+=i-2)
2) Printing star in increasing order- That means your second loop should be in increasing order
for(int j =0;j<=7; j++)
Complete code:
for(int i =7;i>=0; i=i-2){ // i=i-2 because *s are getting incremented by 2
for(int j =0;j<=7; j++){
if(j>=i){ // if j >= i then print * else space(" ")
System.out.print("*");
}
else{
System.out.print(" ");
}
}
System.out.println();// a new line just after printing *s
}
Starting loops with 1 can sometimes help you visualize better.
int stopAt = 7;
for (int i = 1; i <= stopAt ; i += 2) {
for (int j = 1; j <= stopAt; j++) {
System.out.print(j <= stopAt - i ? " " : "*");
}
System.out.println();
}
Notice, how each row prints an odd number of *s ending at the line with 7. So, you start with i at 1 and go through 3 1+2, 5 3+2, and then stopAt 7 5+2.
The nested for loop has to print 7 characters always to make sure *s appear right aligned. So, the loop runs from 1 to 7.
Here the complete code:
for(int i = 0; i < 8; i++){
if( i%2 != 0){
for(int x = 0; x < i; x++){
System.out.print("*");
}
}else{
System.out.println();
}
}
i want to print a triangle/pyramid style like:
1
323
54345
7654567
here is my code:
int lines = 5;
for (int i = 1; i < lines; i++) {
for (int j = 1; j < lines-i; j++) {
System.out.print(" ");
}
for (int j = i; j > 1; j--) { //this for loop is my problem. any solution?
System.out.print(j);
}
for (int j = i; j < i+i; j++) {
System.out.print(j);
}
System.out.println();
}
what i got is
1
223
32345
4324567
i been studying codes while working at office and i think week long i still could not find a solution to this even i use search in Google.
i am only into enhancing my logic through conditionals and no heavy object oriented or recursion yet.
The problem in your first loop is a problem you figured out in your second one! (and it has something to do with the largest number in the loop)
for (int j = i; j > 1; j--) { //this for loop is my problem. any solution?
System.out.print(j);
}
Look at the numbers on the left of the pyramid. They start where the ones on the right end (every line of the pyramid is symmetrical). And the general formula for that number is i + i - 1, where i is the line number from your outer loop.
The second row starts at 2 * i - 1 = 2 * 2 - 1 = 3. The third row starts at 2 * 3 - 1 = 5 etc.
Your second inner loop should therefore look like this:
for (int j = i + i - 1; j > i; j--) {
System.out.print(j);
}
Here is the complete fixed source.
You have to start at the i-th odd number. This is i*2-1. And you stop at i. This also fixes a spacing difference introduced by changing it to lines = 4.
int lines = 4;
for (int i = 1; i <= lines; i++) {
for (int j = 1; j < lines-i+1; j++) {
System.out.print(" ");
}
for (int j = i*2-1; j > i; j--) { //this for loop is my problem. any solution?
System.out.print(j);
}
for (int j = i; j < i+i; j++) {
System.out.print(j);
}
System.out.println();
}
Run it here: http://ideone.com/AKsc1f
int lines = 4;
for (int i = 1; i <= lines; i++) {
for (int j = 1; j < lines-i+1; j++) {
System.out.print(" ");
}
//replace this
for(int j=0; j<i-1; j++) System.out.print(i*2-j-1);
System.out.print(i);
for(int j=; j<i-1;j++) System.out.print(i+j+1);
//==========
System.out.println();
}
I've been trying to print a char matrix consisting only of lowercase letters in java. At first I was defining a String out of the matrix entries and then using JOptionPane to print it, but apparently due to the different spacing of the letters, the columns were not alligned so it looks bad. The code was the following:
String wordSearch = "";
for(int i = 0; i < 20; i++){
for(int j = 0; j < 20; j++){
wordSearch = wordSearch + matrix[i][j] +"\t";
}
wordSearch = wordSearch + "\n";
}
JOptionPane.showMessageDialog(null, wordSearch);
Then I attempted just printing the matrix using System.out as follows
for(int i = 0; i < 20; i++){
for(int j = 0; j < 20; j++){
System.out.print(matrix[i][j] +" ");
}
System.out.println();
}
and the output looks perfect, the columns are well alligned.
So my question is how can I achieve the same result using JOptionPane or something similar? Why does the output look different when I print it in the console?
Thank you very much for any help.
This should work:
javax.swing.UIManager.put("OptionPane.font", new Font("Courier", Font.PLAIN, 16));
final StringBuilder wordSearch = new StringBuilder();
for (int i = 0; i < 20; i++){
for (int j = 0; j < 20; j++){
wordSearch.append(matrix[i][j]).append('\t');
}
wordSearch.append('\n');
}
JOptionPane.showMessageDialog(null, wordSearch.toString());
(not tested)