Reputation: 155
I have a simple problem. I wrote a method in java to get the contents of text file.
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;
}
I have called this method in main program but it only returns one line of the file. The contents of my text file are like this:
PEPSI John London 214222
COLA Sarah France 478800
Here is my main program:
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]);
}
}
When i run the main program and call the method it is only return the first line and i want to return all the file.
Upvotes: 1
Views: 552
Reputation: 21
You have the output on a loop based on the length of array3, but not array4, so it will always only print the first supplier because of the length of array3.
System.out.println("Current Suppliers: ");
for(int u = 0; u < array3.length; u++)
{
System.out.printf(array3[u]);
System.out.println(array4[u]);
}
Perhaps adding the System.out.println(array4) to a loop based on its length below the first loop.
Upvotes: 0
Reputation: 124648
Instead of returning an array of 4 strings, it seems what you really want is to return a list of array of 4 strings:
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;
}
Then, iterate over the results:
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]);
}
}
}
Upvotes: 2
Reputation: 172
Try take the return out of the while loop, otherwise after the first iteration it returns.
Upvotes: 0