In the below code block:
public static void main(String[] args) {
int i;
int x = 0;
int count;
int sum = 0;
Scanner scan = new Scanner(System.in);
System.out.println("Enter The Table Operator (+, -, *, /, %, or R)");
String operator = scan.nextLine();
System.out.println("Enter The Smallest Operand For the Table:");
int small = scan.nextInt();
System.out.println("Enter The Largest Operand For the Table");
int large = scan.nextInt();
for(i = 0; i < 12; i++) {
for(x = 0; x <= large; x ++)
System.out.printf("%4d", x + small);
System.out.printf("\n");
x++;
large++;
}
}
The code outputs:
1 2 3 4 5 6 7 8 9 10 11 12 13
1 2 3 4 5 6 7 8 9 10 11 12 13
1 2 3 4 5 6 7 8 9 10 11 12 13
1 2 3 4 5 6 7 8 9 10 11 12 13
1 2 3 4 5 6 7 8 9 10 11 12 13
1 2 3 4 5 6 7 8 9 10 11 12 13
1 2 3 4 5 6 7 8 9 10 11 12 13
1 2 3 4 5 6 7 8 9 10 11 12 13
1 2 3 4 5 6 7 8 9 10 11 12 13
1 2 3 4 5 6 7 8 9 10 11 12 13
1 2 3 4 5 6 7 8 9 10 11 12 13
1 2 3 4 5 6 7 8 9 10 11 12 13
but I want it to look like this:
1 2 3 4 5 6 7 8 9 10 11 12 13
2 3 4 5 6 7 8 9 10 11 12 13 14
3 4 5 6 7 8 9 10 11 12 13 14 15
4 5 6 7 8 9 10 11 12 13 14 15 16
5 6 7 8 9 10 11 12 13 14 15 16 17
6 7 8 9 10 11 12 13 14 15 16 17 18
7 8 9 10 11 12 13 14 15 16 17 18 19
8 9 10 11 12 13 14 15 16 17 18 19 20
9 10 11 12 13 14 15 16 17 18 19 20 21
10 11 12 13 14 15 16 17 18 19 20 21 22
11 12 13 14 15 16 17 18 19 20 21 22 23
12 13 14 15 16 17 18 19 20 21 22 23 24
It's basically an addition table. I'm trying to get the x value and the value of "large" to implement by one on each loop. I'm pretty sure I'm using the for loop incorrectly but I haven't been able to find out how.
for (int row = 1; row <= 12; row++) {
for (int col = row; col < row + 13; col++)
System.out.print(col != row ? " " + col : col);
System.out.println();
}
This pretty simple trianlge. Just inline all temporary variables like row and 'col' into the loops. Be simple.
int large = 10;
int small = 0;
int x,i;
for( i = 0; i < large; i++) {
for( x = 1; x <= large; x ++)
System.out.printf("%d ", x + small);
System.out.printf("\n");
x++;
small++;
}
Change "%4d" to "%d ". %4d makes every number 4 spaces long no matter what but you wanted the number and one space.
The last line in your outer for-loop should be small++ instead of large++ to offset the start value each time.
Your loop looks right. You are incrementing the wrong variables.
for(i = 0; i < large; i++) {
for(x = 0; x <= large; x ++){
System.out.printf("%4d", x + small);
}
System.out.printf("\n");
small++;
}
output:
1 2 3 4 5 6 7 8 9 10 11 12 13
2 3 4 5 6 7 8 9 10 11 12 13 14
3 4 5 6 7 8 9 10 11 12 13 14 15
4 5 6 7 8 9 10 11 12 13 14 15 16
5 6 7 8 9 10 11 12 13 14 15 16 17
6 7 8 9 10 11 12 13 14 15 16 17 18
7 8 9 10 11 12 13 14 15 16 17 18 19
8 9 10 11 12 13 14 15 16 17 18 19 20
9 10 11 12 13 14 15 16 17 18 19 20 21
10 11 12 13 14 15 16 17 18 19 20 21 22
11 12 13 14 15 16 17 18 19 20 21 22 23
12 13 14 15 16 17 18 19 20 21 22 23 24
int small = 1;
int large = 12;
for(int i = 0; i < 12; i++) {
for(int x = i; x <= i + large; x ++)
{
System.out.printf("%4d", x + small);
}
System.out.printf("\n");
}
checkout this simple change by changing the x ranges from i -> i + large which will avoid increment large ( because it is not need as in every iteration i also increase)
what you are trying to is in every iteration of i and x you are increment it at the end of the print operation that wont effect exactly as you want because for every iteration the value you print should iterate and print so change the x value to i, which will get incremented in every iteration and use it till i + large (where large is the number you obtain as maximum limit)
Note this can be achieved since small, and large are constant through out the loop
Related
I want to ask a question or a probable favor on how am I going to make my program coding "do-while loop" in creating a Triangular Multiplication. Is there a probable way on to create such thing without using any other statement?
public class Main {
static void ssbr(int n) {
int i = 1;
do{
System.out.printf("%4d", n * i);
i = i + 1;
} while(i <= 7);
System.out.println("");
}
public static void main(String[] args) {
int i = 1;
do{
ssbr(i);
i = i + 1;
} while (i <= 7);
}
}
Output it gave:
1 2 3 4 5 6 7
2 4 6 8 10 11 12
3 6 9 12 15 18 21
4 8 12 16 20 24 30
5 10 15 20 25 30 35
6 12 18 24 30 36 42
7 14 21 28 35 42 49
Output I wanted:
1
2 4
3 6 9
4 8 12 16
5 10 15 20 25
6 12 18 24 30 36
7 14 21 28 35 42 49
You can do it with the following algorithm:
You have to do it 7 times and therefore you can use a loop that should run 7 times.
Each row starts with the row number, and run for row number * row number times with a step-value equal to the row number.
Given below is the implementation of this algorithm using for loop and I leave it to you to implement it using the do-while loop (as it seems to be your homework 😀)
public class Main {
public static void main(String[] args) {
int n = 7;
for (int row = 1; row <= n; row++) {
for (int col = row; col <= row * row; col += row) {
System.out.printf("%-4d", col);
}
System.out.println();
}
}
}
Output:
1
2 4
3 6 9
4 8 12 16
5 10 15 20 25
6 12 18 24 30 36
7 14 21 28 35 42 49
My purpose is a java app that takes a number from a user. Start 1 and write it to console. Each new line series will increase 1 until the number token from the user. The important thing is to align each line to the right side.
Scanner in = new Scanner(System.in);
int numberOfLines = in.nextInt();
for (int rows = 1; rows <= numberOfLines; rows++) {
for (int i = numberOfLines - rows; i >= 1; i--) {
System.out.print(" ");
}
for (int col = rows; col >= 1; col--) {
System.out.printf(" %d",col);
}
System.out.println();
}
1
2 1
3 2 1
4 3 2 1
5 4 3 2 1
6 5 4 3 2 1
7 6 5 4 3 2 1
8 7 6 5 4 3 2 1
9 8 7 6 5 4 3 2 1
10 9 8 7 6 5 4 3 2 1
11 10 9 8 7 6 5 4 3 2 1
when reaching double-digit numbers it is not right-aligned text. I tried to use the if condition in the loop but I could not do it.
Here's a different way to think about it using String concatenation.
You could generate the last row, first, to determine the maximum width that each row must be. Then for each row, you count backwards from the current row number down to 1 so you know the width of just the numbers part. Finally, you prepend the number of spaces needed to make the current row as wide as the last row. Note that is a horribly inefficient use of Strings, but really I'm demonstrating a different algorithm. Making this memory efficient would just make it harder to understand. Also note that the output being rendered correctly is dependent upon the environment in which you are running, and how it displays long strings. Some systems will add a scrollbar, while others may cause the strings to wrap.
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Number of rows? ");
int numberOfLines = in.nextInt();
if (numberOfLines >= 1) {
int totalWidth = 0;
// add up the widths of the numbers themselves
for (int number = 1; number <= numberOfLines; number++) {
totalWidth = totalWidth + ("" + number).length();
}
// add in the spaces in-between the numbers
totalWidth = totalWidth + (numberOfLines - 1);
// now generate each row by counting backwards from the current row number
for (int rowNumber = 1; rowNumber<=numberOfLines; rowNumber++) {
String row = "";
for (int i=rowNumber; i>=2; i--) {
row = row + i + " ";
}
row = row + "1";
// prepend the spaces in front to make it as wide as the last row
int paddingLength = totalWidth - row.length();
for(int i=1; i<=paddingLength; i++) {
row = " " + row;
}
// output the row
System.out.println(row);
}
}
else {
System.out.println("Number of rows must be positive!");
}
}
Sample output with 25 rows:
Number of rows? 25
1
2 1
3 2 1
4 3 2 1
5 4 3 2 1
6 5 4 3 2 1
7 6 5 4 3 2 1
8 7 6 5 4 3 2 1
9 8 7 6 5 4 3 2 1
10 9 8 7 6 5 4 3 2 1
11 10 9 8 7 6 5 4 3 2 1
12 11 10 9 8 7 6 5 4 3 2 1
13 12 11 10 9 8 7 6 5 4 3 2 1
14 13 12 11 10 9 8 7 6 5 4 3 2 1
15 14 13 12 11 10 9 8 7 6 5 4 3 2 1
16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1
17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1
18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1
19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1
20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1
21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1
22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1
23 22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1
24 23 22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1
25 24 23 22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1
Your code is doing the job just fine. The one problem you have, is that it stops working properly once you get to numbers that are more than 1 digit large: In your example, the 10 and the 11.
It's actually kind of tricky to fix that - what if I input '120392'?
You have a few options. Each option is more amazing, but also requires more code.
Restrict your input. For example, disallow inputs beyond 99, and assume all numbers have a # of digits equal to the largest allowing numbers (so, 2 digits).
Calculate the # of digits in the input, then assume all numbers have the calculated # of digits.
Just get it right, with the spacing being applied increasing as numbers grow digits.
If you choose the first or second option, you'd get something like:
1
2 1
3 2 1
4 3 2 1
5 4 3 2 1
6 5 4 3 2 1
7 6 5 4 3 2 1
8 7 6 5 4 3 2 1
9 8 7 6 5 4 3 2 1
10 9 8 7 6 5 4 3 2 1
11 10 9 8 7 6 5 4 3 2 1
Note how this has way more spaces than your example (2 spaces in between e.g. every 4 and 3 instead of 1.
So, how? For #1 and #2, you need System.out.printf("%2d"); - this means: print a number, but if it takes fewer than 2 characters to do so, left-pad with spaces.
For #1 you hardcode the '2' (and hardcode a 99 limit; alternatively, hardcode 3 spaces, and a 999 limit). For #2 you get your input and then figure out how many digits that is. Something like String.valueOf(limit).length(); will do that, then you construct the format string using this length.
For #3 you track which number you're not printing in your System.out.print(" "); loop, so that you can still figure out how long the blank space you need to make has to be: If you're not printing a 10, you need 3 spaces. If you're not printing a 500, you'd need 4. If you're not printing a 5, you need 2.
For #2 and #3: printf("%4s", ""); prints 4 spaces. This is what you'd use to ask java to print X number of spaces. You're going to need this for solutions #2 and #3.
This sounds like first-week homework. I think #1 is most appropriate.
In order to make the 2 digits right aligned ,one of the ways would be- after the for loop of 'col' convert each digit to String then reverse it then after that print it . If u don't convert it to String then numbers like 10,20,30,etc would be printed as 1,2,3,etc
for (int rows = 1; rows <= numberOfLines; rows++) {
for (int i = numberOfLines - rows; i >= 1; i--) {
System.out.print(" ");
}
for (int col = rows; col >= 1; col--) {
if(col>9){
COL=Integer.toString(col);
for(int i=COL.length();i>=0;i--)
rev=rev+COL.charAt(i);
System.out.printf(" %d",rev);
}
else
System.out.printf("%d",col);
}
System.out.println();
}
This question already has answers here:
Pascal's Triangle Format [duplicate]
(8 answers)
Closed 3 years ago.
I have to print Pascal's Triangle, so it should have number 1 on each side, and format of triangle should be even on each side (now it's longer on the right side). My code:
public static void main(String[] args) {
printPascalTriangle(10);
}
public static void printPascalTriangle(int size) {
for (int i = 0; i <= size; i++) {
System.out.println();
for (int j = 0; j <= (size - i); j++) {
System.out.print(" ");
}
for (int j = 0; j <= i; j++) {
System.out.print(" " + (i + j));
}
}
}
And the output is:
0
1 2
2 3 4
3 4 5 6
4 5 6 7 8
5 6 7 8 9 10
6 7 8 9 10 11 12
7 8 9 10 11 12 13 14
8 9 10 11 12 13 14 15 16
9 10 11 12 13 14 15 16 17 18
10 11 12 13 14 15 16 17 18 19 20
Why it doesn't sum up? And why loop doesn't format spaces properly?
You should use printf method instead of print with proper arguments to format your output:
public static void main(String[] args) {
printPascalTriangle(10);
}
public static void printPascalTriangle(int rows) {
for (int i = 0; i < rows; i++) {
int number = 1;
System.out.printf("%" + (rows - i) * 2 + "s", "");
for (int j = 0; j <= i; j++) {
System.out.printf("%4d", number);
number = number * (i - j) / (j + 1);
}
System.out.println();
}
}
Output:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
1 6 15 20 15 6 1
1 7 21 35 35 21 7 1
1 8 28 56 70 56 28 8 1
1 9 36 84 126 126 84 36 9 1
The code below is the answer I wrote for a question that asks to rotate an n x n 2D matrix by 90 degrees (clockwise), without creating a new 2D array. So for example,
Given input matrix =
[
[1,2,3],
[4,5,6],
[7,8,9]
],
rotate the input matrix:
[
[7,4,1],
[8,5,2],
[9,6,3]
]
I tried to do it row by row, but the problem I have to deal with is what to do if the pair of index if already altered. So if I try to assign index pair [1, 2] to [0, 1], but then [0,1] is already changed before. The solution I came up with is to use a HashMap, put the index pair in an array as key, and the original number as value.
Here is my code
public void rotate(int[][] matrix) {
int n = matrix.length;
HashMap<int[], Integer> map = new HashMap<>();
for(int i = 0; i < n; i++){
for (int j = 0; j < n; j++){
if(map.containsKey(new int[]{n-j,i})){
matrix[i][j] = map.get(new int[]{n-j, i});
}
else{
int temp = matrix[i][j];
matrix[i][j] = matrix[n-j][i];
map.put(new int[]{n-j,i}, temp);
}
}
}
}
However, the result shows that
if(map.containsKey(new int[]{n-j,i})){
matrix[i][j] = map.get(new int[]{n-j, i});
}
this line of code isn't searching for the array I put in before. I know that I am creating a new array every time, but how does it make containsKey not know if the array contains same numbers(the same array)? Can anyone help me understand why using an array here to mark the pair of index isn't working in a HashMap?
You don't need a Map to rotate a matrix. You only need one temp variable.
To rotate a 3x3:
1 2 3
4 5 6
7 8 9
temp = 1, copy corner values around, then save value to next corner:
1 2 3 7 2 3 7 2 3 7 2 3 7 2 1
4 5 6 → 4 5 6 → 4 5 6 → 4 5 6 → 4 5 6
7 8 9 7 8 9 9 8 9 9 8 3 9 8 3
repeat for border values, temp = 2:
7 2 1 7 4 1 7 4 1 7 4 1 7 4 1
4 5 6 → 4 5 6 → 8 5 6 → 8 5 6 → 8 5 2
9 8 3 9 8 3 9 8 3 9 6 3 9 6 3
And you're done, in-place rotation with only 1 value in temp storage, i.e. O(1) memory footprint.
Now I'll let you actually code that, for any size matrix.
UPDATE
For the fun of it, I decided to try writing it, so here it is, with test code. I'm not going to explain the logic though, that's for you to figure out yourself.
public static void main(String... args) {
for (int size : new int[] {2,3,4,5,10}) {
int[][] matrix = createMatrix(size);
printMatrix(matrix);
System.out.println();
rotateMatrix(matrix);
printMatrix(matrix);
printSeparatorLine(matrix);
}
}
private static int[][] createMatrix(int size) {
int[][] matrix = new int[size][size];
for (int y = 0, i = 0; y < size; y++)
for (int x = 0; x < size; x++)
matrix[y][x] = ++i;
return matrix;
}
private static void rotateMatrix(int[][] matrix) {
for (int y1 = 0; y1 < matrix.length / 2; y1++) {
for (int y2 = matrix.length - y1 - 1, x1 = y1; x1 < y2; x1++) {
int x2 = matrix.length - x1 - 1, temp = matrix[y1][x1];
matrix[y1][x1] = matrix[x2][y1];
matrix[x2][y1] = matrix[y2][x2];
matrix[y2][x2] = matrix[x1][y2];
matrix[x1][y2] = temp;
}
}
}
private static void printMatrix(int[][] matrix) {
int w = maxValueWidth(matrix);
for (int[] row : matrix) {
for (int i = 0; i < row.length; i++)
System.out.printf("%" + (w + (i == 0 ? 0 : 1)) + "d", row[i]);
System.out.println();
}
}
private static void printSeparatorLine(int[][] matrix) {
char[] buf = new char[(maxValueWidth(matrix) + 1) * matrix.length - 1];
Arrays.fill(buf, '-');
System.out.println(new String(buf));
}
private static int maxValueWidth(int[][] matrix) {
return Arrays.stream(matrix).flatMapToInt(Arrays::stream).map(i -> String.valueOf(i).length()).max().getAsInt();
}
Output
1 2
3 4
3 1
4 2
---
1 2 3
4 5 6
7 8 9
7 4 1
8 5 2
9 6 3
-----
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
13 9 5 1
14 10 6 2
15 11 7 3
16 12 8 4
-----------
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
21 16 11 6 1
22 17 12 7 2
23 18 13 8 3
24 19 14 9 4
25 20 15 10 5
--------------
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
51 52 53 54 55 56 57 58 59 60
61 62 63 64 65 66 67 68 69 70
71 72 73 74 75 76 77 78 79 80
81 82 83 84 85 86 87 88 89 90
91 92 93 94 95 96 97 98 99 100
91 81 71 61 51 41 31 21 11 1
92 82 72 62 52 42 32 22 12 2
93 83 73 63 53 43 33 23 13 3
94 84 74 64 54 44 34 24 14 4
95 85 75 65 55 45 35 25 15 5
96 86 76 66 56 46 36 26 16 6
97 87 77 67 57 47 37 27 17 7
98 88 78 68 58 48 38 28 18 8
99 89 79 69 59 49 39 29 19 9
100 90 80 70 60 50 40 30 20 10
---------------------------------------
You said "this line of code isn't searching for the array I put in before". But you also acknowledge that you were creating a new object each time. That won't work:
Since arrays extend Object, but don't override hashCode() or equals(), you get the default implementations defined by Object. These require that the array is actually the exact same one as is being compared to - so it can't just be 'equivalent'. That is, another array of the same type, with the same elements in the same order, won't work.
Source: https://coderanch.com/t/399422/java/array-HashMap-Key
Instead, you should use a Pair object to store your coordinates. You can write your own implementation or use a pre-existing one, such as javafx.util.Pair
I'm having a minor problem with a program I'm working on. Everything works out perfectly, except for one tiny part.
public class Prog230b
{
public static void main (String args[])
{
for(int i = 1; i <= 25; i++) //
{
int num = i;
System.out.print("\n" + num + ":");
while(num != 1)
{
if(num % 2 == 0)
num /= 2;
else
num = 3 * num + 1;
System.out.print(EasyFormat.format(num,4,0));
}
}
}
}
EasyFormat is just a reference to an exterior formatting file. Below is my output.
1:
2: 1
3: 10 5 16 8 4 2 1
4: 2 1
5: 16 8 4 2 1
6: 3 10 5 16 8 4 2 1
7: 22 11 34 17 52 26 13 40 20 10 5 16 8 4 2 1
8: 4 2 1
9: 28 14 7 22 11 34 17 52 26 13 40 20 10 5 16 8 4 2 1
10: 5 16 8 4 2 1
11: 34 17 52 26 13 40 20 10 5 16 8 4 2 1
12: 6 3 10 5 16 8 4 2 1
13: 40 20 10 5 16 8 4 2 1
14: 7 22 11 34 17 52 26 13 40 20 10 5 16 8 4 2 1
15: 46 23 70 35 106 53 160 80 40 20 10 5 16 8 4 2 1
16: 8 4 2 1
17: 52 26 13 40 20 10 5 16 8 4 2 1
18: 9 28 14 7 22 11 34 17 52 26 13 40 20 10 5 16 8 4 2 1
19: 58 29 88 44 22 11 34 17 52 26 13 40 20 10 5 16 8 4 2 1
20: 10 5 16 8 4 2 1
21: 64 32 16 8 4 2 1
22: 11 34 17 52 26 13 40 20 10 5 16 8 4 2 1
23: 70 35 106 53 160 80 40 20 10 5 16 8 4 2 1
24: 12 6 3 10 5 16 8 4 2 1
25: 76 38 19 58 29 88 44 22 11 34 17 52 26 13 40 20 10 5 16 8 4 2 1
The problem is that it prints nothing for 1. I know this is because I have while(num != 1), but I am unsure what to put instead that does not result in an infinite loop.
Use a do-while loop instead. That way your code will execute at least one time when num starts as 1.
do
{
if(num % 2 == 0)
num /= 2;
else
num = 3 * num + 1;
System.out.print(EasyFormat.format(num,4,0));
} while (num != 1);