Method prints table incorrectly - java

I was wondering if someone could help me with a small problem I'm having.
I am trying to print out an array of 100 items, every row needs 10 items, after which it starts a new row. I have done this successfully, however, every row in every column displays the same number. For example. My output would be:
1 1 1 1 1 1 1 1 1 1
2 2 2 2 2 2 2 2 2 2
When it should be appearing as something along the lines of:
1 2 3 4 5 6 7 8 9 10
11 12 13 14 15 16 17 18 19 20
Here is the following method I am using to print the table:
public static void printTable(int[] emirps) {
for (int i = 0; i < 100; i++) {
for (int j = 0; j < 10; j++) {
// After 10 go to a new line
System.out.printf("%d\t", emirps[i]);
}
System.out.println("");
}
}
If anyone can help me pinpoint where I have goofed I'd greatly appreciate it.

You are printing the same emirps[i] each time through the inner loop. There are a couple of ways around this. Here's one:
public static void printTable(int[] emirps) {
for (int i = 0; i < 100; i += 10) {
for (int j = 0; j < 10; j++) {
// After 10 go to a new line
System.out.printf("%d\t", emirps[i + j]);
}
System.out.println();
}
}
Here's another (not very elegant):
public static void printTable(int[] emirps) {
for (int i = 0; i < 100; ++i) {
System.out.printf("%d\t", emirps[i]);
if (i % 10 == 9) {
System.out.println();
}
}
}

This looks like homework, so instead of giving you the answer, here's a hint:
For the first iteration of the first loop, i = 0. When this is the case, you increment j from 0 to 9. Note that i stays the same throughout. This is when you print your first line.
Once you're through with the second for loop, i increases by 1 to, and now i = 1. Again, you increment j from 0 to 9, and i stays at 1. This is when you print your second line.
This repeats 100 times, as i goes from 0 to 99.
There are 2 ways of approaching this:
Use one for loop, and figure out when to print an end-of-line character.
Use two for loops, each going up to 10. Figure out your index by simple multiplication and addition.
You should try and implement both methods. It'll help you understand loops better.

You are not using the j index anywhere in this code.
Here is how you should print:
System.out.printf("%d\t", emirps[i+j]);
Notice how in the print statement you are now using both the i and j indices.
Also, to get your row offset working correctly, you should be incrementing i by 10 at each step of the loop.
Alternatively, declare emirps as a 2-dimensional array. Then the signature of printTable() would be:
public static void printTable(int[][] emirps)
In that setup, here is how you would print:
System.out.printf("%d\t", emirps[i][j]);
So in the first setup, i+j together index into a 1-D array. In the second setup, i is the row and j is the column, indexing together into a 2-D array. It looks like you're doing a 1-D array but this other example is for your future reference.

Use the modulo operator. Every time your number can be divided by 10 without a remainder, you can make a new line because you have filled up the row. You obtain the remainder using the 'modulo operator' which is the percent (%) sign. It can be used like /, except that rather than the quotient being the result, the remainder of the division operation is the result.
public static void main(String[] args)
{
StringBuilder builder = new StringBuilder();
for (int i = 0; i < 100; i++)
{
if (i != 0 && i % 10 == 0)
{
builder.append('\n');
}
builder.append(i + " ");
}
System.out.println(builder.toString());
}
Prints out:
0 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

Related

How can I print out 1-50 even numbers only, but the it start a new line every multiples of 10. (JAVA)

I'm a newbie, but I'm willing to learn how to code.
I tried using this code:
int n = 50;
int counter = 0;
System.out.print("Even Numbers from 1 to "+n+" are: ");
for (int i = 1; i <= n; i++) {
counter++;
if (counter == 2) {
System.out.println(i + " ");
counter = 0;
%10== 0
to find all even numbers between 1 to 50 and make a new line at multiples of 10 just follow these steps -
Make one loop which will go 1 to 50
Check if the number is even by checking the remainder after diving it with 2, if YES print that number.
Check if the number is a multiple of 10 by checking the remainder after dividing it by 10, if YES make a new line
The code will look something like this -
int i = 1;
while(i<=50){
if(i%2 == 0) System.out.print(i + " ");
if(i%10 == 0) System.out.println();
i++;
}
Output -
2 4 6 8 10
12 14 16 18 20
22 24 26 28 30
32 34 36 38 40
42 44 46 48 50
It's up to you which looping method you want to use for me While loop looks cleaner.
I hope this solves all your queries.
PFB Snippet:
public class Main
{
public static void main(String[] args) {
for(int i=1;i<=50;i++){
if (i%2 == 0) //Check whether number is even
{
System.out.print(i+" ");
if (i%10 == 0) // Check if it is multiple of 10
{
System.out.print("\n");
}
}
}
}
}
Output:
2 4 6 8 10
12 14 16 18 20
22 24 26 28 30
32 34 36 38 40
42 44 46 48 50
"\n" is a Escape Sequence which means new line

Java for loop with discrete values

I need a for loop that its limit could be exceeded after one ends(one of the limits), I like to declare the limit 9 and start traversing an array to index of 8 then start from 9 and take 9 more steps and so on,until I reach the end of the array, my tries reached to this point but I wonder if it works correctly:
int [] i={9,18,27,36,45,54,63,72,81};
for(int x:i){
for(int j=0;j<x;j++)
{}
}
does the nested for loop going to change the x value after each complete cycle of the inner for loop or not?
then start from 9 and take 9 more steps
Your code doesn't behave as you want, since the inner loop always starts at 0.
There's no need to declare the i array. You can do it like this :
int start = 0;
for (int i = 9; i <= 81; i+=9) {
for (int j = start; j < i; j++) {
}
start = i;
}
Or as phflack suggested :
for (int i = 9; i <= 81; i+=9) {
for (int j = i - 9; j < i; j++) {
}
}
you can use this code:
int start = 0;
for (int i = 9; i <= 81; i+=9) {
for (int j = start; j < i; j++) {
System.out.print(j+" ");
}
System.out.println();
start = i;
//System.out.print(start+" ");
}
}
and you see:
0 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
Another training for you:
int start = 0;
for (int i = 1; i <= 10; i++) {
for (int j = 1; j < i; j++) {
System.out.print(j + " ");
}
System.out.println();
}
and you can see:
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
1 2 3 4 5 6
1 2 3 4 5 6 7
1 2 3 4 5 6 7 8
1 2 3 4 5 6 7 8 9
You can use two loop to print like matrix.

Error in the code when working with arrays

Hy!
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException?
package studing;
public class Array {
public static void main(String[] args) {
int i;
int[] ar1 = new int[50];
for(i = 0; i < ar1.length; i++)
{
ar1[i] = i * 2 + 1;
System.out.print(ar1[i] + " ");
};
System.out.println();
for(i = ar1.length; i > -1; i--)
{
ar1[i] = i * 2 - 1;
System.out.print(ar1[i]);
};
}
}
After compiling the console displays:
1 3 5 7 9 11 13 15 17 19 21 23 25 27 29 31 33 35 37 39 41 43 45 47 49
51 53 55 57 59 61 63 65 67 69 71 73 75 77 79 81 83 85 87 89 91 93 95
97 99
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException:
50 at studing.Array.main(Array.java:18)
I want the output console in the second row 99 97 95 93 ...
Thanks in advance!
You start at ar1.length in your second loop, which is out of bounds.
To get it to work, you need to start at ar1.length-1, which is the maximum index for your array.
This is because arrays are 0-based in Java, as noted in the comments by #Maroun Maroun.
The first time the second for loop runs, i = 50 (the initial value), which is beyond the end of the array. This value is used before the index update of i--, so ar1[50] is out of bounds (proper indexes are 0 to 49 for a 50 element array).

for increment java issue

I'm new to Java. I am trying to create a multiplication table with 12 on each side of the table, so 12 going to the right and 12 going down. On each line, we will see the two values multiple. So my plan is to use 12 very similar for statements to print each of the twelve lines. One value will increment within a loop. The issue is, the first line isn't increment my y value. So it just prints out spaced out 1s.
If you have any suggestions on my latter part of the assignment, it'd be helpful. Once I get the first line to print 12 digits, I can make 11 other for statements. But I feel like there may be a simpler way to get the rest of the statements.
public class Sixthree
{
public static void main (String[] args)
{
int x = 1;
int y = 1;
System.out.print(" ");
for ( int c= x*y; y<= 12; y++)
{
System.out.print(c + " ");
}
}
}
I want the out put to look like this to start off with.:
1 2 3 4 5 6 7 8 9 10 11 12
But the current output looks like this:
1 1 1 1 1 1 1 1 1 1 1 1 1
But I want it to eventually like this: http://math.about.com/blgrid.htm
But without the blue lines.
You are getting all 1s because the loop initialization statement int c= x*y will be executed only once for a for loop. That is it is executed the first time when x=1 and y=1 and since, it is given as the loop initialisation statement and not in the loop body, it is never reevaluated. The for loop works as :
The loop initialisation statement is executed only once at the beginning of the loop. After each iteration the loop update expression is executed and the loop condition is reevaluated. for(loop_initialisation;loop_condition;loop_update) { ... }
So you should update c inside the loop, something like :
for ( int c= x*y; y<= 12; y++)
{
c = x*y;
System.out.print(c + " ");
}
for (int i = 1; i <= 12; i++) {
for (int j = 1; j <= 12; j++){
System.out.printf ("%3d ", j * i);
}
System.out.print ("\n");
}
The above code will give you output similar to what is shown below:
1 2 3 4 5 6 7 8 9 10 11 12
2 4 6 8 10 12 14 16 18 20 22 24
3 6 9 12 15 18 21 24 27 30 33 36
4 8 12 16 20 24 28 32 36 40 44 48
5 10 15 20 25 30 35 40 45 50 55 60
6 12 18 24 30 36 42 48 54 60 66 72
7 14 21 28 35 42 49 56 63 70 77 84
8 16 24 32 40 48 56 64 72 80 88 96
9 18 27 36 45 54 63 72 81 90 99 108
10 20 30 40 50 60 70 80 90 100 110 120
11 22 33 44 55 66 77 88 99 110 121 132
12 24 36 48 60 72 84 96 108 120 132 144
You should be using two nested for loops, one to iterate over the values of x, another to iterate over the values of y with each inner loop printing the value of x * y and each outer loop printing a new line character for formatting.
// Pseudo-code //
for(each x) {
for(each y) {
print(product);
}
print(newline);
}
Why it just prints out spaced out 1s ?
It is because you just assign c only once in for-loop. for ( int c= x*y; y<= 12; y++)
When value y is incvreasing, value c is not changing. The values is 1*1=1 (x=1, y=1).
As a result, you see it just prints out spaced out 1s.
You can use nested for loop to implement it.
public class Sixteen {
public static void main(String[] args) {
int x = 12;
int y = 12;
for (int i = 1; i <= x; i++) {
for (int j = 1; j <= y; j++) {
System.out.printf("%d ", i * j);
}
System.out.println();
}
}
}
for (int x = 1; x <= 12; x++)
{
for (int y = 1; y <= 12; y++)
{
int multiply = x * y;
System.out.print(multiply + "\t");
}
System.out.println();
}

Java: Is it possible to make line break x times inside for loop?

I tried to Google and search StackOverflow my question but I didn't found any answers to this.
I have made an array where both size and values are randomly generated. When the array values have been printed 20 times I would like to make a line break, but without printing the rest values with always new line.
Here is my code:
public static void catArr() {
Random rändöm = new Random();
int size = rändöm.nextInt(100);
int[] arr = new int[size];
for (int i = 0; i < size; i++) {
arr[i] = rändöm.nextInt(100);
}
Arrays.sort(arr);
for (int i = 0; i < size; i++) {
System.out.print(" " + arr[i]);
if (i > 20)
System.out.println(); //How to do this only once?
else if (i > 40)
System.out.println(); //Same here?
}
}
And this is one of the generated outputs:
3 8 10 25 30 31 34 38 46 50 55 59 62 66 67 68 68 68 72 76 76 81
82
83
84
86
91
92
93
94
94
97
I think that one way to solve this is using 2-D array, but I would like to know if there is another way.
Yay thanks to Patric, I got the wanted result:
0 2 3 7 7 9 11 14 14 16 18 19 24 25 26 28 28 30 30 31
31 33 33 34 41 41 41 42 43 44 45 46 51 51 52 53 59 60 61 62
62 62 63 65 65 67 67 68 69 70 74 74 76 78 82 83 84 84 87 88
89 93 93 94 94 94 95
try using
if ( ( i % 20 ) == 0 ){
System.out.println();
}
if i divided by 20 leaves no remainder then print a new line!
Maybe
if (i % 20==0)
can solve your else if problem.
Use (++i % 20) == 0 and remove i++ from loop; pre-increment avoid first unwanted line break.
Literally, this will do what you seem to want:
if (i == 20)
System.out.println();
else if (i == 40)
System.out.println();
But I have a feeling that you actually want to add a newline after the 20th, 40th, 60th and so on.
if (i % 20 == 0)
System.out.println();
And if you want to output exactly one newline at the end, then you need something like this:
for (int i = 0; i < size; i++) {
if (i > 1 && i % 20 == 1) {
System.out.println();
System.out.print(" " + arr[i]);
}
System.out.println();
You may use boolean for your Sys outs.
boolean myBoolean = true;
if(myBoolean){
//print
myBoolean = false; //set boolean to false.
}
On the other hand, in my preferences, I still stick with my integer flagging.
int isTrue = 1;
if(isTrue == 1){
//print
isTrue = 0;
}

Categories