java - Printing an array on a certain line -
i need help printing array, need print 6 items per line , switch next line 7th , next numbers. come in numbers array without defining how many numbers entered?
import java.util.scanner; public class numberarray { public static void main(string[] args) { scanner input = new scanner(system.in); system.out.println("how many grades want enter?"); int num = input.nextint(); int array[] = new int[num]; system.out.println("enter " + num + " grades now."); (int grades = 0 ; grades < array.length; grades++ ) { array[grades] = input.nextint(); } system.out.println("these grades have entered."); printarray(array); } public static void printarray(int arr[]) { int n = arr.length; (int = 0; < n; i++) { system.out.print(arr[i] + " \t"); } } }
i need help printing array, need print 6 items per line , switch next line 7th , next numbers.
from question, seems indicate want output this:
1 2 3 4 5 6 7 8 9 ... n
this can achieved quite simply.
option 1 - classic if statement
for(int x = 0; x < array.length; x++) { system.out.print(array[x]); if(x == 5) { // 5 because we're counting 0! system.out.println(); } }
option 2 - using ternary operator maintain on 1 line
note: more or less same. it's nice finish in these sorts of answers.
for(int x = 0; x < array.length; x++) { system.out.print(array[x] + x == 5? "\n":""); }
edit
if meant want 6 items on each line, so:
1 2 3 4 5 6 7 8 9 10 11 12 ...
then can utilize %
(the modulus operator) print out new line on every output. quite easy change, you'll need create sure you're checking value before you're outputting content. can shown in this ideone.
java arrays
No comments:
Post a Comment