2015-11-02 24 views
1

我有一個簡單的問題。 我在java中寫了一個方法來獲取文本文件的內容。獲取java中的文本文件的內容?

public static String[] viewSuppliers() 
{ 
    Scanner x = null; 
    try{ 
     x = new Scanner(new File("C:\\Users\\فاطمة\\Downloads\\suppliers.txt")); 
     while(x.hasNext()) 
     { 
      String a = x.next(); 
      String b = x.next(); 
      String c = x.next(); 
      String d = x.next(); 
      String array[] = {a,b,c,d}; 
      return array; 
     } 
     x.close(); 
    } 
    catch(Exception e) 
    { 
     e.printStackTrace(); 
    } 
    return null; 
} 

我在主程序中調用了這個方法,但它只返回一行文件。我的文本文件的內容是這樣的:

PEPSI John London 214222 
COLA Sarah France 478800 

這裏是我的主要程序:

String array3[] = {"Supplier Company: ", "Supplier Name: ", "Supplier Address: ", 
    "Supplier Phone Number: "}; 
String array4[] = i.viewSuppliers(); // object of class 
if(i.viewSuppliers() == null) 
    System.out.println("No current suppliers."); 
else 
{ 
    System.out.println("Current Suppliers: "); 
    for(int u = 0; u < array3.length; u++) 
    { 
     System.out.printf(array3[u]); 
     System.out.println(array4[u]); 
    } 
} 

當我運行主程序並調用該方法是隻返回第一線,我想返回所有文件。

+1

您在第一次迭代結束時返回數組,導致它僅處理第一個迭代。 – Reisclef

回答

2

,而不是返回的4個字符串數組, 的好像你真正想要的是返回的4個字符串數組列表:

public static List<String[]> viewSuppliers() 
{ 
    List<String[]> lines = new ArrayList<>(); 
    Scanner x = null; 
    try{ 
     x = new Scanner(new File("C:\\Users\\فاطمة\\Downloads\\suppliers.txt")); 
     while(x.hasNext()) 
     { 
      String a = x.next(); 
      String b = x.next(); 
      String c = x.next(); 
      String d = x.next(); 
      String array[] = {a,b,c,d}; 
      lines.add(array); 
     } 
     x.close(); 
    } 
    catch(Exception e) 
    { 
     e.printStackTrace(); 
    } 
    return lines; 
} 

然後,遍歷結果:

List<String[]> list = i.viewSuppliers(); // object of class 
if (list.isEmpty()) 
    System.out.println("No current suppliers."); 
else 
{ 
    System.out.println("Current Suppliers: "); 
    for (String[] supplier : list) { 
     for(int u = 0; u < array3.length; u++) 
     { 
      System.out.printf(array3[u]); 
      System.out.println(supplier[u]); 
     } 
    } 
} 
+0

哇,你是驚人的兄弟,它的作品非常感謝你這麼多:) –

0

嘗試把回報了while循環,它返回第一個迭代後除外。

+0

是的,我試過這個,但問題是數組從while循環中獲取參數,當它返回到外部時,顯示我沒有聲明該數組。 –

0

根據array3的長度,你有一個循環的輸出,但不是array4,所以它總是隻打印第一個供應商,因爲array3的長度。

System.out.println("Current Suppliers: "); 
for(int u = 0; u < array3.length; u++) 
{ 
    System.out.printf(array3[u]); 
    System.out.println(array4[u]); 
} 

也許將System.out.println(array4)添加到基於其長度低於第一個循環的循環中。