Print an array elements with 10 elements on each line - java

I just created an array with 100 initialized values and I want to print out 10 elements on each line so it would be somthing like this
0 1 2 3 4 5 6 7 8 9
10 11 12 13 14 15 16
...26
this is the code I used and I managed to do it for the first 10 elements but I couldn't figure out how to do it for the rest
public static void main(String[] args) {
int[] numbers = { 0,1,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17};
int i, count = 0;
for (i = 0; i < numbers.length; i++) {
System.out.print(numbers[i] + " ");
count++;
if (count == 9)
for (i = 9; i < numbers.length; i++)
System.out.println(numbers[i] + " ");
}
}

int[] numbers = new int[100];
for (int i = 0; i < numbers.length; i++) {
if (i % 10 == 0 && i > 0) {
System.out.println();
}
System.out.print(numbers[i] + " ");
}
This prints a newline before printing numbers[i] where i % 10 == 0 and i > 0. % is the mod operator; it returns the remainder if i / 10. So i % 10 == 0 when i = 0, 10, 20, ....
As for your original code, you can make it work with a little modification as follows:
int count = 0;
for (int i = 0; i < numbers.length; i++) {
System.out.print(numbers[i] + " ");
count++;
if (count == 10) {
System.out.println();
count = 0;
}
}
Basically, count is how many numbers you've printed in this line. Once it reaches 10, you print the newline, and then reset it back to 0, because you're starting a new line, and for that line, you haven't printed any numbers (yet).
Note that in above two solutions, an extra space is printed at the end of each line. Here's a more flexible implementation that only uses separators (horizontal and vertical) when necessary. It's only slightly more complicated.
static void print(int[] arr, int W, String hSep, String vSep) {
for (int i = 0; i < arr.length; i++) {
String sep =
(i % W != 0) ? hSep :
(i > 0) ? vSep :
"";
System.out.print(sep + arr[i]);
}
System.out.println(vSep);
}
If you call this say, as print(new int[25], 5, ",", ".\n");, then it will print 25 zeroes, 5 on each line. There's a period (.) at the end of each line, and a comma (,) between zeroes on a line.

Why do you use 2 nested loops where you only need to remember at which places you need to output a linebreak? Also using the same variable i for both loops will not do what you expect.
How about:
for (i = 0; i < numbers.length; i++) {
System.out.print(numbers[i] + " ");
count++;
if (count == 10)
System.out.print("\n");
count = 0;
}
}

All you are going to have to do is to print out a newline after every ten numbers.
for (i = 0; i < numbers.length; ++i)
{
System.out.print(number[i]);
if (i % 10 == 9)
{
System.out.println();
}
else
{
System.out.print(" ");
}
}

I know this is an old question, but I just wanted to answer. In java 8 you can do this in one line. Arrays.stream(arr).forEach(s->System.out.print(s%10 > 0 ? s+" ":"\n"));

Related

How to get indices as well as array numbers printed out horizontally?

I have an assignment of which a part is to generate n random numbers between 0-99 inclusive in a 1d array, where the user enters n. Now, I have to print out those numbers formatted like this:
What is your number? 22 //user entered
1 2 3 4 5 6 7 8 9 10
----random numbers here---------
11 12 13 14 15 16 17 18 19 20
-----random numbers here--------
21 22
---two random numbers here---
Using those numbers, I have find lots of other things, (like min, max, median, outliers, etc.) and I was able to do so. However, I wasn't able to actually print it out in the format shown above, with no more than 10 numbers in one row.
Edit: Hello, I managed to figure it out, here's how I did it:
int counter = 0;
int count2 = 0;
int count3 = 0;
int add = 0;
int idx = 1;
int idx2 = 0;
if (nums > 10)
{
count3 = 10;
count2 = 10;
}
else
{
count3 = nums;
count2 = nums;
}
if (nums%10 == 0) add = 0;
else add = 1;
for (int i = 0; i < nums/10 + add; i++)
{
for (int j = 0; j < count3; j++)
{
System.out.print(idx + "\t");
idx++;
}
System.out.println();
for (int k = 0; k < count2; k++)
{
System.out.print(numbers[idx2] + "\t");
idx2++;
counter++;
}
System.out.println("\n");
if (nums-counter > 10)
{
count3 = 10;
count2 = 10;
}
else
{
count3 = nums-counter;
count2 = nums-counter;
}
}
Thank you to everyone who helped! Also, please let me know if you find a way to shorten what I have done above.
*above, nums was the number of numbers the user entered
I'd use a for-loop to make an array of arrays: and then formatting the lines using those values:
var arr_random_n = [1,2,3,4,5,6,7,8,9,0,1,2,3,6,4,6,7,4,7,3,1,5,7,9,5,3,2,54,6,8,5,2];
var organized_arr = [];
var idx = 0
for(var i = 0; i < arr.length; i+=10){
organized_arr[idx] = arr.slice(i, i+10); //getting values in groups of 10
idx+=1 //this variable represents the idx of the larger array
}
Now organized_arr has an array of arrays, where each array in index i contains the values to be printed in line i.
There's probably more concise ways of doing this. but this is very intuitive.
Let me know of any improvements.
Something like this might be what you're looking for.
private static void printLine(String msg)
{
System.out.println("\r\n== " + msg + " ==\r\n");
}
private static void printLine(int numDisplayed)
{
printLine(numDisplayed + " above");
}
public static void test(int total)
{
int[] arr = new int[total];
// Fill our array with random values
for (int i = 0; i < total; i++)
arr[i] = (int)(Math.random() * 100);
for (int i = 0; i < total; i++)
{
System.out.print(arr[i] + " ");
// Check if 10th value on the line, if so, display line break
// ** UNLESS it's also the last value - in that case, don't bother, special handling for that
if (i % 10 == 9 && i != total - 1)
printLine("Random Numbers");
}
// Display number of displayed elements above the last line
if (total < 10 || total % 10 != 0)
printLine(total % 10);
else
printLine(10);
}
To print 10 indexes on a line then those elements of an array, use two String variables to build the lines, then print them in two nested loops:
for (int i = 0; i < array.length; i += 10) {
String indexes = "", elements = "";
for (int j = 0; j < 10 && i * 10 + j < array.length; j++) {
int index = i * 10 + j;
indexes += (index + 1) + " "; // one-based as per example in question
elements += array[index] + " ";
}
System.out.println(indexes);
System.out.println(elements);
}

For loop java making the output into 2 columns

Hi I'm a beginner and I'm still learning and if someone could help me in this one thx in advance my code is:
for(int i = 0; i < 10; i++) {
System.out.println(i);
}
and the output should be like this:
0 1
2 3
4 5
6 7
8 9
Just use next line only for odd numbers:
for (int i = 0; i < 10; i++) {
if (i % 2 == 0)
System.out.format("%2d", i);
else
System.out.format(" %2d\n", i);
}
Output:
0 1
2 3
4 5
6 7
8 9
P.S. For more general usage, I would extract it into separate method
public static void printTwoColumns(int min, int max) {
int width = String.valueOf(max).length();
for (int i = min; i < max; i++) {
String str = String.format("%" + width + 'd', i);
if (i % 2 == 0)
System.out.print(str);
else {
System.out.print(' ');
System.out.println(str);
}
}
}
You can do something like this:
for (int i = 0; i < 10; i++) {
System.out.print(i);
System.out.println(++i);
}
The first print uses the current i value and using System.out.print.
The second
print is using println so it goes one line down and also takes ++i so it will advance i by 1 and will also print the new value.
Each loop iteration is printing two values and advances i by total of 2.
To do what you want you can either do something like this:
for(int i = 0; i < 10; i ++){
if(i % 2 == 0){
System.out.print(i); //Only for evens
}else{
System.out.println(i); //Only for odds
}
}
Or you could simplify it even more with something like this:
for(int i = 0; i < 5; i += 2){
System.out.println(i + " " + (i + 1));
}

Program that takes user input and lists multiples of 7 according to that number (Java)

Here is my code to create a program that takes a user input and lists multiples of 7 that relate to that number.
For example: The user inputs 3, I need the output to be "7, 14, 21".
Currently if I enter a number less than 7, the program complies without printing an output, but as soon as I enter 7 or any number higher than 7 then the program compiles and prints exactly what I need it to.
So the problem I need to fix is to be able to enter a number lower than 7 and recieve the correct output.
Thanks in advance!
import java.util.Scanner;
public class MultiplesOfSeven {
public static void main(String[] args){
int j = 0;
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
for(j = 1; j <= n; j++){
if(j % 7 == 0){
System.out.print(j + " ");
for (int counter = 0 ; counter < n ; counter++) {
System.out.print(j*(2 + counter) + " ");
}
}
}
}
Don't overthink the loop here. As alternatives, both which mean you can delegate the % check, consider
for (j = 0; j < n; ++j){
// output (j + 1) * 7;
}
or, the less elegant due to your having to write 7 in three places
for (j = 7; j <= n * 7; j += 7){
// output j
}
This code is preventing your programm from printing anythingk, when you enter a number below 7:
if(j % 7 == 0){
% is the modulo operator.
It says: do what is in the brackets if the number I have counted to (j) has no reminder if I divide it by 7.
So what you have to do is count to the number entered (using a for loop) and print the mulitplication of the current number times 7.
It's not printing anything because when the number you inputted is less than seven and greater than zero, the code inside
if(j%7==0)
does not get executed. I think your code should be like this.
for (j = 1; j <= n; j++) {
if (j % 7 == 0) {
System.out.print(j + " ");
}
for (int counter = 0; counter < n; counter++) {
System.out.print(j * (2 + counter) + " ");
}
}
import java.util.Scanner;
public class MultiplesOfSeven {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
for(int j = 1; j <= n; j++) {
System.out.print(7*j + " ");
}
}
}
This is simple solution of your problem. This will work for all cases. Keep code simple good luck.

Check why index is out of bounds

I want to write a program that reads a matrix of positive int with the format txt (the matrix can be of any size). (I read the matrix from the console).
The program looks for a location in the matrix such that if a knight is positioned at that location, all possible moves will land the knight on elements which have the same value and it must have at least 2 options. The program prints the result. for example, the black places are where the knight can move to.
This is the code I wrote. the problem is that i'm getting: "Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1
at Knights.main(Knights.java:23)", I know it has a problem with the first row (there is no backwards value in the start of the matrix) but I don't know how can I fix it.
public static void main (String[] args) {
String size = StdIn.readLine();
int counter = 0;
int matrixSize = Integer.parseInt(size);
int [][] matrix = new int [matrixSize+1][matrixSize+1];
for (int i=0; i <= matrixSize-1; i++) {
for (int j=0; j <= matrixSize-1; j++) {
if ((matrix[i][j]) > 0)
matrix[i][j] = StdIn.readInt();
}
}
for (int k=0; k <= matrixSize-2; k++) {
for (int l=0; l <= matrixSize-2; l++) {
if (matrix[k-1][l+2] == matrix[k+1][l+2]) {
counter +=1;
StdOut.println(counter); }
else if (matrix[k-1][l+2] == matrix[k+1][l-2]) {
counter +=1;
StdOut.println(counter); }
if (counter>=2)
StdOut.println("location "+ matrix[k][l] + "is surrounded by the number " +matrix[k+1][l-2]);
}
}
if (counter < 2)
StdOut.println("no surrender by any number");
}
}
I would add an extra test here to check if k-1 is greater than 0.
As && is a short-circuit operator, the second expression is not tested if the first is false and can not throw an exception.
Solution
if (k - 1 > 0 && matrix[k - 1][l + 2] == matrix[k + 1][l + 2]) {
counter += 1;
StdOut.println(counter);
} else if (k - 1 > 0 && matrix[k - 1][l + 2] == matrix[k + 1][l - 2]) {
counter += 1;
StdOut.println(counter);
}

Printing odd numbers in odd sequences

There's this problem from my programming class that I can't get right... The output must be all odd numbers, in odd amounts per line, until the amount of numbers per line meets the odd number that was entered as the input. Example:
input: 5
correct output:
1
3 5 7
9 11 13 15 17
If the number entered is even or negative, then the user should enter a different number. This is what I have so far:
public static void firstNum() {
Scanner kb = new Scanner(System.in);
int num = kb.nextInt();
if (num % 2 == 0 || num < 0)
firstNum();
if (num % 2 == 1)
for (int i = 0; i < num; i++) {
int odd = 1;
String a = "";
for (int j = 1; j <= num; j++) {
a = odd + " ";
odd += 2;
System.out.print(a);
}
System.out.println();
}
}
public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
firstNum();
}
The output I'm getting for input(3) is
1 3 5
1 3 5
1 3 5
When it really should be
1
3 5 7
Can anyone help me?
Try this:
public static void firstNum() {
Scanner kb = new Scanner(System.in);
int num = kb.nextInt();
while (num % 2 == 0 || num < 0) {
num = kb.nextInt();
}
int odd = 1;
for (int i = 1; i <= num; i += 2) {
String a = "";
for (int j = 1; j <= i; j++) {
a = odd + " ";
odd += 2;
System.out.print(a);
}
System.out.println();
}
}
if (num % 2 == 1) {
int odd = 1;
}
for (int i = 0; i < num; i++) {
String a = "";
for (int j = 1; j <= odd; j++) {
a = odd + " ";
odd += 2;
System.out.print(a);
}
System.out.println();
}
You should assign odd before for loop.
In inner for loop compare j and odd together.
For questions like this, usually there is no need to use and conditional statements. Your school probably do not want you to use String as well. You can control everything within a pair of loops.
This is my solution:
int size = 7; // size is taken from user's input
int val = 1;
int row = (size / 2) + 1;
for (int x = 0; x <= row; x++) {
for (int y = 0; y < (x * 2) + 1; y++) {
System.out.print(val + " ");
val += 2;
}
System.out.println("");
}
I left out the part where you need to check whether input is odd.
How I derive my codes:
Observe a pattern in the desired output. It consists of rows and columns. You can easily form the printout by just using 2 loops.
Use the outer loop to control the number of rows. Inner loop to control number of columns to be printed in each row.
The input number is actually the size of the base of your triangle. We can use that to get number of rows.
That gives us: int row = (size/2)+1;
The tricky part is the number of columns to be printed per row.
1st row -> print 1 column
2nd row -> print 3 columns
3rd row -> print 5 columns
4th row -> print 7 columns and so on
We observe that the relation between row and column is actually:
column = (row * 2) + 1
Hence, we have: y<(x*2)+1 as a control for the inner loop.
Only odd number is to be printed, so we start at val 1 and increase val be 2 each time to ensure only odd numbers are printed.
(val += 2;)
Test Run:
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
You can use two nested loops (or streams) as follows: an outer loop through rows with an odd number of elements and an inner loop through the elements of these rows. The internal action is to sequentially print and increase one value.
a loop in a loop
int n = 9;
int val = 1;
// iterate over the rows with an odd
// number of elements: 1, 3, 5...
for (int i = 1; i <= n; i += 2) {
// iterate over the elements of the row
for (int j = 0; j < i; j++) {
// print the current value
System.out.print(val + " ");
// and increase it
val += 2;
}
// new line
System.out.println();
}
a stream in a stream
int n = 9;
AtomicInteger val = new AtomicInteger(1);
// iterate over the rows with an odd
// number of elements: 1, 3, 5...
IntStream.iterate(1, i -> i <= n, i -> i + 2)
// iterate over the elements of the row
.peek(i -> IntStream.range(0, i)
// print the current value and increase it
.forEach(j -> System.out.print(val.getAndAdd(2) + " ")))
// new line
.forEach(i -> 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
See also: How do I create a matrix with user-defined dimensions and populate it with increasing values?
Seems I am bit late to post, here is my solution:
public static void firstNum() {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the odd number: ");
int num = scanner.nextInt();
if (num % 2 == 0 || num < 0) {
firstNum();
}
if (num % 2 == 1) {
int disNum = 1;
for (int i = 1; i <= num; i += 2) {
for (int k = 1; k <= i; k++, disNum += 2) {
System.out.print(disNum + " ");
}
System.out.println();
}
}
}

Categories

Resources