(Java) I am making a horizontal Ruler with for loops - java

I'm trying to create a horizontal ruler as shown below:
The code I have right now is:
public class JavaRuler {
public static final int COUNT = 19;
public static void main(String[] args) {
Design();
Inches();
Number();
}
public static void Design() {
for (int j = 1; j <= COUNT * 2 + 2; j++) {
System.out.print("__");
}
System.out.println();
}
public static void Inches() {
for (int i = 1; i <= COUNT * 2 + 2; i++) {
System.out.print("'|");
}
System.out.println();
}
public static void Number() {
for (int k = 1; k <= COUNT; k++) {
System.out.print("___" + k);
}
}
}
The ruler has to be re-sizable in inches and if statements are not allowed (only for loops) my current output is really close but I cant seem to figure out how to decrease the "_" in the third row once the numbers go beyond 9. Any tips?

I think my example here will do the trick
public static void Number() {
for (int k = 1; k <= COUNT; k++) {
System.out.print(("____" + k).substring(("" + k).length()));
}
}
Result
'|'|'|'|'|'|'|'|'|'|'|'|'|'|'|'|'|'|'|'|'|'|'|'|'|'|'|'|'|'|'|'|'|'|'|'|'|'|'|'|
___1___2___3___4___5___6___7___8___9__10__11__12__13__14__15__16__17__18__19

You can refer to this, but the result will be a mess if the COUNT is a big number. I have also updated some of your codes so that the inches and design will not overlap the last number.
public class JavaRuler {
public static final int COUNT = 20;
public static void main(String[] args) {
Design(" ");
Inches();
Number();
Design("|");
}
public static void Design(String s) { // Added parameter
System.out.print(s + "_"); // Added
for (int j = 0; j < COUNT * 2; j++) { // Updated
System.out.print("__");
}
System.out.print(s); // Added
System.out.println();
}
public static void Inches() {
System.out.print("|"); // Added
for (int i = 0; i < COUNT * 2; i++) { // Updated
System.out.print("'|");
}
System.out.print("'|"); // Added
System.out.println();
}
public static void Number() {
System.out.print("|"); // Added
for (int k = 1; k <= COUNT; k++) {
String underScore = " "; // Added
int length = (int) (Math.log10(k - 1) + 1);
for (int i = 1; i < length; i++) {
underScore = underScore.replaceFirst(" ", ""); // Added
}
System.out.print(underScore + k); // Updated
}
System.out.print("|"); // Added
System.out.println();
}
}
Result:
_________________________________________________________________________________
|'|'|'|'|'|'|'|'|'|'|'|'|'|'|'|'|'|'|'|'|'|'|'|'|'|'|'|'|'|'|'|'|'|'|'|'|'|'|'|'|'|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20|
|_________________________________________________________________________________|

I came back to it later today and it hit me! I figured it out!
public class Ruler {
public static final int COUNT = 19;
public static void main(String[] args) {
Design();
Inches();
Numbers();
}
public static void Design() {
for (int j = 1; j <= COUNT * 2 + 2; j++) {
System.out.print("__");
}
System.out.println();
}
public static void Inches() {
System.out.print("|");
for (int i = 1; i <= COUNT * 2 + 2; i++) {
System.out.print("'|");
}
System.out.println();
System.out.print("");
}
public static void Numbers() {
System.out.print("|");
for (int k = 1; k <= 9; k++) {
System.out.print("___" + k);
}
System.out.print("___");
for (int m = 10; m <= COUNT; m++){
System.out.print(m + "__");
}
System.out.print("|");
}
}

Related

can someone help me to print this pattern in java or help me with the logic

5
54
543
5432
54321
I tried to print the pattern above using the following for loop but I don't know why it's not working,
for(int i = 0;i<=5;i++,count = 1,System.out.println()){
for(int j = 5;j>=i;j--)
{
System.out.print("");
}
for (int k = 5;count <=i;count++,k--)
{
System.out.print(k+"");
}
You need something like this:
for (int i = 0; i < 5; i++) {
int count = 0;
for (int j = 5; j >= i; j--) {
System.out.print(" ");
}
for (int k = 5; count <= i; count++, k--) {
System.out.print(k);
}
System.out.println();
}
It prints:
5
54
543
5432
54321
Your mistakes:
At for(int i = 0;i<=5;i++,count = 1,System.out.println()){
This is not a good place for: count = 1,System.out.println()
At System.out.print(""); This doesn't print anything.
At System.out.print(k+""); the +"" is not necessary.
Assuming you need to print pattern for string "54321" only:
public class Answer {
public static void main(String[] args) {
String line = "54321";
for (int i = 1; i <= 5; i++) {
System.out.format("%5s%n", line.substring(0, i));
}
}
}
However you can print any line with this triangular pattern:
public class Answer {
public static void main(String[] args) {
String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
printTriangle(alphabet);
String digits = "9876543210";
printTriangle(digits);
}
private static void printTriangle(String line) {
int lineLen = line.length();
for (int i = 1; i <= lineLen; i++) {
System.out.format("%" + lineLen + "s%n", line.substring(0, i));
}
}
}

How to break a one-dimensional array in rows?

I want to break a one-dimensional array in rows.
Array dimension 50. I need to output the array to the console with 10 elements per line. (lang Java 1.8) Thanks!
public void print() {
for (int i = 0; i < arr.length; i++) {
if (i<=9) {
System.out.print(arr[i] + " ");
}else {
System.out.print("\r");
}
}
}
Sample output
0 1 2 3 4 5 6 7 8 9
10 11 12 13 14 15 16
etc....
You can see it from 2 differents point of view
Each 10 numbers, print a new line : when the index ends with a 9 you reach ten elements so you print a new line println()
public void print() {
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
if (i % 10 == 9) {
System.out.println();
}
}
}
Print enough number of line and on each one : print 10 elements
public void print() {
for (int i = 0; i < arr.length / 10; i++) {
for (int j = 0; j < 10; j++) {
System.out.print(arr[i * 10 + j] + " ");
}
System.out.println();
}
}
Code for any number of elements per line:
public void print(int elementsPerLine) {
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i]);
if (i % elementsPerLine == 0 && i > 0) {
System.out.println();
} else {
System.out.print(" ");
}
}
}
Use the following code,
public static void printResult(int[][] result)
{
for(int i=0; i<5; i++)
{
for(int j=0; j<10; j++)
{
System.out.print(result[i][j] + ", ");
}
System.out.println();
}
}
public static int[][] modifyArray( int[] singleArray )
{
int columns = 10;
int rows = singleArray.length/10;
int[][] result = new int[rows][columns];
for(int i=0; i<rows; i++)
{
for(int j=0; j<columns; j++)
{
result[i][j] = singleArray[columns*i + j];
}
}
return result;
}
public static void main(String[] args)
{
int[] singleArray = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50};
int[][] result = modifyArray( singleArray);
printResult( result );
}
You must use the modulo operator
https://en.wikipedia.org/wiki/Modulo_operation
public void print() {
for (int i = 0; i < arr.length; i++) {
if (i%10 == 0) {
System.out.print("\r");
}else {
System.out.print(arr[i] + " ");
}
}
}
Maybe you could write something like
if (i % 10 == 0)
System.out.print("\r");
}
System.out.print(arr[i] + " ");
Take slices of 10 items into a new array each time and print that array:
int count = 10;
int iterations = (arr.length / count) + ((arr.length % count) > 0 ? 1 : 0);
for (int i = 1; i <= iterations; i++) {
int[] slice = new int[count];
System.arraycopy(arr, (i - 1) * count, slice, 0, i == iterations ? (array.length % count) : count);
System.out.println(Arrays.toString(slice));
}
The above code works for any value of count.
Take a look at a code down below:
public class PrintEach10thElements {
/**
* #param args the command line arguments
*/
static List<Integer> arrays = new ArrayList<>();
public static void main(String[] args) {
//create 50 elements in an array
for (int i = 0; i <= 49; i++) {
arrays.add(i);
}
for (int g = 0; g < arrays.size(); g++) {
if ( arrays.get(g) % 10 != 0) {
System.out.print(arrays.get(g) + " ");
} else {
System.out.println();
System.out.print(arrays.get(g) + " ");
}
}
}
}
If you don't mind using a Guava library, you can also do this
List<Integer> myList = Arrays.asList(myArray);
System.out.println(Lists.partition(myList, 10).stream()
.map(subList -> subList.stream()
.map( Object::toString )
.collect(Collectors.joining(" ")))
.collect(Collectors.joining("\n")));

How can I alter this code so that the output is flipped?

I am making this code that displays a series of asterisks in rows that get smaller by one each time you go down a row. It's supposed to start at 10 and stop at 1 on the very bottom row but for some reason my code starts with 1 at the top and grows bigger as it goes down. I was wondering how I could go about flipping the output so that it looks like the example. Thanks in advance
Example:
**********
*********
********
*******
******
*****
****
***
**
*
My code:
public class RowsOfAsterisks {
public static void main(String[] args) {
// TODO Auto-generated method stub
for (int i = 1; i < 11; i++)
{
for (int x = 0; x < i; x++)
{
System.out.print("*");
}
System.out.println();
}
}
}
You can create another method in order to avoid two for statment
Check if it can help you:
public class RowsOfAsterisks
{
public static String repeat(String str, int times)
{
return new String(new char[times]).replace("\0", str);
}
public static void main(String[] args)
{
for(int i = 10; i > 0; i--)
{
System.out.println(repeat("*", i));
}
}
}
You just have to start the outer loop from 10 to achieve this.
I hope the below code helps you:
public class RowsOfAsterisks {
public static void main(String[] args) {
for (int i = 10; i > 0; i--)
{
for (int x = 0; x < i; x++)
{
System.out.print("*");
}
System.out.println();
}
}
}
int rows = 10;
int columns = 10;
for(int i = 0; i<rows; i++)
{
for(int j = 0; int j < columns; j++)
{
System.out.print("*");
}
System.out.println();
--columns;
}
You're on the right track you just need to fix up the nested loop like so:
public static void main(String[] args) {
for (int i = 1; i < 11; i++)
{
for (int x = 11; x > i; x--)
{
System.out.print("*");
}
System.out.println();
}
}

How to print specified pattern in Java

I want to print the below pattern
v
v v
v v
v v
Below is the code which I have tried.
public static void main(String[] args) {
System.out.println("The Pattern is");
for (int i = 0; i < 4; i++) {
//System.out.println(i);
for (int k = 0; k <= i - 2; k++) {
System.out.print("v ");
}
for (int j = 0; j <= 4 - i; j++) {
System.out.print(" ");
}
System.out.println();
}
}
I'm getting the below output:
v
v v
Can anyone help me to solve this pattern?
Another way to do the job (dynamic number of rows):
public static void main(String[] args) {
final int numRows = 4;
for (int row = 0; row < numRows; row++) {
for (int preSpace = numRows - row; preSpace >= 0; preSpace--) {
System.out.print(" ");
}
if (row > 0) {
System.out.print("v");
for (int postSpace = 1; postSpace < row * 2; postSpace++) {
System.out.print(" ");
}
}
System.out.println("v");
}
}
Move the j loop before k loop
public static void main (String[] args) throws java.lang.Exception
{
System.out.println("The Pattern is");
for(int i=0;i<4;i++) {
for(int j=0;j<=4-i;j++)
System.out.print(" ");
for(int k=0;k<=i-2;k++)
System.out.print("V ");
System.out.println();
}
}
DEMO
The following code will print it
public static void main(String[] args) {
System.out.println("The Pattern is");
// startup parameter
final int rowSize = 4;
final int startPos = 2;
int leftPos = startPos;
int rightPos = startPos;
// for each row
for(int row=0; row<rowSize; row++){
// find and print v (max is right most v)
for(int col=0; col<rightPos+1; col++){
// when reach left pos
if(col==leftPos){
System.out.print("v");
// when left pos and right pos is same
if(leftPos==rightPos){
break;
}
}
// when reach right pos
if (col==rightPos){
System.out.print("v");
break;
}
// print space when it is not match
System.out.print(" ");
}
// next line
System.out.println();
// adjust position
if(leftPos!=0) leftPos--;
rightPos++;
}
}
This works for me:
public class DrawPattern {
public static void main(String[] args) {
int i, j;
int num = 7;
for (i = 0; i < num; i++) {
for (j = 0; j < num; j++) {
if (isConditionMatch(num, i, j)) {
System.out.print("V");
} else {
System.out.print(" ");
}
}
System.out.println();
}
}
// this pattern will decide where to print 'V'
private static boolean isConditionMatch(int num, int i, int j) {
return (i + j == (num - 1) / 2 || j - i == (num - 1) / 2);
}
}
Output:
V
V V
V V
V V

How do I simplify these For-loops to save lines of code? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
The output of the code displays the following:
The code below seems pretty funky to me, even as a newbie. I imagine the code can be done more efficiently or at least lines of code can be saved without having to whip out so many loops.
If anyone can provide a cleaner solution, thanks in advance.
public class diamond {
public static void main(String[] args) {
for (int c=1; c<=10; c++) {
for (int d=1; d<=11-c; d++) {
System.out.print("*");
}
for (int e=2; e<c*2; e++) {
System.out.print(" ");
}
for (int i=1; i<=11-c; i++) {
System.out.print("*");
}
System.out.println();
}
for (int f=2; f<=10; f++) {
for (int g=1; g<=f; g++) {
System.out.print("*");
}
for (int h=2; h<22-f*2; h++) {
System.out.print(" ");
}
for (int j=1; j<=f; j++) {
System.out.print("*");
}
System.out.println();
}
}
}
The key is to notice repetitive patterns in your code and factor it out.
You could use a helper method to print a series of N characters:
public static void printNTimes(char value, int n) {
for (int i = 0; i < n; i++) {
System.out.print(value);
}
}
You can generalize the approach by using constants for the characters involved and the size of the diamond.
private static final char OuterChar = '*';
private static final char InnerChar = ' ';
private static final int Size = 10;
And add another helper method to print a row with N instances of one character on the outside, and 2 * (Size - N) characters on the inside:
private static void printRow(int n) {
printNTimes(OuterChar, n);
printNTimes(InnerChar, (Size - n) * 2);
printNTimes(OuterChar, n);
System.out.println();
}
Your code then becomes:
public class diamond
{
private static final char OuterChar = '*';
private static final char InnerChar = ' ';
private static final int Size = 10;
public static void printNTimes(char value, int n) {
for (int i = 0; i < n; i++) {
System.out.print(value);
}
}
private static void printRow(int n) {
printNTimes(OuterChar, n);
printNTimes(InnerChar, (Size - n) * 2);
printNTimes(OuterChar, n);
System.out.println();
}
public static void main(String[] args) {
for (int c = Size; c >= 1; c--) {
printRow(c);
}
for (int c = 2; c <= Size; c++) {
printRow(c);
}
}
}
int max=9,min=10;
for(int i=0;i<19;i++){
for(int j=0;j<20;j++){
if(j<min || j>max){
System.out.print("*");
}
else{
System.out.print(" ");
}
}
if(i<9){
min--;
max++;
}
else {
min++;
max--;
}
System.out.println();
}
I find this rather clear but YMMV.
for( int i = 10; i >= 1; i-- ){
String s = "**********".substring(0, i);
System.out.printf( "%-10s%10s\n", s, s );
}
for( int i = 1; i <= 10; i++ ){
String s = "**********".substring(0, i);
System.out.printf( "%-10s%10s\n", s, s );
}
Since this is repeated within the loop:
for (int d=1; d<=11-c; d++)
{
System.out.print("*");
}
you could write it to a variable and print it out twice. That would eliminate two loops. (one subloop in each outer loop)
I like to wrap logic in code that is easy to read and maintain so instead of doing loads of nested for-loops I wrote a class with descriptive methods.
package se.wederbrand.stackoverflow.diamond;
import java.util.ArrayList;
import java.util.List;
public class Diamond {
final List<String> rows;
public static void main(String[] args) {
System.out.println(new Diamond(10));
}
public Diamond(int width) {
this.rows = new ArrayList<>();
for (int stars = 1; stars <= width; stars++) {
// add all rows, start from the middle and build around it
addRows(stars, width);
}
}
private void addRows(int stars, int width) {
String row = generateRow(stars, width);
// add on top
this.rows.add(0, row);
if (stars > 1) {
// add to bottom
this.rows.add(row);
}
}
private String generateRow(int stars, int width) {
String row = "";
int spaces = width - stars;
for (int j = 0; j < stars; j++) {
row += "*";
}
for (int j = 0; j < spaces; j++) {
row += " ";
}
for (int j = 0; j < stars; j++) {
row += "*";
}
return row;
}
#Override
public String toString() {
String diamond = "";
for (String row : rows) {
diamond += row + System.lineSeparator();
}
return diamond;
}
}
This is an fun question as you get to see how everybody takes a different approach to solving it. This way just gives you a string that is "padded" with another character on the other side.
public static void main(String[] args) {
for (int c = 1; c <= 10; c++) {
System.out.println(printPadded(11 - c, '*', (c - 1) * 2, ' '));
}
for (int f = 10; f >= 2; f--) {
System.out.println(printPadded(11 - f, '*', (f - 1) * 2, ' '));
}
}
public static String printPadded(int padCount, char padCharacter,
int middleCount, char middleCharacter) {
StringBuilder s = new StringBuilder(padCount * 2 + middleCount);
for (int i = 0; i < padCount; i++) {
s.append(padCharacter);
}
for (int i = 0; i < middleCount; i++) {
s.append(middleCharacter);
}
for (int i = 0; i < padCount; i++) {
s.append(padCharacter);
}
return s.toString();
}

Categories