I want to read the data from an "DataFile.txt" file, but in a program I have 2 integers, so how can I pass integers ("days" and "tprice" variables are supposed to be integers) using StringTokenizer?
private void readDataFileAndDisplay()
{
String allRecord=""; // all details of customer
try
{
Scanner in = new Scanner (new FileReader ("DataFile.txt")); //open file
String myEntry = "" ;
String name ="";
String ID="";
String roomType ="";
String meal="";
String days="";
String tprice="";
while (in.hasNextLine ())
{
myEntry = in.nextLine();
StringTokenizer st = new StringTokenizer (myEntry, ",");
while (st.hasMoreTokens ())
{
name = st.nextToken();
ID = st.nextToken();
name = st.nextToken();
roomType = st.nextToken();
meal = st.nextToken();
days = st.nextToken();
tprice =st.nextToken();
myList.add (new Customer (name, ID, roomType, meal, days, tprice));
}
} // end of while loop
in.close(); // close file
} catch (IOException ex)
{
System.out.println ("file loading failed.");
}
}
I have also tried parseInt like:
int Intdays = Integer.parseInt (st.nextToken ());
int IntTprice = Integer.parseInt (st.nextToken ());
but after compiling it is showing the exception below:
name = st.nextToken();
ID = st.nextToken();
name = st.nextToken();
roomType = st.nextToken();
meal = st.nextToken();
days = st.nextToken();
tprice =st.nextToken();
int Intdays = Integer.parseInt(days);
int IntTprice = Integer.parseInt(tprice);
myList.add(new Customer(name,ID,roomType,meal,Intdays,IntTprice));
Try with this code.
days = Integer.parseInt (st.nextToken ());
tprice = Integer.parseInt (st.nextToken ());
would do it, if you declare days and tprice as int.
But you can use your Scanner directly - I show how to with a String instead of a file, which is better for demonstration:
data = "John, Miller, 303, 404";
sc = new java.util.Scanner (data);
sc.useDelimiter (", ");
name = sc.next (); // John
surname = sc.next (); // Miller
tdays = sc.nextInt (); // 303
You are trying to read name twice. Your data has only 6 fields where as you are trying to read 7 fields. (name = st.nextToken() looks like a typo)
while (st.hasMoreTokens ())
{
name = st.nextToken();
ID = st.nextToken();
name = st.nextToken();
roomType = st.nextToken();
meal = st.nextToken();
days = st.nextToken();
tprice =st.nextToken();
myList.add (new Customer (name, ID, roomType, meal, days, tprice));
}
this is wrong. You need to check for st.hasMoreTokens() every time before you call st.nextToken().
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.