Unale для печати списка целочисленных массивов из для l oop in Java - PullRequest
0 голосов
/ 30 марта 2020

Фрагмент кода ниже. Я попытался инициализировать переменную за пределами для l oop, но все еще получаю ту же ошибку.

Я не могу напечатать массив переменных за пределами-l oop.

public class count_test01 {

    public static void main(String[] args) {

        int n = 2;
        countTest(n);
    }


    public static void countTest(int num){

        //int[] longCnt01_intArray01;

        int cnt01, cnt02;
        long longCnt01, longCnt02;

        longCnt01 = 1;

        // int holds 10 digits in length, MAX is 2,147,483,647.
        // long holds holds 19 digits in length, MAX is 9,223,372,036,854,775,807.
        for(int i = 1; i <= 11; i++) { //63; i++) { //(long i = 1; i <= 9000000000000000000L; i++) {            
            longCnt01 *= i; //2; //at 2, i can be <= 63.


            // Convert Integer Count to String.
            String longCnt01String = BigDecimal.valueOf(longCnt01).toPlainString(); 

            //Convert String to Integer Array.
            int[] longCnt01_intArray = new int[longCnt01String.length()];

            for (int i1 = 0; i1 <= longCnt01String.length()-1; i1++){
                longCnt01_intArray[i1] = longCnt01String.charAt(i1) - '0';
            }

            // Create new integer array, save a copy.
            int[] longCnt01_intArray01 = new int[longCnt01_intArray.length];
            for( int i2 = 0; i2 < longCnt01_intArray.length; i2++){

                longCnt01_intArray01[i2] = longCnt01_intArray[i2];
            }

            System.out.println("Count of i           : " + i + "\n");
            System.out.println("Count of longCnt01   : " + longCnt01 + "\n");
            System.out.println("Size of longcnt01    : " + Arrays.toString(longCnt01_intArray) + "\n\n");
        //System.out.println("Size of longCnt01    : " + Arrays.toString(longCnt01_intArray01) + "\n");
        }

        System.out.println("Size of longCnt01    : " + Arrays.toString(longCnt01_intArray01) + "\n");
        System.out.println("Count of longCnt01   : " + longCnt01 + "\n");
}

Жалуется на большое количество кода и недостаточное количество напечатанного текста.

1 Ответ

0 голосов
/ 30 марта 2020

Хорошо, я обдумал рабочее решение того, как я бы go об этом. Я переработал большую часть кода, просто чтобы предупредить вас, поэтому, пожалуйста, спросите, есть ли у вас какие-либо вопросы или вы хотите знать, как настроить его для ваших нужд, если он не совсем соответствует вашим ожиданиям.

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Example {

  public static void main(String[] args) {
    int n = 2;
    countTest(n);
  }

  public static void countTest(int num) {
    int cnt01, cnt02;
    long longCnt01, longCnt02;

    //Make a scalable arraylist to hold all the copies
    List<Integer[]> copies = new ArrayList<>();

    longCnt01 = 1;

    for (int i = 1; i <= 11; i++) { 
      //Moved print here to keep it logically close to it's related component
      System.out.println("Count of i           : " + i + "\n");

      longCnt01 *= i;
      //Moved print here to keep it logically close to it's related component
      System.out.println("Count of longCnt01   : " + longCnt01 + "\n");

      // First thing, refactored the Integer array retrieval into it's own method 
      // and use Integer class instead to make use of a scalable ArrayList
      Integer[] longCnt01_intArray = getIntArrayFromCount(longCnt01);

      // Quick and easy way to make a copy then store in the arraylist for later use
      copies.add(longCnt01_intArray.clone());
    }

    //Use a loop to gro through all copies
    for(int i = 0; i < copies.size(); i++) {
      System.out.println("Size of Copy " + i + ": " + Arrays.toString(copies.get(i)) + "\n");
    }
    System.out.println("Count of longCnt01   : " + longCnt01 + "\n");
  }

  private static Integer[] getIntArrayFromCount(long count) {
    // Convert Integer Count to String.
    String longCnt01String = BigDecimal.valueOf(count).toPlainString();

    // Convert String to Integer Array.
    Integer[] longCnt01_intArray = new Integer[longCnt01String.length()];

    for (int i1 = 0; i1 < longCnt01String.length(); i1++) {
      longCnt01_intArray[i1] = longCnt01String.charAt(i1) - '0';
    }

    //Moved print here to keep it logically close to it's related component
    System.out.println("Size of longcnt01    : " + Arrays.toString(longCnt01_intArray) + "\n\n");

    return longCnt01_intArray;
  }
}
...