2016-02-09 53 views
0

我希望将第5行中打印的值插入到整数数组中。 该文件包含整数值和字符串值
****我还在学习过程中**** 对不起,我改变了一下这个问题。 谢谢将值插入到字符串类型列表中的整数数组中

 File f = new File("SampleInput.txt"); 
      try{ 
       ArrayList<String> lines = get_arraylist_from_file(f);  
       for(int x =23; x < lines.size(); x++){ 
        System.out.println(lines.get(x)); 
        **enter code here** 
       } 
      } 
    catch(Exception e){ 
     System.out.println("File not found!!!!"); 
    } 
} 
public static ArrayList<String> get_arraylist_from_file(File f) 
    throws FileNotFoundException { 
    Scanner s; 
    ArrayList<String> list = new ArrayList<String>(); 
    s = new Scanner(f); 
    while (s.hasNext()) { 
     list.add(s.next()); 
    } 
    s.close(); 
    return list; 
} 
+0

为什么不使用List而不是Array? – basic

回答

0

更容易如下

List<Integer> list = new ArrayList<Integer>(); 
File f = new File("SampleInput.txt"); 
      try{ 
       ArrayList<String> lines = get_arraylist_from_file(f);  
       for(int x =23; x < lines.size(); x++){ 
        System.out.println(lines.get(x)); 
        list.add(Integer.parseInt(lines.get(x))); 
       } 
      } 
    catch(Exception e){ 
     System.out.println("File not found!!!!"); 
    } 
} 
0

我猜你想要的东西,像这样使用整数的ArrayList,

try{ 
    ArrayList<String> lines = get_arraylist_from_file(f); 
    ArrayList<int> intLines = new ArrayList(); 
    for (int x = 23; x < lines.size(); x++) { 
    System.out.println(lines.get(x)); 
    intLines.add(Integer.parseInt(lines.get(x))); 
    } 
} 
-1

你必须创建一个int数组在适当大小的循环之外,然后解析这些字符串并将它们添加到循环中的数组中:

  ArrayList<String> lines = get_arraylist_from_file(f); 
      int[] intArray = new int[lines.size-23]; 
      for(int x =23; x < lines.size(); x++){ 
       System.out.println(lines.get(x)); 
       //**enter code here** 
       String line = lines.get(x); 
       intArray[x-23] = Integer.parseInt(line); 
      } 
+0

你也可以''Integer.parseInt(lines.get(x));'' –

1
 List<Integer> numList = new ArrayList<>(); 
     File f = new File("SampleInput.txt"); 
     try{ 
      ArrayList<String> lines = get_arraylist_from_file(f);  
      for(int x =23; x < lines.size(); x++){ 
       System.out.println(lines.get(x)); 
       **enter code here** 
       numList.add(Integer.parseInt(lines.get(x))); 
      } 
     } 
相关问题