I am trying to write a program, which shows numbers 1 to 100. I would like to have a line break after every 20th number. I have tried using a counterloop, which resets itself after every 20th number, but the program runs infinite. How do I fix this?
public class zahlen1_bis_100 {
public static void main(String[] args) {
for (int x = 1; x <= 100; x++) {
for (int counter = 1;counter <= 20; counter++) {
if (counter == 20) {
System.out.println();
counter = 1;
}
}
System.out.print(x + " ");
}
}
}
for (int x = 1; x <= 100; x++) {
System.out.print(x +
(x % 20 == 0 ? "\n" : " ")
);
}
}
Inside the print, it prints x and then checks if the x is a multiple of 20 to print a new line; Otherwise prints a space. It's in Ternary Operator format, but could also be written in normal if block format:
for (int x = 1; x <= 100; x++) {
System.out.print(x);
if (x % 20 == 0)
System.out.print(" ");
else
System.out.println();
}
}
There is no point in using an inner loop. Instead of that, you can implement a if statement to break into next line.
Logic => if the number is a multiple of 20, then break into next line.
Implementation =>
public static void main(String[] args) {
for (int x = 1; x <= 100; x++) {
System.out.print(x + " ");
if(x%20==0){
System.out.println();
}
}
Output =>
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
Thank you all for your help! I wanted to create a "unified" look of the output , so I ended up with the following code:
public class zahlen1_bis_100 {
public static void main(String[] args) {
for (int x = 1; x <= 100; x++) {
if (x < 10) {
System.out.print(x + " ");
} else {
System.out.print(x + " ");
}
if (x % 20 ==0) {
System.out.println();
}
}
}
}
[Result][1]
[1]: https://i.stack.imgur.com/66tXZ.png
Related
I am trying to make a number grid using a Java for-loop
but I have difficulty making it aligned and following the pattern.
The output that I want to see is:
5 4 3 2 1
6 7 8 9 10
15 14 13 12 11
16 17 18 19 20
25 24 23 22 21
I've been watching youtube tutorials and articles about Java for-loops
but I can't find any idea to solve this. I am currently stuck with this code:
int j=5;
int up1=14, up2=6;
for(int u=1; u<=5; u++)
{
for(int s=1; s<=5; s++)
{
System.out.print(j+"\t");
j--;
}
System.out.println("");
if(u%2==0){
j+=up1;
}else{
j+=up2;
}
}
Its output is:
5 4 3 2 1
6 5 4 3 2
15 14 13 12 11
16 15 14 13 12
25 24 23 22 21
I have heard about int update
but I have no idea how to apply it in my code.
You forgot to invert the increment(-1/+1) every line.
Then you need only to adjust up1 and you're fine
int j = 5;
int inc = -1;
int up1 = 4, up2 = 6;
for (int u = 1; u <= 5; u++) {
for (int s = 1; s <= 5; s++) {
System.out.print(j + "\t");
j += inc;
}
System.out.println("");
inc = -inc;
if (u % 2 == 0) {
j += up1;
} else {
j += up2;
}
}
Output:
5 4 3 2 1
6 7 8 9 10
15 14 13 12 11
16 17 18 19 20
25 24 23 22 21
Your problem with the alignment might be that you want leading spaces for the single digits, then use this for the print:
System.out.print(String.format("%2d\t", j));
Output
5 4 3 2 1
6 7 8 9 10
15 14 13 12 11
16 17 18 19 20
25 24 23 22 21
Easy way to say your pattern is correct. Now, you remove "tab" or spacing on output.
Look you wrote \t which means give me a spacing of "tab" size.
System.out.print(j+"\t");
You just have to remove \t. Than, give it a single space.
System.out.println(j+" ");
Done!
int k = 1;
for (int i = 1; i <= 5; i++) {
String accending = "",descending="";
for (int j = k; j < k+5; j++) {
accending+=j+"\t";
descending=j+"\t"+descending;
}
if (i % 2 != 0) {
System.out.println(descending);
k=Integer.parseInt(descending.split("\t")[0])+1;
}else{
System.out.println(accending);
k=Integer.parseInt(accending.split("\t")[4])+1;
}
}
I think it is easy to understand with this code.Simply turn ending digit in each line to a number.
Solution
Even Rows
The pattern for the even rows is that it increases always by 10, you can simply take your j indice and multiply it by factor 5 times the row number.
Important note Here in the example I started counting rows at zero 0 - 4, because first row is odd
Row || Column
1. 2. 3.
0. 5 + (5*0) -> 5 4 + (5*0) -> 4 3 + (5*0) -> 3
2. 5 + (5*2) -> 15 4 + (5*2) -> 14 3 + (5*2) -> 13 ....
4. 5 + (5*4) -> 25 4 + (5*4) -> 24 3 + (5*4) -> 23
Odd Rows
For the odd rows the pattern is more difficult
It increases the last column by ten and then go "backwards" the j value.
Here I defined an counter variable which I increment in every odd iteration.
Row || Column
1. 2.
1. 10*1 - 5 + 1 -> 6 10*1 - 4 + 1 -> 7
3. 10*2 - 5 + 1 -> 16 10*2 - 4 + 1 -> 17
5. 10*3 - 5 + 1 -> 26 10*3 - 4 + 1 -> 27 // this it how it would continue
Here the Full Solution
public static void main(String[] args) {
int counter = 1;
for(int i = 0; i < 5; i++) {
for(int j = 5; j > 0; j--){
if(i % 2 == 0) {
System.out.print(j+(5*i)+ " ");
}else {
System.out.print(10*counter -j+1 + " ");
}
}
if(i%2!=0) {
counter ++;
}
System.out.println();
}
Output is
5 4 3 2 1
6 7 8 9 10
15 14 13 12 11
16 17 18 19 20
25 24 23 22 21
The given pattern goes like this:
The pattern starts with a number e.g. X = 5.
When the main loop counter is an odd number, the print counter starts with start value and decreases by one X times. Finally, it sets start for the next row to start with the final value of the print counter - 1 + X.
When the main loop counter is an even number, the print counter starts with start value and increases by one X times. Finally, it sets start for the next row to start with start + 1.
Based on this property of the pattern, you can write it as
public class Main {
public static void main(String[] args) {
final int X = 5;
int start = X, j, k;
for (int i = 1; i <= X; i++) {
if (i % 2 == 0) {
k = 1;
for (j = start; k <= X; j++, k++) {
System.out.print(j + "\t");
}
start = j - 1 + X;
} else {
k = 1;
for (j = start; k <= X; j--, k++) {
System.out.print(j + "\t");
}
start++;
}
System.out.println();
}
}
}
Output:
5 4 3 2 1
6 7 8 9 10
15 14 13 12 11
16 17 18 19 20
25 24 23 22 21
Change the value of X to 10 and you will get the following pattern:
10 9 8 7 6 5 4 3 2 1
11 12 13 14 15 16 17 18 19 20
30 29 28 27 26 25 24 23 22 21
31 32 33 34 35 36 37 38 39 40
50 49 48 47 46 45 44 43 42 41
51 52 53 54 55 56 57 58 59 60
70 69 68 67 66 65 64 63 62 61
71 72 73 74 75 76 77 78 79 80
90 89 88 87 86 85 84 83 82 81
91 92 93 94 95 96 97 98 99 100
int j=5;
int up1=14, up2=6;
for(int u=1; u<=5; u++)
{
for(int s=1; s<=5; s++)
{
System.out.printf("%5d",j);
j--;
}
System.out.println("");
if(u%2==0) {
j+=up1;
} else {
j+=up2;
}
}
What do you think about this code?
I was wondering how I could align this code properly? So that it could look more like a table. In the output, the numbers start shifted to the right and I do not know how to fix it
public class MultiplicationTable {
int[][] arr = new int[13][13];
public void initializeBoard()
{
for(int i = 1; i < 13; i ++)
{
for(int j = 1; j < 13; j++)
{
arr[i][j] = i * j;
}
}
}
public void printBoard()
{
for(int i = 1; i < 13; i ++)
{
for(int j = 1; j < 13; j++)
{
System.out.print(arr[i][j] +" ");
}
System.out.println();
}
}
}
Use the Scanner#printf() method to display formatted text within the Console window, for example:
public void printBoard() {
for (int i = 1; i < 13; i++) {
for (int j = 1; j < 13; j++) {
System.out.printf("%-6s", arr[i][j]);
}
System.out.println();
}
}
The Console should display:
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 have done it almost correctly. I believe with a smaller change in your printBoard() method like this should make the out put correctly
public static void printBoard()
{
for(int i = 1; i < 13; i ++)
{
for(int j = 1; j < 13; j++)
{
if(arr[i][j] >= 100){
System.out.print(arr[i][j] +" ");
} else if(arr[i][j] >= 10){
System.out.print(arr[i][j] +" ");
} else {
System.out.print(arr[i][j] +" ");
}
}
System.out.println();
}
}
And I got the output like this
I hope this helps.
I have this code, and it works fine, but I want to format it so that it prints 15 numbers on each line.
I have seen it done with % or for loops, but I don't know how to use them in my code. Thank you to everyone for helping! Thank you!
import java.util.*;
import java.io.*;
class Main
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
System.out.print("Enter the number that you want to find all the prime numbers up to it: ");
int num = sc.nextInt();
boolean[] bool = new boolean[num];
for (int i = 0; i < bool.length; i++) {
bool[i] = true;
}
for (int i = 2; i < Math.sqrt(num); i++) {
if(bool[i] == true) {
for(int j = (i * i); j < num; j = j + i) {
bool[j] = false;
}
}
}
System.out.println("List of prime numbers upto given number are : ");
for (int i = 2; i < bool.length; i++) {
if(bool[i]==true)
{
System.out.print(i + " ");
}
}
}
}
You can make increment a count each time bool[i] is true, then move to the next line when the count is 15 and reset the count back to 0.
Here is what your print loop would now look like:
System.out.println("List of prime numbers upto given number are : ");
int count = 0;
for (int i = 2; i< bool.length; i++) {
if(bool[i])
{
if (count == 15) {
count = 0;
System.out.println();
}
System.out.print(i + " ");
count++;
}
}
Output:
Enter the number that you want to find all the prime numbers up to it: 120
List of prime numbers upto given number are :
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47
53 59 61 67 71 73 79 83 89 97 101 103 107 109 113
In the context of what you're doing the best option would be something like this:
int count = 0;
System.out.println("List of prime numbers upto given number are : ");
for (int i = 2; i< bool.length; i++) {
if(bool[i]==true) {
System.out.print(i + " ");
count++;
}
if(count == 15) {
System.out.println();
count = 0;
}
}
Do it as follows:
System.out.println("List of prime numbers upto given number are : ");
for (int i = 2, j = 1; i < bool.length; i++) {
if (bool[i] == true) {
System.out.print(i + " ");
if (j % 15 == 0) {
System.out.println();
}
j++;
}
}
A sample run:
Enter the number that you want to find all the prime numbers up to it: 200
List of prime numbers upto given number are :
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47
53 59 61 67 71 73 79 83 89 97 101 103 107 109 113
127 131 137 139 149 151 157 163 167 173 179 181 191 193 197
199
Feel free to comment in case of doubt.
so I'm just starting a pretty simple project for school in which I want to create a booking system for a stadium. I've got a twoD array that will create a simple 7X10 array. However, I want to leave some space in the middle of the array that would represent the pitch/field in the stadium. I'm wondering how to do this?
I'm thinking an array inside an array if that is possible?
This is my code so far(got most of it from another question on here):
package FootballMatch;
public class Seats {
public static void main(String[] args) {
System.out.print("\t\t Stadium Seating \n");
int seatArray[][]= new int[10][7];
int i, x, y = 1;
for(i = 0; i < 10; i++) {
for(x = 0; x < 7; x++) {
seatArray[i][x] = y;
y++;
} // end inner for
} // end outer for
for(int[] row : seatArray) {
printRow(row);
}
} // end of main
public static void printRow(int[] row) {
for (int i : row) {
System.out.print(i);
System.out.print(" \t");
}
System.out.println();
}
}
output:
`Stadium Seating
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`
So i want to have every 3rd to 5th number in the third to eight row of the array invisible, like this:
`Stadium Seating
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 _ _ _ 20 21
22 23 _ _ _ 27 28
29 30 _ _ _ 34 35
36 37 _ _ _ 41 42
43 44 _ _ _ 48 49
50 51 _ _ _ 55 56
57 58 59 60 61 62 63
64 65 66 67 68 69 70`
Note all of these numbers will probably be changed to 'x' in the finished program. 'x' meaning the seat is available and an empty space meaning its the field!
Going off of ControlAltDel's suggestion, a well designed answer to this problem (that also allows for later expansion) is to create a Seat Class to represent a single seat.
public class Seat{
private int index; //-1 if not available, > 0 otherwise
private boolean available;
/** Creates an available seat with index i. i > 0. */
public Seat(int i){
index = i;
available = true;
}
/** Creates a non-available seat. */
public Seat(){
index = -1;
available = false;
}
/** Return a string representation of this Seat. Its index if available, - otherwise */
public String toString(){
if(available) return index + "";
else return "-";
}
}
Then you can create a matrix of Seats that represents your stadium:
public static void main(String[] args) {
System.out.print("\t\t Stadium Seating \n");
Seat seatArray[][]= new Seat[10][7];
int i, x, y = 1;
for(i = 0; i < 10; i++) {
for(x = 0; x < 7; x++) {
if(i >= 2 && i <= 7 && x >= 2 && x <= 4){
seatArray[i][x] = new Seat(); //Not available seat
} else {
seatArray[i][x] = new Seat(y);
}
y++;
}
}
for(Seat[] row : seatArray){ printRow(row); }
}
public static void printRow(Seat[] row) {
for (Seat s : row) {
System.out.print(s); //toString method called implicitly here.
System.out.print(" \t");
}
System.out.println();
}
Use an boolean array to indicate that those positions can be occupied by a person.
In order to do this, you have to change your printing method. You have to use a code like:
// You must set canSeat at your will (true and false).
public static void print(int[][] seatArray, Boolean canSeat[][]) {
for(i = 0; i < 10; i++) {
for(x = 0; x < 7; x++) {
if(canSeat[i][x])
System.out.print(seatArray[i][x]);
else
System.out.print(" ");
System.out.print(" \t");
}
}
}
Currently I'm only able to display odd numbers of 1 3 5 7 9. However, I would like to display all the odd numbers from 1 - 99 with 9 rows and 5 col. May I know how am I able to display from 11 onwards rather than just 9 rows of 1 3 5 7 9.
Below is the code I'm stuck with.
public static void main(String args[])
{
for (int i=1; i<=9; i++)
{
for (int j=1; j<=10; j++)
{
if (j%2 !=0)
System.out.print(j + " " );
}
System.out.println();
}
}
first you need to calculate your number, try
for (int i=0; i<=9; i++)
{
for (int j=1; j<=10; j++)
{
int number = j+i*10
if (number%2 !=0)
System.out.print(number + " " );
}
System.out.println();
}
but this problem you can solve with single loop
for (int i=1; i<=99; i++)
{
if (number%2 !=0)
System.out.print(number + " " );
if (number%10 ==0)
System.out.println();
}
for ( i = 1; i < 100; i+=2 ) {
System.out.print(i);
}
System.out.println();
public static void main(String args[])
{
for (int i=1; i<=99; i++)
{
if (i%2 !=0)
System.out.print(i + " " );
if(i%10 == 0)
System.out.println();
}
}
This code will allow you to do what you want with 1 loop which is more efficient than using nested loops.
This will loop through each number from 1-99 and print if it is odd. If the number is a multiple of 10 then it will print a new line.
Maybe this helps:
public static void main(String args[])
{
for (int j = 0; j < 10; j++)
{
for (int i = 1; i <= 9; i++)
{
int c = j * 10 + i;
if (c % 2 !=0)
System.out.print(c + " " );
}
System.out.println();
}
}
Other alternative with just one loop:
public static void main(String args[]) {
for (int j = 1; j <= 99; j += 2) {
System.out.print(j + " ");
if ((j + 1) % 10 == 0) {
System.out.println();
}
}
}
If you want to use a nested forloop you have to use both iterating variables to build your numbers. You dont use i at all in the inner for-loop. Therefore only 1 3 5 7 9 gets printed 9 times. For a hotfix try to use something like
System.out.print(i + j + " " );
instead of
System.out.print(j + " " );
note how i+j does not compute an addition here.
Anyway like pointed out in the comments you dont really need 2 loops here.
we cheat:
for (int i = 1; i <= 99; i += 2)
System.out.printf("%d%s", i, i % 10 == 9 ? "\n" : " ");
we check:
int c =0;
for (int i = 1; i <= 99; i++)
if ((i & 1) == 1) {
c++;
System.out.printf("%d%s", i, c % 5==0 ? "\n" : " ");
}
both output same, 5 odd numbers in a row, without trailing spaces.
With this one you can easily set the number of columns as you like it.
We use a single loop.
Code:
int columns = 5;
int start = 1;
int end = 99;
// iterate through every seconds i.
for (int i = start; i <= end; i += 2) {
System.out.printf("%-4d", i);
// if we have displayed enough words, start a new line
if (i % (2 * columns) == 0) {
System.out.println();
}
}
Output:
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
However, if I understood your question correctly, you wanted to show numbers with 5 columns and 9 rows? Well this is impossible if we print only the numbers from 1 to 99. With 5 columns and numbers 1 to 99, you will get 10 rows.
Your code now prints 9 rows of:
1 3 5 7 9
This is happening because your inner loop loops on values between 1 and 9, always.
You should try something like:
int counter = 0;
for(int i=1; i<=99; i++) {
if(i%2 != 0) {
System.out.print(i + " ");
counter++;
}
if(counter == 5) {
System.out.println();
counter = 0;
}
}
This will print:
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