以特定格式从阵列打印元素

时间:2015-05-23 08:20:50

标签: java arrays

我有两个数组

import java.util.Scanner; 
import javax.swing.JOptionPane; 

public class LengthConversion { 

    public static void main(String[] args) {

        double cmValue, inchValue;
        int choice;

        //Create Scanner object
        Scanner fromKeyboard = new Scanner(System.in);

       //Customise Object text
       Object[] options = {"cm-to-inch", "inch-to-cm", "Cancel"};

       //Option Dialog box
       choice = JOptionPane.showOptionDialog(null, "Choice an option", "Length Conversion", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.INFORMATION_MESSAGE, null, options, options[2]);

      //Begin 'if' Statement
      if (choice == 0) {
          //Show Input Dialog Box
          String inputType = JOptionPane.showInputDialog("Enter the cm to convert:");
         //Read value that user type
         cmValue = fromKeyboard.nextDouble();
         //Compute cm to inch
         inchValue = cmValue/2.54;
         //Preview result
         String outputType = JOptionPane.showInputDialog(null, +inchValue+" inches");
     } else {
         //Ask user to enter value
         String inputType = JOptionPane.showInputDialog("Enter the inch to convert:");
         //Read value that user type
         inchValue = fromKeyboard.nextDouble();
         //compute inch to cm
         cmValue = inchValue * 2.54;
         //Display result
         JOptionPane.showMessageDialog(null, +cmValue+" cm");
     } //end of 'else' Statement
 } //end main
} //end class Length Conversion

输出应为

int a[]={1,2,3,4,5,6,7,8,9};

int b[]={4,2,3}

输出应该是这样的

b[0] has 4 so the first line of output should be  1,2,3,4 (from array a )
b[1] has 2 so the 2nd line of output should be 5,6  (from array a )
b[2] has 3 so the 3rd line of outout should be 7,8,9  (from array a )

我正在尝试使用此代码,但它无效

1,2,3,4
5,6
7,8,9

注意:数组for(i=0;i<b[j];i++) { if(flag==false){ System.out.print(a[i]); flag=true; } else System.out.print(" "+a[i]); } j=j+1; System.out.print("\n"); a

中可以包含任意数量的元素

3 个答案:

答案 0 :(得分:1)

int cur = 0;                                    //denotes index of array a
for (int i=0; i<b.length; i++) {                //looping on the elements of b

    int count = b[i], j;                       //count: number of elements to print is in b[i]
    for(j=cur; j<cur+count && j<a.length; j++) //looping from current index in array a to the next "count" elements which we need to print
       System.out.print(a[j]+",");             //print the elements for one line
    System.out.println();
    cur = j;                                  //updating the new index of array a from where to start printing  
}

答案 1 :(得分:1)

我们通过在整数变量a[]中保存b[]元素的运行总计来跟踪我们在nextIndex中达到的索引。

注意:此代码的先决条件是,b[]元素的总和不得大于a[]中元素的数量。

public static void main(String[] args) {

    int[] a = { 1,2,3,4,5,6,7,8,9 };
    int[] b = { 4,2,3 };

    int nextIndex = 0;

    for (int i = 0; i < b.length; i++) {

        for (int j = nextIndex; j < nextIndex + b[i]; j++) {

            if (j == (nextIndex + b[i] - 1)) {
                System.out.print(a[j]);
            }
            else {
                System.out.print(a[j] + ",");
            }

        }

        nextIndex += (b[i]);

        System.out.println();

    }
}

答案 2 :(得分:1)

当你使用Arrays.copyOfRange(int[] original, int from, int to)从原始数组中提取“sub”数组时,一个for循环足以完成你想要的东西。 Arrays.toString()为您打印数组。

public static void main(String[] args) throws Exception {
    int a[] = {1, 2, 3, 4, 5, 6, 7, 8, 9};
    int b[] = {4, 2, 3};

    int aIndex = 0;
    int bIndex = 0;
    for (int i = 0; i < b.length; i++) {
        bIndex += b[i]; // Keeps track of the ending index of the copying
        System.out.println(Arrays.toString(Arrays.copyOfRange(a, aIndex, bIndex)));
        aIndex += b[i]; // Keeps track of the starting index of the copying
    }
}

结果:

[1, 2, 3, 4]
[5, 6]
[7, 8, 9]