1

I'm doing a relatively simple file read, and I've been experiencing anomalies in my validation between an input value and a data value read from a flat file and stored in an array. I've traced the error to the firstName field. I'm defining this field as equal to array[0]. While array[0] displays perfectly in my output, fieldName does not...it's either blank or null.

Here's my code, with an output sample.

I'm not sure if Stringbuilder is most appropriately used here? or one of the deep String methods? None of what I've tried seems to work. What am I missing...I know it's something obvious that I just can't see.

public class DisplaySelectedNumbers
{
    public static void main(String[] args)
    {
        final String FN = "            ";
        final String LN = "            ";
        final String PHONE = "0000000000";
        String delimiter = ",";
        String s = FN + delimiter + LN + delimiter + PHONE + System.getProperty("line.separator");
        final int RECSIZE = s.length();
        String[] array = new String[3];
        Scanner kb = new Scanner(System.in);
        Path file = Paths.get("PhoneList.txt");
        String fName = JOptionPane.showInputDialog(null,"Enter first name to search");
        try
        {
            InputStream iStream=new BufferedInputStream(Files.newInputStream(file));
            BufferedReader reader=new BufferedReader(new InputStreamReader(iStream));
            while ((s = reader.readLine()) != null)
            {
                array = s.split(delimiter);
                String dispString = array[0]+" "+array[1]+" "+array[2]+"\n";
                System.out.println("array[0]="+array[0]);
                System.out.println("array[1]="+array[1]);
                System.out.println("array[2]="+array[2]);
                String firstName = array[0];
                System.out.println("firstName=");
                    s=reader.readLine();
            }
        }
        catch(Exception e)
        {
            System.out.println("Message: " + e);
        }
    }
}


array[0]=D
array[1]=JJ
array[2]=0123450000
firstName=
array[0]=B
array[1]=EE
array[2]=1111111111
firstName=
array[0]=D
array[1]=GG
array[2]=0033333333
firstName=
dwwilson66
  • 6,806
  • 27
  • 72
  • 117

2 Answers2

5

You forgot to actually print the firstName variable:

System.out.println("firstName="); 

You need instead:

System.out.println("firstName=" + firstName); 
Attila
  • 28,265
  • 3
  • 46
  • 55
1

Not really a complete answer for your question, but yes, using StringBuilder in your code would be better if you need to improve String concatenation speed, specially in a loop.

StringBuilder vs String concatenation

Community
  • 1
  • 1
ceklock
  • 6,143
  • 10
  • 56
  • 78