2013-11-23 84 views
2
public static void main(String[] args) { 
try{ 
    BufferedReader br=new BufferedReader(new FileReader("file.txt")); 

    String[] pole=br.readLine().split(" "); 
    double L=Double.parseDouble(pole[0]); 
    double N=Double.parseDouble(pole[1]); 
    String[] weight=new String[N]; 
    double[] scale=new double[N]; 
    double[] place=new double[N]; 
    for(int i=0; i<N; i++){ 
     weight[i]=br.readLine(); 
     String[] variable=weight[i].split(" "); 
     double variable1=Double.parseDouble(variable[0]); 
     double variable2=Double.parseDouble(variable[1]); 
     scale[i]=variable2; 
     place[i]=variable1*variable2;    
    } 

我有这个java代码。我想从文件中获取数字并将它们转换为double,但它给了我这样的错误:类型不匹配:无法从double转换为int。我怎样才能解决这个问题?类型不匹配:不能从double转换为int java

回答

4

由于N为double你需要一个类型的案件有

String[] weight=new String[(int)N]; 

原因是double是浮点型,你不能创建的length 1.5 :)

+0

为什么尝试你想要tr ca吗?你的数据是否保证四舍五入? – Antoniossss

+0

@Antoniossss没错,但没有必要四舍五入。如果值0.9或0.51,我从不创建元素:)在这种情况下两者都是相同的。 –

0

N是一个双数组,但你正试图迭代它。你必须输入它。

0

你的问题是在这里..

double L=Double.parseDouble(pole[0]); 
double N=Double.parseDouble(pole[1]); 

变化

int L=Integer.parseInt(pole[0]); 
int N=Integer.parseInt(pole[1]); 

因为int只接受的数组索引..

2

与此

public class Tuple { 

    public static void main(String[] args) { 
     try{ 
      BufferedReader br=new BufferedReader(new FileReader("UserController.txt")); 

      String[] pole=br.readLine().split(" "); 
      double L=Double.parseDouble(pole[0]); 
      double N=Double.parseDouble(pole[1]); 
      System.out.println("L is "+L); 
      String[] weight=new String[(int) N]; 
      double[] scale=new double[(int) N]; 
      double[] place=new double[(int) N]; 
      for(int i=0; i<N; i++){ 
       weight[i]=br.readLine(); 
       String[] variable=weight[i].split(" "); 
       double variable1=Double.parseDouble(variable[0]); 
       double variable2=Double.parseDouble(variable[1]); 
       scale[i]=variable2; 
       place[i]=variable1*variable2;    
      } 
     } 
      catch(Exception e) { 
       e.printStackTrace(); 
      } 
    } 
} 
相关问题