Need help centering text output - java

import java.util.Scanner;
public class diamond {
public static void main (String[] args){
Scanner scan = new Scanner(System.in);
System.out.println("Please enter an integer");
int lines = scan.nextInt();
for(int counter = 1; counter <= lines; counter++)
{
if (counter%2 != 0)
{
for(int count2 = 1; count2 <= counter; count2++){
System.out.print("*");
}
System.out.println();
}
}
}
}
I am supposed to ask the user for a number of lines and output a diamond made of asterisks that number of lines tall. I need some help figuring out how to center the asterisks. I know for strings there is some String.utils method or something, but the output comes in pieces based on a for loop, so I don't think that really works here. If it does, by all means let me know though.

You need to print a certain amount of spaces before each line. Then, you would need another for loop for the opposite.
Try this code:
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Please enter an integer ");
int lines = scan.nextInt();
for (int counter = 1; counter <= lines; counter++) {
if (counter % 2 != 0) {
for (int i = 0; i < lines - (counter / 2) - 3; i++) {
System.out.print(" ");
}
for (int count2 = 1; count2 <= counter; count2++) {
System.out.print("*");
}
System.out.println();
}
}
for (int counter = lines - 1; counter >= 1; counter--) {
if (counter % 2 != 0) {
for (int i = 0; i < lines - (counter / 2) - 3; i++) {
System.out.print(" ");
}
for (int count2 = 1; count2 <= counter; count2++) {
System.out.print("*");
}
System.out.println();
}
}
}

I think you should prepare a string to print out on each line, then you will know exactly how many characters it has, when the line increases, remove the two '*' in center of the string and add one " " in front of it, then print it out again.

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

2D array scanner validation

Anyone able to steer me in the right direction. I am building a simple mark program where I get input from Scanner and insert it into my 2D array. I want to validate my input so that it isn't below 0 or above 100 but if I have the incorrect number I don't want the array to move to next position.
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);//naming the scanner
String [] student = {"Mark","Jen","Gaby","John","Michael","James"};
String [] subject = {"Digital electronics","Analogue electronics","Maths","Networks","Telecommunications",
"Computer applications","Software developemnt","Workshop"};
String [] printSub = {"Digit","Analo","Maths","Netwo","Telec","Appli","Softw","Works"};
int maxRow = 6;//setting max row amount int
int maxCol = 8;//set max column amount int
int [][] mark = new int [maxRow][maxCol];//declaring the int array and setting the row & column max.
int i = 0, j = 0;//declaring i and j for use in the for loops
int maxMark = 0;//declaring for use in if statement to find highest mark
int minMark =100;//Declaring for use in if statement to find lowest mark
for(i = 0; i < maxRow; i++)
{
for(j = 0; j < maxCol; j++)
{
System.out.print("Please enter "+student[i]+" mark for "+subject[j]+" and press return :");
mark[i][j]= input.nextInt();
}
}
for(i=0; i < maxRow; i++)
{
for(j=0; j < maxCol; j++)
{
if (i == 0 && j == 0)
{
System.out.print("Student \t");
for(int sub = 0; sub < 8; sub++)
{
System.out.print(printSub [sub]+"\t");
}
System.out.println();
System.out.println();
}
if(i < maxRow && j == 0)
{
System.out.print(student[i]+"\t \t ");
}
System.out.print(mark [i][j]+"\t");
}
System.out.println();
System.out.println();
}
}
I am not looking for the answer i am looking for more of a nudge in the direction where I may be able to figure out the answer myself.
Thanks for the help in advance.
Matt
Nudge : You do not directly insert number into array, you insert it into some temporary variable, checks it and then decide if you save it or you ask again (while cycle needed)
Spoiler 1 : Here is complete solution, if you want to do it yourself, do not look there :) :
for (i = 0; i < maxRow; i++) {
for (j = 0; j < maxCol; j++) {
System.out.print("Please enter ");
int number = input.nextInt();
boolean isItOk = false;
while (isItOk == false) {
if (number < 0 || number > 100) {
System.out.println("You shall not insert a value below 0 or bigger than 100! Try it again");
number = input.nextInt();
} else {
isItOk = true;
}
}
mark[i][j] = number;
}
}
Spoiler 2 : This is a little nicer code, but for beginners, I would recommend the approach of Spoiler 1, because it is always usable. In more complex problems, the Spoiler 2 solution is not always possible.
for (i = 0; i < maxRow; i++) {
for (j = 0; j < maxCol; j++) {
System.out.print("Please enter ");
int number = input.nextInt();
while (number < 0 || number > 100) {
System.out.println("You shall not insert a value below 0 or bigger than 100! Try it again");
number = input.nextInt();
}
mark[i][j] = number;
}
}
Scanner s = new Scanner(System.in);
int number =0;
System.out.print("Please enter ");
while(true)
{
number = s.nextInt();
if(number > -1 && number < 101)
break;
System.out.println("Marks should be between 0 and 100, Please enter");
}
You also need to validate if input is integer, which can be done through exception handling

Limiting my output with an array

My question has to do with counting integers in an array. This is my code so far.
import java.util.Scanner;
public class Frequency {
public static void main(String[]args) {
Scanner kbd = new Scanner(System.in);
System.out.print("enter numbers: ");
int[] arr = new int[51];
for(int i = 0; true; i++) {
int in = kbd.nextInt();
if(in < 0)break;
else if(in > 50)break;
else arr[in]++;
}
for(int i = 0; i < arr.length; i++) {
System.out.println(i+" occurrences of "+arr[i]);
}
}
}
The way the problem outputs is correct except I need some way of filtering out all the numbers that have an occurrence of 0 so that only numbers that were in the input show in the output; instead of every number between 0 and 50.
You have already written an if statement, to stop your first loop when user enters a negative number. Simply write the same thing for your second loop:
for(int i = 0; i < arr.length; i++) {
if (arr[i] > 0) {
System.out.println(arr[i]+" occurrences of "+i);
}
}
Side-note: I have also swapped arr[i] and i
for(int i = 0; i < arr.length; i++) {
if(!(i==0 || i%10==0) && arr[i]!=0)
System.out.println(i+" occurrences of "+arr[i]);
}

how to display two-dimensional array in rectangular output?

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("");
}

Categories