2013-11-17 3 views
0

Я все еще новичок в Java и задавался вопросом, есть ли способ сократить мой массив, чтобы использовать оператор остатка, чтобы начать новую строку, когда 5 переходит в число, и нет ничего лишнего? Я пытаюсь понять это с сегодняшнего утра и, похоже, не добился никакого прогресса. Благодарим вас за помощь.Упрощение многострочного массива

public class arrayTest { 

     public static void main(String args[]) { 
      final int ARRAY_LENGTH = 25;   // number of ints 
      int array[] = new int[ ARRAY_LENGTH ]; // calculate value for each array element 

      for (int counter = 0; counter < 5; counter++) 
       System.out.printf("%d, ", counter); 
      for (int counter = 5; counter < 6; counter++) 
       System.out.printf("%d\n", counter); 
      for (int counter = 6; counter < 10; counter++) 
       System.out.printf("%d, ", counter); 
      for (int counter = 10; counter < 11; counter++) 
       System.out.printf("%d\n", counter); 
      for (int counter = 11; counter < 15; counter++) 
       System.out.printf("%d, ", counter); 
      for (int counter = 15; counter < 16; counter++) 
       System.out.printf("%d\n", counter); 
      for (int counter = 16; counter < 20; counter++) 
       System.out.printf("%d, ", counter); 
      for (int counter = 20; counter < 21; counter++) 
       System.out.printf("%d\n", counter); 
      for (int counter = 21; counter < 25; counter++) 
       System.out.printf("%d, ", counter); 
      for (int counter = 25; counter < 26; counter++) 
       System.out.printf("%d\n", counter); 
     } 

    } 
+0

Что ... вы пытаетесь сделать? И почему вы не используете только один цикл для этого? – Makoto

+0

Используйте один цикл и 'modulo' operator'% ' –

+1

В качестве примечания стороны: имена классов в Java по соглашению должны начинаться с буквы верхнего регистра. Прочитайте это: [Условные обозначения для языка программирования Java] (http://www.oracle.com/technetwork/java/codeconv-138413.html) – informatik01

ответ

1
public class arrayTest 
{ 

public static void main(String args[]) 
{ 
    final int ARRAY_LENGTH = 25; // number of ints 
    int array[] = new int[ ARRAY_LENGTH ];// calculate value for each array element 
    for (int counter = 0; counter < array.length; counter++) { 
    System.out.printf("%d, ", counter); 
    if (counter%5 == 4) { 
    System.out.printf("\n"); // System.out.println() also works 
    } 
    } 
} 

} 
+0

Err ... это дает другой вывод для кода OP ... – Melquiades

+0

Да, потому что его первый для итераций 6 раз (я предположил, что это ошибка), и он не отображает конечную запятую (легко реализовать, как только он понимает, как работают и работают остальные). Я не хотел усложнять этот пример. –

0

Используйте это после того, как вы инициализировать ваш массив

for(int i=0; i<ARRAY_LENGTH;i+=5){ 
    for(int counter=i;counter<i+5;counter++){ 
     array[counter]=counter; 
     System.out.print(counter); 
    } 
    System.out.print("\n"); 
} 
+0

Этот код печатает только числа, которые делятся на 5, дают остаток 0, если я не понял его намерения, это отличается от исходного вывода OP. – Melquiades

+0

ОК, вы правы, я отредактирую его. thanks :) – ismail

0

Вам нужно использовать только одну петлю следующим образом:

final int ARRAY_LENGTH = 25; 
int[] array = new int[ARRAY_LENGTH]; 
for(int i = 1; i <= ARRAY_LENGTH; i++){ 
    array[i - 1] = i % 5; 
    System.out.println(i % 5); 
+0

Этот код вставляет новую строку на каждой итерации, а это не то, что требуется OP. Кроме того, вам не хватает закрывающей скобки в конце. – Melquiades

0

Заменить для петель с этим (тот же результатом как ваша программа), комментарии в коде:

public class arrayTest { 

    public static void main(String args[]) { 
     final int ARRAY_LENGTH = 25;   // number of ints 
     int array[] = new int[ ARRAY_LENGTH ]; // calculate value for each array element 

     for (int counter = 0; counter < ARRAY_LENGTH; counter++) { 
      array[counter] = counter; 
      System.out.printf("%d, ", counter); 

      //skip 0, then if current number modulo 5 is zero (no remainder) 
      //insert new line 
      if (counter > 0 && counter % 5 == 0) System.out.println(); 
     } 
     //to add 25 at the end, as in your code, you can do this: 
     //this is because our loop starts at 0 and goes until 24 
     System.out.println(ARRAY_LENGTH); 
    } 
} 
Смежные вопросы