簡體   English   中英

使用.split()方法並僅獲取創建的字符串數組的一部分

[英]Using .split() method and getting only part of the string array created back

我需要從.dat文件中讀取文本,如下所示:

4
Mary 13.99
Ruth 22.04
Anne 12.39
Talor 18.34

我使用了一個看起來像這樣的緩沖讀卡器:

public class Tester{

    public static void main(String [] args){

       BufferedReader reader = null;

       try {
           File file = new File("C:\\Users\\hoguetm\\workspace\\practiceproblems\\beautiful.dat");
           reader = new BufferedReader(new FileReader(file));

           String line;

           while ((line = reader.readLine()) != null) {
               //System.out.println(line);
               //split will go here
               String[] str1Array =  line.split(" ");
               System.out.println(str1Array[0]);

               //works

               /*
               for (String retval: line.split(" ")){
                    System.out.println(retval);
               }
               */
           }

       } catch (IOException e) {
           e.printStackTrace();
       } finally {
           try {
               reader.close();
           } catch (IOException e) {
               e.printStackTrace();
           }
       }
   }  

}

我需要在除4之外的行末尾添加數字並打印出總和,但是當我將[0]更改為[1]時,它表示超出范圍。 請幫忙

不要拆分第一行。 分開第二行。

reader.readLine(); //added this line

while ((line = reader.readLine()) != null){

}

這是因為第一行只有一個字段。 試試這個:

double total = 0;
while ((line = reader.readLine()) != null) {
           String[] str1Array =  line.split(" ");
           if(str1Array.length > 1) {
               System.out.println(str1Array[1]);
               total += Double.parseDouble(str1Array[1]);
           }
       }

String.split(String)方法根據API-Documentation丟棄數組末尾的所有emtpy字符串。 如果您需要返回固定大小的數組,請使用line.split(" ",-1) - 但要准備好在結果中處理空字符串。

1超出第一行的范圍。 String.split()將為第一行返回一個包含1個元素(整行)的數組,然后返回一個包含所有其他行的2個元素的數組。

這個.dat文件的一般格式是什么? 它是第一行的單個數字,然后是所有后續行的名稱/數字對嗎? 如果是這種情況,我建議忽略第一行(在循環之前使用額外的reader.readLine()調用。或者可以在整個文件中添加單個數字行?如果是這種情況,那么我建議檢查每次循環時數組的長度,如果長度為2,則只執行add。

如果您的輸入文件保證采用您發布的格式,則可以執行以下操作:

reader.readLine();
while ((line = reader.readLine()) != null) {
    ...

這將導致您的讀者使用文件的第一行並完全忽略它。 也就是說,您發布的文件表明第一行表示后面的行數,這意味着您應該解析它並使用for循環。 例如:

int nLines = Integer.parseInt(reader.readLine());
for(int i = 0; i < nLines; i++)
{
    line = reader.readLine();
    ...
}

這完全基於您提供的小樣本。 有關dat文件規范的更多信息將非常有用。

嘗試這個

int count =Integer.parseInt(reader.readLine());
String line;
while (count>0) {
    line = reader.readLine();             

    //System.out.println(line);
  //split will go here

 String[] str1Array =  line.split(" ");
System.out.println(str1Array[0]);

   //works

           /*
           for (String retval: line.split(" ")){
                System.out.println(retval);
           }
           */
 count--;
       }

暫無
暫無

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

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