Java exercise - display table with 2d array - java

I'm struggling to finish a java exercise, it involves using 2d arrays to dynamically create and display a table based on a command line parameter.
Example:
java table 5
+-+-+-+-+-+
|1|2|3|4|5|
+-+-+-+-+-+
|2|3|4|5|1|
+-+-+-+-+-+
|3|4|5|1|2|
+-+-+-+-+-+
|4|5|1|2|3|
+-+-+-+-+-+
|5|1|2|3|4|
+-+-+-+-+-+
What i have done so far:
public static void main(String[] args) {
int num = Integer.parseInt(args[0]);
String[][] table = new String[num*2+1][num];
int[] numbers = new int[num];
int temp = 0;
for(int i=0; i<numbers.length; i++)
numbers[i] = i+1;
// wrong
for(int i=0; i<table.length; i++){
for(int j=0; j<num;j++){
if(i%2!=0){
temp=numbers[0];
for(int k=1; k<numbers.length; k++){
numbers[k-1]=numbers[k];
}
numbers[numbers.length-1]=temp;
for(int l=0; l<numbers.length; l++){
table[i][j] = "|"+numbers[l];
}
}
else
table[i][j] = "+-";
}
}
for(int i=0; i<table.length; i++){
for(int j=0; j<num; j++)
System.out.print(table[i][j]);
if(i%2==0)
System.out.print("+");
else
System.out.print("|");
System.out.println();}
}
This doesn't work, since it prints 1|2|3|4 in every row, which isn't what I need. I found the issue, and it's because the first for loop changes the array order more times than needed and basically it returns as it was at the beginning.
I know that probably there's a way to achieve this by writing more code, but I always tend to nest as much as possible to "optimize" the code while I write it, so that's why I tried solving this exercise by using less variables and loops as possible.

You are too complex. Hard to find your error. Straight code follows:
public static void main(String[] args) {
//int num = Integer.parseInt(args[0]);
int num = 5; // for test
// creating 2d array
int[][] figures = new int[num][num];
// filling the array
for(int row=0; row<figures.length; ++row) {
for(int col=0; col<figures[row].length; ++col) {
figures[row][col] = (row + col) % num + 1;
}
}
// printing the array
for(int row=0; row<figures.length; ++row) {
// printing border
for(int col=0; col<figures[row].length; ++col) {
System.out.print("+-");
}
System.out.println("+");
// printing data row
System.out.print("|");
for(int col=0; col<figures[row].length; ++col) {
System.out.print(figures[row][col]);
System.out.print("|");
}
System.out.println();
}
// printing final border
for(int col=0; col<figures[0].length; ++col) {
System.out.print("+-");
}
System.out.println("+");
}

public static void main(String args[]){
int dimension = Integer.valueOf(args[0]);
int[][] twoDimArray = new int[dimension][dimension];
for(int i=0;i<dimension;i++){
for(int j=0;j<dimension;j++){
System.out.print("|"+((i+1)%(dimension+1)));
} //end of j loop
} //end of i loop
} //end of main
The above is only the logic for printing the numbers in the specified sequence.
The other design pattern ( +-+ ) thing i guess u can manage.

the following codes will initialize a 2d int array for the data (1-5 in your example). and print the table. note that the table structure was not save in a String 2d-array. just print the table out. see comments in line.
public static void main(String[] args){
final int num = 5; //hardcoded 5, just for testing.
final int[][] data = new int[num][num];
for (int r = 0; r < data.length; r++) {
for (int c = 0; c < data[r].length; c++) {
final int t = r + c + 1;
data[r][c] = t <= num ? t : t - num;
}
}
// now we have all int data in data 2D-array
// here is the +-+- line
final StringBuilder sb = new StringBuilder("+");
for (int i = 0; i < data.length; i++)
sb.append("-+");
// now print the table
for (int r = 0; r < data.length; r++) {
System.out.println(sb.toString());
for (int c = 0; c < data.length; c++)
System.out.print("|" + data[r][c]);
System.out.println("|");
}
System.out.println(sb.toString());
}
output:
if you give num=9 as argument. the codes above will print:
+-+-+-+-+-+-+-+-+-+
|1|2|3|4|5|6|7|8|9|
+-+-+-+-+-+-+-+-+-+
|2|3|4|5|6|7|8|9|1|
+-+-+-+-+-+-+-+-+-+
|3|4|5|6|7|8|9|1|2|
+-+-+-+-+-+-+-+-+-+
|4|5|6|7|8|9|1|2|3|
+-+-+-+-+-+-+-+-+-+
|5|6|7|8|9|1|2|3|4|
+-+-+-+-+-+-+-+-+-+
|6|7|8|9|1|2|3|4|5|
+-+-+-+-+-+-+-+-+-+
|7|8|9|1|2|3|4|5|6|
+-+-+-+-+-+-+-+-+-+
|8|9|1|2|3|4|5|6|7|
+-+-+-+-+-+-+-+-+-+
|9|1|2|3|4|5|6|7|8|
+-+-+-+-+-+-+-+-+-+

you have make it more complicated try this Simple code :
enter code here
public static void main(String[] args)
{
int n = 5 ;
for(int i = 1 ; i <= n ;i++)
{
for(int l = 0 ; l < n;l++)
System.out.print("+-");
System.out.print("\n|");
for(int j = i ; j <=n;j++ )
{
System.out.print(j+"|");
}
for(int k = 1 ; i >= 2 && k <=i-1;k++)
{
System.out.print(k+"|");
}
System.out.println();
}
}

Related

How stop array input limit then the result to show the output?

I have a question about stop array input limit then the result to show the output.
Below is my coding have already set new float[3][3]:
import java.util.Scanner;
public class Clone2Darray {
public static float[][] clone(float[][] a) throws Exception {
float b[][] = new float[a.length][a[0].length];
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a[0].length; j++) {
b[i][j] = a[i][j];
}
}
return b;
}
public static void main(String args[]) {
Scanner sc = new Scanner (System.in);
System.out.println ("Type nine float numbers two-dimensional array of similar type and size with line breaks, end by -1:");
float[][] a = new float[3][3];
for (int i=0; i<3; i++){
for (int j=0; j<3; j++){
String line = sc.nextLine();
if ("-1".equals(line)){
break;
}
a[i][j]=Float.parseFloat(line);
}
}
System.out.println("\n The result is:");
try {
float b[][] = clone(a);
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a[0].length; j++) {
System.out.print(b[i][j] + " ");
}
System.out.println();
}
} catch (Exception e) {
System.out.println("Error!!!");
}
}
}
The limit output is show me like below:
run:
Type float numbers in the two-dimensional array of similar type and size
with line breaks, end by -1:
5.33
9.33
63.33
6.36
3.55
7.25
2.33
3.66
The result is:
6.33 5.33 9.33
63.33 6.36 3.55
7.25 2.33 3.66
BUILD SUCCESSFUL (total time: 31 seconds)
My problem is want to stop limit float[3][3] and can unlimited key in the input until type -1 to stop the input. May I know how to remove the limit float[3][3] in the array? Hope anyone can guide me to solve my problem. Thanks.
At the point when you allocate memory for the two-dimensional array you have to tell the sizes of its elements, because memory will be allocated for that array and the amount of memory to be allocated must be known.
You can bypass this, by using some more dynamic types, like List and its popuplar implementation, ArrayList, even in a nested form. That's a nice thing to do, but then you will not have a "real" array.
The below code allows you to create the dynamic arrays.
import java.util.Scanner;
public class Clone2DArray {
public static float[][] clone(float[][] a) throws Exception {
float b[][] = new float[a.length][a[0].length];
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a[0].length; j++) {
b[i][j] = a[i][j];
}
}
return b;
}
public static void main(String args[]) {
Scanner sc = new Scanner (System.in);
System.out.println("enter row size");
int row = Integer.parseInt(sc.nextLine());
System.out.println("enter column size");
int column = Integer.parseInt( sc.nextLine());
System.out.println ("Type float numbers two-dimensional array of similar type and size with line breaks:");
float[][] a = new float[row][column];
for (int i=0; i<row; i++){
for (int j=0; j<column; j++){
String line = sc.nextLine();
if ("-1".equals(line)){
break;
}
a[i][j]=Float.parseFloat(line);
}
}
System.out.println("\n The result is:");
try {
float b[][] = clone(a);
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a[0].length; j++) {
System.out.print(b[i][j] + " ");
}
System.out.println();
}
} catch (Exception e) {
System.out.println("Error!!!");
}
}
}

how to use recursion for nested 'for' loops

I have a problem with nested for loops in java. My problem is that at the beginning I don't know exactly how many for loops I will need. It is set somewhere in the middle of my program. So let say my program creates an array. If the array has 3 elements then I create a three for loops like below.
for(int i = 0; i<tab[0].length() ; i++){
for(int j = 0; j<tab[1].length() ; j++){
for(int k = 0; k<tab[2].length() ; k++){
System.out.println(i+" "+j+" "+k);
}
}
}
If my program created an array with 4 elements then it would be like this:
for(int i = 0; i<tab[0].length() ; i++){
for(int j = 0; j<tab[1].length() ; j++){
for(int k = 0; k<tab[2].length() ; k++){
for(int h = 0; h<tab[3].length() ; h++){
System.out.println(i+" "+j+" "+k+" "+h);
}
}
}
}
Can any one tell me how to do this with recursion? I can have 2 nested loops but I can have 10 of them and always at the end I would like to print in the console numbers associated with all loops (i,j,k,h)
Here is a solution. At each recursive call, previousTabs becomes 1 longer and tabs becomes 1 shorter.
public static void iterate(int[] previousValues, int[] tabs) {
if (tabs.length == 0) {
System.out.println(Arrays.toString(previousValues));
}
else {
final int[] values = new int[previousValues.length + 1];
for (int i = 0; i < previousValues.length; i++) {
values[i] = previousValues[i];
}
final int[] nextTabs = new int[tabs.length - 1];
for (int i = 0; i < nextTabs.length; i++) {
nextTabs[i] = tabs[i + 1];
}
for (int i = 0; i < tabs[0]; i++) {
values[values.length - 1] = i;
iterate(values, nextTabs);
}
}
}
public static void iterate(int[] tabs) {
iterate(new int[0], tabs);
}

2D array populating not working

I'm trying to populate a 2D array with char's from a string I've read in. I'm having a problem with actually populating this 2D array. It keeps printing a 2D array bigger than what I've given it, and the number always seems to be 6 rather than the letters from the string.
I store the string in an ArrayList called tempArray.
Input strings:
WUBDLAIUWBD
LUBELUFBSLI
SLUEFLISUEB
I instantiate a 2D array with columnlength = 11, and rowcount 3
epidemicArray = new int[rowCount][columnCount];
Array before I try to populate it:
00000000000
00000000000
00000000000
My code:
public static void updateArray(){
//extract string from temp
for (int i = 0; i < tempArray.size(); i++){
String temp = tempArray.get(i);
char[] charz = temp.toCharArray();
for (int j = 0; j < charz.length; j++){
for (int k = 0; k < rowCount; k++){
for (int l = 0; l < columnCount; l++){
epidemicArray[k][l] = charz[j];
}
}
}
}
}
Output: Which I didn't expect
6666666666666666666666
6666666666666666666666
6666666666666666666666
Expected output: (2D array)
WUBDLAIUWBD
LUBELUFBSLI
SLUEFLISUEB
Thanks, this is really bugging me.
Change your code to this:
public static void updateArray(){
//extract string from temp
for (int i = 0; i < tempArray.size(); i++){
String temp = tempArray.get(i);
char[] charz = temp.toCharArray();
for (int j = 0; j < charz.length; j++){
epidemicArray[i][j] = charz[j];
}
}
}
This edit should work since the number of columns is the length of one of the string (same length for the 3 of them).
Here is my output
[EDIT]. #magna_nz, I used the following methods to print the array
public static void printRow(int rowNumber) {
for (int i = 0; i < 11; i++) {
System.out.print( epidemicArray[rowNumber][i] + " ");
}
System.out.println();
}
public static void main(String[] args) {
updateArray();
for (int i = 0; i < 3; i++) {
printRow(i);
}
}
This will print the numbers, but if you want to print characters you can change the above printRow method to something like:
public static void printRow(int rowNumber) {
for (int i = 0; i < 11; i++) {
System.out.print( (char)epidemicArray[rowNumber][i] + " ");
}
System.out.println();
}
And this will give you the following result:
You're overwriting your entire epidemicArray with the last value that charz[j] gets. Which is apparently 66. Actually you're overwriting that entire array with every value from charz and the last one won.

trouble with creating a method that returns the average of each column of a 2d array (this is in java)

Im having trouble creating this method because i just started on arrays and now i have to create a method that takes as an input an 2d array of inters and returns one single array that contains the average for each column? can anyone help?
public class Assigment4 {
public static void main(String[] args) {
int[][] a = new int[5][5];
a[0][0] = 1; //rows
a[0][1] = 2;
a[0][2] = 3;
a[0][3] = 4;
a[0][0] = 1; //columns
a[1][0]= 2;
a[2][0] = 3;
a[3][0] = 4;
double []summ =(averageForEachColumn(a));
}
public static double [] averageForEachColumn (int [][] numbers){
double ave [] = new double[numbers[0].length];
int count=0;
for (int i = 0; i < numbers[0].length; i++){
double sum = 0;
count= count+1;
for (int j = 0; j < numbers.length; j++){
count= count +1;
sum += numbers[j][i];
}
ave[i] = sum/count;
System.out.println (sum);
}
return ave;
}
}
Your count should be reset to 0 before the inner loop.
count= count+1; // change this to count = 0;
for (int j = 0; j < numbers.length; j++){
You haven't populated most of the values in the 2d array. There are 16 total values, you have populated 7 of them (one of them twice).
Get rid of count altogether, you don't need it.
Change:
ave[i] = sum/count;
To:
ave[i] = sum/a[i].length;
This is a simplified example of a 2x4 array. You can add more values at you leisure.
public static void main(String[] args)
{
int[][] array = {{1, 2, 3, 4},{5, 6, 7, 8}};
for(int col = 0; col < 4; col++)
{
double sum = 0;
int row = 0;
while (row < array.length)
{
sum+=array[row++][col];
}
System.out.println("Average of values stored in column " + col + " is " + sum / array.length);
}
}
Of course, you can add the result of sum/array.length to an array of averages instead of just displaying it.

Printing pyramid in Java on the console

How can I print a pyramid in Java like this
1
23
456
78910
My current code looks like this:
public class T {
public static void main(String[] args) {
int i, j, num = 1;
int n = Integer.parseInt(args[0]);
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= i; j++) {
System.out.println(num);
num++;
}
System.out.println(" ");
}
}
}
If I try this removing declared i & j then it shows an array out of bounds exception
However 'i' & 'j' are creating the problem. What should my code look like.
int val=1;
for(int i=0;i<6;i++){
for(int j=1;j<i;j++){
System.out.print(val);
val++;
}
System.out.print("\n");
}
initially val is equal to 1 . Inside the first for loop i=0 and j with increase from 1, but when i=0 second for loop doesn't run. then you get the first value as 1. Then it will point to new line.
When i=1,j still 1 so second for loop runs 1 time and print 2, because val has increment(val++). when j=2 in inside for loop it is not running only print the new value (3) of val there.
so on this will work
public static void main(String[] args) {
int num = 1;
//i is how many numbers per row
for(int i = 1; i < 5; i++){
//prints i numbers because j increases from 0 to i, incrementing num each time
for(int j = 0; j < i; j++){
System.out.print(num++);
}
System.out.println();
}
}
This code will work for your purposes.
Now, please read on if you would like to understand Java better and see why the compiler was throwing errors in your code. You shouldn't use stackoverflow to copy in paste someone else's code without understanding it. In your code, you were declaringi and j twice. In Java, you cannot declare a variable twice. You did it first in int i,j, num = 1; and then again in each for loop for (int i = 1; i <= lines; i++). You could correct this by saying for(i = 1; i <= lines; i++). Notice how the int is left out in the second version of the for loop. You can simply assign a value to a variable in a for loop rather than creating a new variable as you do when declare the type int i = 1
The syntax of a for loop is:
for(initialization; Boolean_expression; update)
{
//Statements
}
The initialization step is executed first, and only once. This step allows you to declare and initialize any loop control variables. You are not required to put a statement here, as long as a semicolon appears.
As for the array out of bounds error that you receive, you are trying to read in a command line argument in the statement int n = Integer.parseInt(args[0]); Notice how the main method has a parameter String[] args. These are called command line arguments and can be passed in if you manually run the program from the command line. You were trying to read in args[0] which is outside of the bounds of args[].
In other words, if you run
java MyProgram one two
Then args contains:
[ "one", "two" ]
public static void main(String [] args) {
String one = args[0]; //=="one"
String two = args[1]; //=="two"
}
I suppose you give the number of lines as your only argument, so the code would be
public static void main(String[] args)
{
int lines = Integer.parseInt(args[0]);
int num = 1;
for (int i = 1; i <= lines; i++) {
for (int j = 1; j <= i; j++) {
System.out.print(num);
num++;
}
System.out.println("");
}
}
int l=1;
for (int i=0; i<5; i++)
{
for (int k=0; k<5-i; k++)
{
System.out.print(" ");
}
for (int j=0; j<(i*2)+1; j++)
{
if(j%2!=0){
System.out.print(l++);
}else {
System.out.print(" ");
}
}
System.out.println("");
}
public static void pyramid(int max) {
int num = 1;
max = 4;
for (int row = 0; row < max; row++) {
for (int column = 0; column < max; column++)
System.out.print(column <= row ? num++ : " ");
System.out.println();
}
}
import java.util.Scanner;
/**
*
* #author shelc
*/
public class PrintNumberPyramid {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the count : ");
int number = scanner.nextInt();
//enter the number of rows you want to print
pyramid(number);
}
public static void pyramid(int rows) {
int count = 1;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < rows; j++) {
System.out.print(j <= i ? count++ : " ");
}
System.out.println();
}
}
}

Categories

Resources