如何在二维数组中随机分割数据并以75%和25%格式显示它们

时间:2015-09-26 05:13:38

标签: java arrays

我从txt文件加载了一个二维数组。我需要程序分别随机显示75%和25%的数组。我尝试使用Math.random但它将数字更改为从0到1显示。我将在进一步的计算中使用这些数字。我附上了整个代码。 dataSplit方法是我分离数组的地方。我在此示例中使用的txt文件仅用于测试目的。我实际上有一个更大的文件。

提前感谢您的帮助, 阿维

P.S。我从1开始列计数,因为要忽略第1列。

这是txt文件

1 6 7 8

2 9 10 11

3 12 13 14

以下是代码

package tester;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.Random;
import java.util.Scanner;

public class Test1 {

public static void main(String[] args) throws FileNotFoundException 
{      
    Scanner inFile = new Scanner(new FileReader("one.txt"));

    float [][] glassdata = new float[3][4];

    loadArray(glassdata, inFile);
    displayArray(glassdata);

    System.out.println("\n***************\n");

    normalizingVector(glassdata);

    System.out.println("\n***************\n");

    dataSplit(glassdata);
}

public static void loadArray(float [][] g, Scanner inFile)
{
    for(int row = 0; row < g.length; row++)
    {
        for(int col = 0; col < g[row].length; col++)
        {
           g[row][col] = inFile.nextFloat();
        }
    }      
}

public static void displayArray(float [][] g)   
{
    for(int row = 0; row < g.length; row++)
    {
        for(int col = 1; col < g[row].length; col++)
        {
            System.out.print(g[row][col] + " ");
        }
        System.out.println();
    }
}

public static void normalizingVector(float [][] g)
{
    float temp1 = 0;
    float temp2 = 0;        

    for (int row = 0; row < g.length; row++)
    {
        for(int col = 1; col < g[row].length; col++)
        {               
            while(col < g[row].length)              
            {
                temp1 = temp1 + (float) Math.pow(g[row][col], 2);
                col++;
            }

            col = 1;
            temp1 = (float) Math.sqrt(temp1);

            while(col < g[row].length)
            {               
                temp2 = (g[row][col]) / temp1;
                System.out.print(temp2 + " ");
                col++;              
            }
        }

        System.out.println();
        temp1 = 0;
        temp2 = 0;
    }
}

public static void dataSplit(float [][] g)
{
    int row;
    int col;
    for(row = 0; row < g.length; row++)
    {
        for(col = 1; col < g[row].length * 0.75; col++)
        {
            System.out.print(g[row][col] + " ");
        }

        System.out.println();
    }

    System.out.println("*******!@#$$*************");

    for(row = 0; row < g.length; row++)
    {
        for(col = 2; col < g[row].length * 0.25; col++)
        {
            System.out.print(g[row][col] + " ");
        }
        System.out.println();
    }
}
}

0 个答案:

没有答案