我有一个简单的问题。我在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]);
}
}
当我运行主程序并调用该方法时,它仅返回第一行,并且我想返回所有文件。
您似乎真正想要的不是返回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]);
}
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句