我正在参加编程类(class),但事情并不适合我。我有一项作业要求:
Write a program to assign the integer values 1 through 25 to a 25 element integer array. Then, print the array as five separate lines each containing five elements separated by commas. The last element on each line should be followed by a newline instead of a comma. The output of your program should appear exactly as follows:
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
Hints:
- One way to determine every 5th element is to use the modules operator (%). If you divide the subscript by 5 and the remainder is 0, it is the 5th number.
- You can use System.out.print() to print a value without a newline following it. This will allow you to print multiple things on the same line.
我有一些代码,但我不知道从这里去哪里:
public class Program4
{
public static int[] array;
public static void main(String[] args);
{
int[] numbers = new int [25]
for(int i=0; i<25; i++)
array[i] = i + 1;}
public static void printArray()
{
for(int i=1; i<=25; i++);
{
System.out.print(array[i - 1]);
if (i % 5 == 0)
System.out.printIn();
}
}
我只是对编程有一个心理障碍 - 谁能帮我指出一些有用的例子?
最佳答案
试试这个,
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
public static int[] array;
public static void main(String[] args)
{
array = new int[25];
for(int i=0; i<25; i++)
array[i] = i + 1;
printArray();
}
public static void printArray()
{
int i;
for(i=1; i<=25; i++){
if (i % 5 != 0)
System.out.print(array[i-1]+",");
else
System.out.println(array[i-1]);
}
}
}
关于java - 多行打印数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22179557/