-4

我在字符串中有一个完整的一维数据数组。我需要将此一维数组转换为双数组以进行计算。但我无法弄清楚。如果我能弄清楚,那就太好了。我不确定,但如果我可以在数据文件中读取双精度并解析数据之间的空白,那也很棒。ps 数据被排列为坐标而不是如下所示的聚束,但我这样做的方式不会被读取为 x 和 y,而只会被读取为 1d 数组线。

代码:

file = new File("subtractedvectors.txt");
    scan = new Scanner(file);

    String [] subarray = new String[40];


    for(int row = 0; row < subarray.length; row++)
    {
        subarray[row] = scan.nextLine();
    }


    for(int row = 0; row < subarray.length; row++)
    {
        System.out.println(subarray[row] + " ");
    }

数据:

-0.2869350880499999 0.01840283447500002 
-0.3356446340499999 -0.422276631525 
-1.0879343110499997 -0.311055704525 
-1.8794583530499998 1.268985311475 
-2.0487925240499996 -3.404131234525 
-0.7463400580499997 -0.05142237152500001 
1.2400316559500002 2.965222622475 
1.1715767139500004 -1.1113755165249999 
-0.4877369190499996 0.020307310475000007 
-0.8296528740499998 -0.611436447525 
0.43321626695000015 1.483144874475 
-0.4486841620499997 -4.199991639525 
-0.5980551060499999 -0.180287944525 
-0.9379483020499997 -1.605169775525 
0.15643726595000018 -2.591523262525 
2.19071678095 -1.041180241525 
-0.035047204049999614 0.107759270475 
-0.2796619480499998 1.174812069475 
-0.36357588404999985 -1.952647147525 
-0.1541381710499996 4.825189096475 
-0.5386256110499996 -0.129932855525 
-0.45958803605 1.054999589475 
0.5778822969500004 -1.580357584525 
2.1483562569500005 2.572258306475 
1.27904823795 1.228401456475 
0.9637480429500003 -1.766055860525 
0.33140834695 -0.18790365852500002 
-0.047555686049999935 2.585936438475 
1.2005633959500002 0.22278022747500004 
-1.4305940340499999 -1.694298031525 
-0.41707550904999957 -1.004148960525 
0.3517812019500002 0.599364130475 
-0.4172730140499996 3.248876134475 
-1.0244646370499997 2.770375020475 
-0.9653208200499999 -3.841495616525 
-0.7291669410499997 1.323124606475 
2.3113769619500006 -2.065505287525 
2.0595313709500003 1.454475365475 
-1.0216935320499998 1.511419720475 
1.15528856295 -0.683638613525 
4

2 回答 2

1

你可以试试这段代码。
这段代码的作用是读取字符串数组。
根据两个数字之间的单个空格将其拆分为两部分
,然后将其解析为加倍

String [] subarray = new String[40];
for(int row = 0; row < subarray.length; row++)
{
  subarray[row] = scan.nextLine();
}
double [][] myDoubleArray = new double[40][2];
for(int row = 0; row < subarray.length; row++)
{
  String s = subarray[row].split();//assuming that two doubles are seperated by a space  
  myDoubleArray[row][0] = Double.parseDouble(s[0]);
  myDoubleArray[row][1] = Double.parseDouble(s[1]);
}
于 2013-02-02T17:54:42.307 回答
0

您使用的Scannerwith 支持寻找Double带有特定分隔符的 a。

String input = "-1.25 1.65\n 1.47 5.72";

Scanner scanner = new Scanner(input);
scanner.useLocale(Locale.US);
scanner.useDelimiter("[\\r\\n\\s]+");

while (scanner.hasNextDouble()) {
   System.out.println(scanner.nextDouble());
}

输出:

-1.25
1.65
1.47
5.72

我的示例中的分隔符应该根据您问题中的示例数据为您工作。我可以建议一个而不是使用一个数组List吗?

于 2013-02-02T17:58:40.517 回答