how to display two-dimensional array in rectangular output? - java

This is not homework. I am a beginner (novice) java programmer, trying to read and complete the exercises at the end of ivor horton's beginning java book.
Write a program to create a rectangular array containing a multiplication table from 1 X 1 to 12 X 12. Output the table as 13 columns with the numeric values right aligned in columns. (The first line of output will be the column headings, the first column with no heading, then the numbers 1-12 for the remaining columns. The first item in each of the succeeding lines is the row heading which ranges from 1-12.
NOTE: I have only learned about Arrays & Strings, Loops & Logic, data types, variables, and calculations. I have not learned about classes and their methods and etc......so no fancy stuff please. THANKS!
public class Chapter4Exercise2 {
public static void main(String[] args)
{
int[][] table = new int[12][12];
for(int i=0; i <= table.length-1; i++)
{
for (int j=0; j <= table[0].length-1; j++)
{
table[i][j] = (i + 1) * (j + 1);
if (table[i][j] < 10)
System.out.print(" " + table[i][j] + " ");
else
if (table[i][j] > 10 && table[i][j] < 100)
System.out.print(" " + table[i][j] + " ");
else
System.out.print(table[i][j] + " ");
}
System.out.println(" ");
}
}
}

As long as the numbers are less than 1000, try this:
As #Mr1158pm said:
public class Chapter4Exercise2 {
public static void main(String[] args) {
int tableSize = 10;
int[][] table = new int[tableSize][tableSize];
for(int i=0; i < table.length; i++) {
for (int j=0; j < table[i].length; j++) {
table[i][j] = (i+1)*(j+1);
if(table[i][j] < 10) //Where i*j < 10
System.out.print(" "+(table[i][j])+" ");
else if(table[i][j] < 100) //Where i*j < 100
System.out.print(" "+(table[i][j])+" ");
else //Where i*j < 1000
System.out.print(" "+(table[i][j])+" ");
}
System.out.println("");
}

I don't think that you have to declare an array data structure to print out this table.
Just use two nested for loops and do calcs in the loops.
Here is a working method that you can work on. Just need to fix column alignment, add space here and there.
FYI row<10?" "+row:row is a form on inline if statement. If you haven't seen it before google it. It's quite useful.
public static void main(String[] args) {
for(int row=0; row<13; row++)
{
for(int col=0; col<13; col++)
{
if(row==0) //ffirst row
{
if(col==0)
System.out.print(" ");
else
System.out.print(col<10?" "+col:" "+col);
}
else
{
if(col==0)
System.out.print(row<10?" "+row:row);
else
System.out.print(row*col<10?" "+(row*col):(row*col<100? " "+(row*col):" "+(row*col)));
}
}
System.out.println();
}
}

import java.util.Scanner;
public class Back {
public static void main(String[] args) {
Scanner a1 =new Scanner(System.in);
int row,col;
String ch;
System.out.println("Enter width of screen:");
row = a1.nextInt();
System.out.println("Enter height of screen:");
col = a1.nextInt();
System.out.println("Enter background character:");
ch =a1.next();
String twoD[][] = new String[row][col];
int i,j;
for(i=0;i<row;i++)
for(j=0;j<col;j++){
twoD[i][j] = ch;
}
for(i=0;i<row;i++){
for(j=0;j<col;j++)
System.out.print(twoD[i][j]+" ");
System.out.println();
}

int width = 10;
int height = 10;
int[][] table = new int[width][height];
for(int i = 0; i < width; i++) {
for(int j = 0; j < height; j++) {
System.out.print(" " + table[i][j] + " ");
}
System.out.println("");
}

Related

Rhombus with letters - Java

I am new to programming and started with learning c# and now java. I came across a task creating a rhombus where the user inputs the height (odd numbers only) and the char for the rhombus.
I created a for loop for the height and another loop for the characters. Here is my output:
h: 7
c: k
k
jkj
ijkji
hijkjih
ghijkjihg
But I want the output to be:
h: 7
c: k
k
jkj
ijkji
hijkjih
ijkji
jkj
k
How can I develop my logic to apply it to my code.
Here is my code:
Scanner in = new Scanner(System.in);
System.out.print("h: ");
int h = in.nextInt();
System.out.print("c: ");
char c = in.next().charAt(0);
if(h%2==0){
System.out.println("Invalid number!");
return;
}
int count = 1;
int space = 1;
for (int i = 2; i < h; i++)
{
for (int spc = h - space; spc > 0; spc--)
{
System.out.print(" ");
}
if (i < h)
{
space++;
}
else {
space--;
}
for (int j = 0; j < count; j++)
{
System.out.print(c);
if (j < count/2)
{
c++;
}
else {
c--;
}
}
if (i < h)
{
count = count + 2;
}
else {
count = count - 2;
}
System.out.println();
}
Any help is highly appreciated.
Your code contains the following flaws:
count and space variables depend on the values of i and h, which makes it very hard to keep track of and understand. You should avoid hidden dependencies in your code in general
you change the value of c all the time. It makes it very hard to keep track of. You should never change its value
your function is too big
strange values like i = 2, count/2, incrementing by 2
incorrect conditions
You have one loop which increments i. What you need is a second loop which decrements the value of i. And you should also use the same approach for printing of the characters (2 loops for both sides). Let me show you:
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
// load parameters
System.out.print("h: ");
int h = in.nextInt();
System.out.print("c: ");
char c = in.next().charAt(0);
// validate parameters
if (h % 2 == 0) {
System.out.println("Invalid number!");
return;
}
for(int i = 0; i <= h/2; i++) {
printSpaces((h+1) / 2 - i - 1);
printLine(c, i);
System.out.println();
}
for(int i = h/2-1; i >= 0; i--) {
printSpaces((h+1) / 2 - i - 1);
printLine(c, i);
System.out.println();
}
}
private static void printLine(char character, int sideWidth) {
for (int j = sideWidth; j >= 0; j--)
System.out.print((char) (character - j));
for (int j = 1; j <= sideWidth; j++)
System.out.print((char) (character - j));
}
private static void printSpaces(int numberOfSpaces) {
for (int i = 0; i < numberOfSpaces; i++) {
System.out.print(" ");
}
}
which gives you the desired output.
public class Rhombusstar
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter N : ");
int n=sc.nextInt();
System.out.print("Enter Symbol : ");
char c = sc.next().charAt(0);
for(int i=1;i<=n;i++)
{
for(int j=1;j<=n-i;j++)
{
System.out.print(" ");
}
for(int j=1;j<=n;j++)
{
System.out.print(c);
}
System.out.println();
}
}
}

How to print a multiplication table in java

I have to create a program that prints a times table that
1)Has multiple methods.
2)Reads in two numbers where one is the upper limit and the second will be how deep the table goes (rows and columns essentially). It's a step up from the restriction of just square tables where it can only be, for example, 10x10 or 12x12.
3)Has a loop so that the user can run it again with different input.
4)Use Scanner to read I/P.
The output is supposed to look like this when you input 3 for the first number and 8 for the second number:
But it comes out like this: Output
import java.util.Scanner;
public class TimesTableRewrite
{
public static void main (String[] args)
{
Scanner in;
in = new Scanner (System.in);
boolean runAgain = false;
header();
String response;
do
{
printTable();
System.out.println("\nDo you want to go again? Y or N?");
response = in.next();
if ((response.charAt(0)=='Y'||response.charAt(0)=='y'))
{
runAgain = true;
}
else
{
runAgain = false;
}
}
while (runAgain);
footer();
}
public static void printTable()
{
Scanner in;
in = new Scanner (System.in);
int height;
int length;
System.out.println("Enter the first number to set up how far down you want the table to go.");
height= Integer.parseInt(in.next());
System.out.println("Enter the second number to extend the table horizontally");
length = Integer.parseInt(in.next());
for (int i = 1; i <= height; i++ )
{
for (int j = 1; j <= length; j++ ) //j is number of columns
{
if (i<height)
System.out.format("%4d", + i*j);
else
System.out.format("%4d", + i*j);
if (i==height)
{
System.out.println();
}
}
}
for (int i = 1; i <= height; i++ )
{
for (int j = 1; j <= length; j++ )
{
if (j<length)
System.out.format("%4d", + i*j);
else
System.out.format("%4d", + i*j);
if (j==length)
{
System.out.println();
}
}
}
}
public static void header()
{
System.out.println("This program will help you practice your times tables!");
System.out.print("This newer version will allow you to go beyond the 12 times tables!");
System.out.println("It will let you choose your upper limit \nand how deep the times table will go.");
System.out.println("Let's go!");
System.out.println("\nPlease enter two numbers to generate a multiplication table.");
}
public static void footer ()
{
System.out.println("That's all folks! See you next week!");
}
}
Replace this:
for (int i = 1; i <= height; i++ )
{
for (int j = 1; j <= length; j++ ) //j is number of columns
{
if (i<height)
System.out.format("%4d", + i*j);
else
System.out.format("%4d", + i*j);
if (i==height)
{
System.out.println();
}
}
}
for (int i = 1; i <= height; i++ )
{
for (int j = 1; j <= length; j++ )
{
if (j<length)
System.out.format("%4d", + i*j);
else
System.out.format("%4d", + i*j);
if (j==length)
{
System.out.println();
}
}
}
With this:
for (int i = 1; i <= height; i++ )
{
for (int j = 1; j <= length; j++ ) //j is number of columns
{
System.out.print(i * j);
System.out.print("\t"); //We add a tab after each number to form every column.
}
System.out.println(); //We add a berakline for each row.
}

Output of 50 - broken up to 10 numbers per line

I am struggling trying to find a way to output this array/loop so that only 10 outputs appear on a line.
public static void main(String[] args) {
double [] alpha = new double[50];
int num=1;
for (int i=0; i < alpha.length; i++) {
alpha[i] = num; //populate index 0-50 w/ 1-50
num++;
if (alpha[i] < 26) // first 25, print ^2
System.out.print(Math.pow(alpha[i],2)+ " ");
else // last 25, print value(3)
System.out.print(alpha[i]*3 + " ");
}
System.exit(0);
}
Add a conditional that prints a break line if i + 1 is multiple of 10.
for (int i=0; i < alpha.length; i++) {
//your code here...
if ( (i + 1) % 10 == 0) {
System.out.println();
}
}
Another way of doing it could be to iterate over the lines u want to print:
// Get the total number of lines you want
int lines = len(alpha) % 10;
for (int i=0; i < lines; i ++) {
for (int j = i * lines; j < i * lines + 10; j++) {
// Print the modified alpha[j]
System.out.print(alpha[j]);
}
System.out.println();
}

Make smaller christmas tree

So I'm beginning in the world of java programming language and I'm trying to print a christmas tree of X height. So far its working, but if for example the user input 4, it will print 4 rows + the christmas tree stump, wich mean 5. However, I would like it to be 4 INCLUDING the stump.So far I have this:
public class xmas {
public static void main(String[] args)
{
Scanner scan = new Scanner(in);
out.print("please enter a number: ");
int temp = scan.nextInt();
int x = (temp-1)*2 +1;
int y = x/2;
int z = 1;
for(int i=0; i<temp; i++)
{
for(int j=0; j<=y; j++)
{
out.print(" ");
}
for(int k = 0; k<z; k++)
{
out.print("*");
}
out.println();
y--;
z+=2;
}
for(int i =0; i<=x/2; i++)
{
out.print(" ");
}
out.println("*");
}
}
I don't know how to do that. Thanks!
Try using temp-- just after the input, like that:
int temp = scan.nextInt();
temp--;
Or decreasing your loop condition:
for(int i=0; i<temp-1; i++)
Output in both cases:
*
***
*****
*
If you just subtract one from the input, your christmas tree should be the right size. Here's what it would look like (using the Java style conventions):
public class ChristmasTree {
public static void main(String[] args) {
Scanner scanner = new Scanner(in);
out.print("Please enter a number: ");
int temp = scanner.nextInt() - 1; // note the `- 1`
int x = (temp - 1) * 2 + 1;
int y = x / 2;
int z = 1;
for(int i = 0; i < temp; i++) {
for(int j = 0; j <= y; j++) {
out.print(" ");
}
for(int j = 0; j < z; k++) {
out.print("*");
}
out.println();
y--;
z += 2;
}
for(int i =0; i<=x/2; i++) {
out.print(" ");
}
out.println("*");
}
}

Output table from 2d array in java

I'm trying to get this data to output as a table, but I haven't been able to make a functional 2d array table with any method I've tried. I'm trying to make a 7x2 matrix for gradeList and devList.
I'm taking pre-initialized and user input data into 3 arrays. I'm trying to make a table out of two of them (and then use the other as labels). nameList would be the label for the rows, and 'grade' and 'deviation' would be the labels for the columns (I haven't tried to set that yet).
I've commented out the first attempt, which output the correct information but couldn't make a readable table. The program compiles, but throws an error any time I run it with the current attempt at a matrix.
Sorry if I've forgotten any useful info and thanks for looking.
//This program determines the mean grade and deviation from that mean for a class of users.
import java.util.Scanner;
public class gradeArrays
{
static Scanner in = new Scanner(System.in);
static int avg;
//array declarations
static String[] nameList = {"Doc","Grumpy","Happy","Sleepy","Dopey","Sneezy","Bashful"};
static int[] gradeList = new int[7];
static int[] devList = new int[7];
//main method
public static void main(String[] args)
{
System.out.println("This program will calculate the mean, and the deviation from that mean, for 7 students.");
getGrades(gradeList);
meanCalc(gradeList);
devCalc(gradeList, avg);
tableOut(gradeList, devList, avg);
}
//input scores from user, method 1
public static int[] getGrades(int[] gradeList)
{
for (int i=0; i < nameList.length; i++)
{
System.out.println("What is the grade for " + nameList[i] + "?");
gradeList[i]= in.nextInt();
}
return gradeList;
}
//calculate average, method 2
public static int meanCalc(int[] gradeList)
{
int sum = 0;
for (int i = 0; i < nameList.length; i++)
{
sum = sum + gradeList[i];
}
if (gradeList.length !=0)
{
avg = sum / gradeList.length;
}
else
{
avg = 0;
}
return avg;
}
//calculate deviation, method 3
public static int[] devCalc(int[] gradeList, int avg)
{
for (int i = 0; i < nameList.length; i++)
{
devList[i] = gradeList[i] - avg;
}
return devList;
}
//output, method 4
public static void tableOut(int[] gradeList, int[] devList, int avg)
{
/*
System.out.println(" Student Grade Deviation");
for (int i = 0; i < nameList.length; i++)
{
System.out.print(" " + nameList[i] + " ");
System.out.print(" " + gradeList[i] + " ");
System.out.printf(" " + "%7d", devList[i]);
System.out.println();
}
System.out.println("The average grade was " + avg + ".");
*/
int[][] outTable = new int[7][2];
for (int row = 0; row < nameList.length; row++)
{
for (int col = 0; col < 3; col++)
{
outTable[row][col] = 21;
}
}
}
}
public static void tableOut(int[] gradeList, int[] devList, int avg)
{
System.out.println("\tStudent\tGrade\tDeviation");
for (int i = 0; i < nameList.length; i++)
{
System.out.print("\t" + nameList[i] + "\t");
System.out.print("\t" + gradeList[i] + "\t");
System.out.printf("\t" + "%7d", devList[i]);
System.out.println();
}
System.out.println("The average grade was " + avg + ".");
int[][] outTable = new int[7][2];
for (int row = 0; row < nameList.length; row++)
{
for (int col = 0; col <2; col++)
{
outTable[row][col] = 21;
}
}
}
This code works properly... Try this.

Categories