Reputation: 1820
I Think I broke this down to the most basic form. If not then I apologize and will try to edit it. Why in my while loop do I need to cast String for the FirstName if I already set the variable to be a String? Am I doing something wrong? I am try to set the FirstName variable to be equal to the first token which is supposed to be the first word of the text file etc.
try
{
BufferedReader infileCust =
new BufferedReader(new FileReader("C:\\custDat.txt"));
}
catch(FileNotFoundException fnfe)
{
System.out.println(fnfe.toString());
}
catch(IOException ioe)
{
System.out.println(ioe.toString());
}
}
public static void createCustomerList(BufferedReader infileCust,
CustomerList custList) throws IOException
{
String FirstName;
String LastName;
int CustId;
//take first line of strings before breaking them up to first last and cust ID
String StringToBreak = infileCust.readLine();
//split up the string with string tokenizer
StringTokenizer st = new StringTokenizer(StringToBreak);
while(st.hasMoreElements()){
FirstName = (String) st.nextElement();
LastName = (String) st.nextElement();
CustId = Integer.parseInt((String) st.nextElement());
}
Edit: Apprently I can use nextToken() instead. But how come my variables are being shown as not used? Are they not within the scope of the while loop?
Upvotes: 3
Views: 2697
Reputation: 726919
This is because nextElement
returns Object. If you call nextToken
, you would not need to cast.
From the documentation:
public Object nextElement()
Returns the same value as the nextToken method, except that its declared return value is Object rather than String. It exists so that this class can implement the Enumeration interface.
EDIT Regarding the variables that are not used: the reason you get the warning is that the variables are assigned, but not printed, saved, or analyzed in some way. If you add a call to, say, writeln
with first and last name, the warnings would go away.
Upvotes: 6
Reputation: 49577
Because StringTokenizer.nextElement() returns
The same value as the nextToken method, except that its declared return value is Object rather than String.It exists so that this class can implement the Enumeration interface.
Upvotes: 2
Reputation: 4079
Because StringTokenizer.nextElement
returns a java.lang.Object
. See the docs here: http://docs.oracle.com/javase/1.4.2/docs/api/java/util/StringTokenizer.html You can use nextToken() : String
instead if you prefer.
Upvotes: 3