簡體   English   中英

如何從 txt 文件中讀取整數和雙精度數

[英]How to read both integers and doubles from txt fle

我有一個文本文件,我想讀取整數和雙精度數。 我不知道我必須閱讀多少個值。 行中的第一個值始終是 integer,第二個值始終是雙精度值。 我想單獨保存第一行的值。

 200
  11010 0.004
    500 0.02
    637 0.018

如何創建 2 個 arrays 並保存值,以便我以后可以使用它們? 我不允許創建新的 class。 我嘗試使用 Point 但無法存儲雙打。

Scanner scanner = new Scanner(new File(args[0]));
        int cores= scanner.nextInt();
        System.out.print(cores);
    while (scanner.hasNext()) {
        int x = scanner.nextInt();
        double y = scanner.nextDouble();
        System.out.printf("x");}

我已經嘗試了上面的代碼,但拋出了異常

您可以使用簡單的文件處理方法逐行讀取文件,對於第一行,您可以使用標志來標記該行並將文件發送到要保存數據的遠程位置。 然后對於所有后面的行,您可以根據“”(空格)拆分字符串。 發布后,一旦您剝離了結果數組的元素,您就可以進行類型轉換和 append 將元素放在 integer 數組的第一個索引處。 並將第二個元素(附加前的類型轉換)添加到雙精度數組。 這適用於任何長度的文件。

相同的演示代碼如下:

public class ReadLineByLine  
{  
    public static void main(String args[])  
    {  
        try  
        {  
            FileInputStream fis=new FileInputStream("Demo.txt");       
            Scanner sc=new Scanner(fis);   
            String tempLineData = "";
            int flag = 0;
            String[] elements;
            List<Integer> ints = new ArrayList<Integer>(
            List<Float> floats = new ArrayList<Float>(
            while(sc.hasNextLine())  
            {  
                if(flag == 0){
                    // Place the operation with the first line here 
                    flag++;
                }
                tempLineData=sc.nextLine();        
                elements = tempLineData.split(" ");
                ints.add((int)elements[0].trim());
                floats.add((float)elements[1].trim());
            }  
            sc.close();     
        }  
        catch(IOException e)  
        {  
            e.printStackTrace();  
        }  
    }  
}  

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM