java帮助将字符串数组转换为双数组

时间:2013-02-02 17:42:08

标签: java

我在String中有一个完整的1d数据数组。我需要将这个1d数组转换成双数组用于计算目的。但我无法弄清楚。如果我能弄清楚这会很棒。我不确定,但是如果我可以在数据文件中读取一个双精度数并解析数据之间的空白也会很棒。附:数据被安排为没有如下所示聚集的坐标,但是我这样做的方式它们不会被读作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 

2 个答案:

答案 0 :(得分: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]);
}

答案 1 :(得分:0)

您正在使用的Scanner支持查找具有特定分隔符的Double

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吗?

,而不是使用数组