I have a text file I am trying to break up with string tokenizer. Here is a few lines of the text file:
Mary Smith 1
James Johnson 2
Patricia Williams 3
I am trying to break up into first name, last name and Customer ID.
I have so far been able to do that but it stops after mary smith.
Here is my code:
public static void createCustomerList(BufferedReader infileCust,
CustomerList customerList) 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);
firstName = st.nextToken();
while(st.hasMoreElements())
{
lastName = st.nextToken();
custId = Integer.parseInt(st.nextToken());
CustomerElement CustomerObject = new CustomerElement();
CustomerObject.setCustInfo(firstName,lastName,custId);
customerList.addToList(CustomerObject);
}
}
String StringToBreak = infileCust.readLine();
reads the FIRST line from the file. And you feed the StringTokenizer with it. It's normal that StringTokenized doesn't find more tokens.
You have to create a second loop enclosing all this to read every line. It is:
outer loop: readLine until it gets null {
create a StringTokenizer that consumes *current* line
inner loop: nextToken until !hasMoreElements()
}
Well, indeed you don't need to do an inner loop because you have three different fields. It's enough with:
name = st.nextToken();
lastName = st.nextToken();
id = st.nextToken;
For the outer loop, you need to store the contents of the current line in the stringToBreak variable so that you can access it inside the loop.
You need a new StringTokenizer for each line so it needs to be inside the loop.
String stringToBreak = null;
while ((stringToBreak = infileCust.readLine()) != null) {
//split up the string with string tokenizer
StringTokenizer st = new StringTokenizer(stringToBreak);
firstName = st.nextToken();
lastName = st.nextToken();
custId = Integer.parseInt(st.nextToken());
}
First off, you want to look at your loop, specifically how you have firstName outside of the loop so that is going to throw all of you tokens off. You will be trying to create new customer objects without enough information.
Related
I'm trying to read a file that has student record(first name, last name, and grade).
I have written a simple code to accomplish this task but the code fails after reading two lines from the text file. Here is my code:
public class Student {
private final String first,last;
final int MAXGRADE = 100;
final int LOWGRADE = 0;
private final int grade;
public Student(String firstname,String lastname, int grade){
this.first = firstname;
this.last = lastname;
this.grade = grade;
}
#Override
public String toString(){
return first + " " + last + "\t" + grade;
}
}
and the driver has this code
public class driver {
public static void main(String[] args) throws FileNotFoundException {
String first_name ,last_name;
int grade;
Scanner fileInput = new Scanner(new File("data1.txt"));
while (fileInput.hasNextLine())
{
first_name = fileInput.next();
last_name = fileInput.next();
grade = fileInput.nextInt();
Student st = new Student(first_name, last_name,grade);
System.out.println(st);
}
}
}
the compiler is pointing to this
grade = fileInput.nextInt();
as the source of the error.
This code is working for me. Make Sure
The location of text file correctly given,
Integer value given at 3rd position in each line (like:- steve smith 22)
If you are using Java 8, then functional way of doing this would be:
String filePath = "C:/downloads/stud_records.txt"; // your file path
/*
* Gives you a list of all students form the file
*/
List<Student> allStudentsFromFile = Files.lines(Paths.get(filePath)).map(line -> {
String[] data = line.split("\\s+"); //Split on your delimiter
Student stud = new Student(data[0], data[1], Integer.parseInt(data[2]));
return stud;
}).collect(Collectors.toList());
Note: I've made an assumption that this:
FirstName LastName Grade
is the input file format.
From the comment you post "#AxelH each line represents a single student first, last name and grade" we can see the problem.
Your actual loop to read a line
while (fileInput.hasNextLine())
{
first_name = fileInput.next();
last_name = fileInput.next();
grade = fileInput.nextInt();
Student st = new Student(first_name, last_name,grade);
System.out.println(st);
}
Is reading 3 lines, one per fileInput.nextXXX();. What you need to do is
Read a line as a String : `String line = fileInput.nextLine();
Split that line base on the delimiter : `String[] data = line.split(" "); //Or your delimiter if not space (carefull with some names...)
Set the value from this array (parse are need for integer)
EDIT :
I have made a mistake since I am used to use nextline and not next, I can't delete the answer as it is accepted so I will update it to be more correct without changing the content.
The code is indeed correct, next will take the following input until the next delimiter, \\p{}javaWhitespace}+, but using the given solution would give you more solution to manage composed names as it could be Katrina Del Rio 3.
This question already has answers here:
How do I use a delimiter with Scanner.useDelimiter in Java?
(3 answers)
Closed 5 years ago.
Here is my program currently for retrieving data from the text file which looks like this:
try {
File file = new File("dataCollection.txt");
Scanner s = new Scanner(file);
while(s.hasNext()){
String firstName = s.next();
String lastName = s.next();
String address = s.next();
String suiteNumber = s.next();
String city = s.next();
String state = s.next();
String zipCode = s.next();
String balance = s.next();
System.out.println("First Name is " + firstName);
}
s.close();
The input file looks like this:
FirstNameFXO|LastFXO|2510 Main Street|Suite 101D|City100|GA|72249|$280.80
FirstNamePNR|LastPNR|396 Main Street|Suite 100A|City102|GA|24501|$346.01
FirstNameXZU|LastXZU|2585 Main Street|Suite 107C|City101|GA|21285|$859.40
I am trying to print out just the firstName so I can use the values later for various other uses but it outputs this instead (the output is much larger, this is just the first three lines):
First Name is FirstNameFXO|LastFXO|2510
First Name is FirstNameXZU|LastXZU|2585
First Name is FirstNameGHP|LastGHP|2097
the problem that you are using method .next() which has default delimiter whitespace so it will read and return the next series of string token until a whitespace is reached.
in your case it will return:
firstname ="FirstNameFXO|LastFXO|2510";
to solve your problem instead you can use method .nextLine()
read each line then save it in variable line and substring it to get the First Name:
while(s.hasNextLine()){
String line = s.nextLine();
String firstname = line.substring(0,line.indexOf("|"));
System.out.println("First Name is " + firstName);
}
I'm writing out a piece of a code that where I am trying to split up the user's input into 3 different arrays, by using the spaces in-between the values the user has entered. However, everytime i run the code i get the error:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
at Substring.main(Substring.java:18)
Java Result: 1
I have tried to use a different delimiter when entering the text and it has worked fine, e.g. using a / split the exact same input normally, and did what i wanted it to do thus far.
Any help would be appreciated!
Here's my code if needed
import java.util.Scanner;
public class Substring{
public static void main(String[]args){
Scanner user_input = new Scanner(System.in);
String fullname = ""; //declaring a variable so the user can enter their full name
String[] NameSplit = new String[2];
String FirstName;
String MiddleName;
String LastName;
System.out.println("Enter your full name (First Middle Last): ");
fullname = user_input.next(); //saving the user's name in the string fullname
NameSplit = fullname.split(" ");//We are splitting up the value of fullname every time there is a space between words
FirstName = NameSplit[0]; //Putting the values that are in the array into seperate string values, so they are easier to handle
MiddleName = NameSplit[1];
LastName = NameSplit[2];
System.out.println(fullname); //outputting the user's orginal input
System.out.println(LastName+ ", "+ FirstName +" "+ MiddleName);//outputting the last name first, then the first name, then the middle name
new StringBuilder(FirstName).reverse().toString();
System.out.println(FirstName);
}
}
Split is a regular expression, you can look for one or more spaces (" +") instead of just one space (" ").
String[] array = s.split(" +");
Or you can use Strint Tokenizer
String message = "MY name is ";
String delim = " \n\r\t,.;"; //insert here all delimitators
StringTokenizer st = new StringTokenizer(message,delim);
while (st.hasMoreTokens()) {
System.out.println(st.nextToken());
}
You have made mistakes at following places:
fullname = user_input.next();
It should be nextLine() instead of just next() since you want to read the complete line from the Scanner.
String[] NameSplit = new String[2];
There is no need for this step as you are doing NameSplit = user_input.split(...) later but it should be new String[3] instead of new String[2] since you are storing three entries i.e. First Name, Middle Name and the Last Name.
Here is the correct program:
class Substring {
public static void main (String[] args) throws java.lang.Exception {
Scanner user_input = new Scanner(System.in);
String[] NameSplit = new String[3];
String FirstName;
String MiddleName;
String LastName;
System.out.println("Enter your full name (First Middle Last): ");
String fullname = user_input.nextLine();
NameSplit = fullname.split(" ");
FirstName = NameSplit[0];
MiddleName = NameSplit[1];
LastName = NameSplit[2];
System.out.println(fullname);
System.out.println(LastName+ ", "+ FirstName +" "+ MiddleName);
new StringBuilder(FirstName).reverse().toString();
System.out.println(FirstName);
}
}
Output:
Enter your full name (First Middle Last): John Mayer Smith
Smith, John Mayer
John
java.util.Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace.
hence even though you entered 'Elvis John Presley' only 'Elvis' is stored in the fullName variable.
You can use BufferedReader to read full line:
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
try {
fullname = reader.readLine();
} catch (IOException e) {
e.printStackTrace();
}
or you can change the default behavior of scanner by using:
user_input.useDelimiter("\n"); method.
The exception clearly tells that you are exceeding the array's length. The index 2 in LastName = NameSplit[2] is out of array's bounds. To get rid of the error you must:
1- Change String[] NameSplit = new String[2] to String[] NameSplit = new String[3] because the array length should be 3.
Read more here: [ How do I declare and initialize an array in Java? ]
Up to here the error is gone but the solution is not correct yet since NameSplit[1] and NameSplit[2] are null, because user_input.next(); reads only the first word (*basically until a whitespace (or '\n' if only one word) is detected). So:
2- Change user_input.next(); to user_input.nextLine(); because the nextLine() reads the entire line (*basically until a '\n' is detected)
Read more here: [ http://www.cs.utexas.edu/users/ndale/Scanner.html ]
hello guys I need help with reading from file with space delimiter. The problem is for example i got a text file the format as follows: id name
example:
1 my name
how can I get the string together (my name) as the code I have tried would only get me (my). I can't change the delimiter from the text file
while(myScanner.hasNextLine())
{
String readLine = myScanner.nextLine();
String readData[] = readLine.split(" ");
String index = readData[0];
String name = readData[1];
}
myScanner.close();
If it's always just going to be id space name with nothing coming after it, then you can do this:
String readLine = myScanner.nextLine();
int split = readLine.indexOf(" ");
String index = readLine.substring(0, split);
String name = readLine.substring(split + 1);
This will only work if those are the only two fields though. If you add more fields after that there's no (general) way to determine where item two ends and item three begins.
Another way is to use next, nextInt, etc, to read out exactly what you want:
String index = myScanner.next(); //Or int index = myScanner.nextInt();
String name = myScanner.nextLine().substring(1); //drop the leading space
That's a bit more flexible of an approach, which might be better suited to your needs.
Use following code.
while(myScanner.hasNextLine())
{
String readLine = myScanner.nextLine();
if(null != readLine && readLine.length()>0) {
String index = readLine.substring(0, id.indexOf(" "));
String name = readLine.substring(id.indexOf(" ") + 1);
}
}
myScanner.close();
Lets say I have a string whose format is "name_surname". I mean there are 2 dynamic parts, and between them an underscore. I want to separate them and have in a variable the left part (name) and in another the right (surname).
Basically i want the reverse of this: String temp=name+"_"+surname;
Use split();
String[] parts = temp.split("_");
String name = parts[0];
String surname = parts[1]; // <-- comment
Commented line will throw an ArrayIndexOutOfBoundsException if your name does not contain the underscore.
You should use split.
String fullName = "name_surname";
String[] components = fullName.split("_");
String firstName = components[0];
String lastName = components[1];
Just use StringTokenizer
StringTokenizer st = new StringTokenizer(str, "_");
while (st.hasMoreElements()) {
System.out.println(st.nextElement());
}