How to tokenize a file and input the data into an array? - java

I have a file of information separated by commas of which I need to tokenize and place into arrays.
The file has info such as
14299,Lott,Lida,22 Dishonest Dr,Lowtown,2605
14300,Ryder,Joy,19 Happy Pl,Happyville,2701
and so forth. I need to tekonize those pieces of information of which is separated by a comma. I'm not sure how to write out the tokenizer code to make it separate. I've managed to count the amount of lines in the document with;
File customerFile = new File("Customers.txt");
Scanner customerInput = new Scanner(customerFile);
//Checks if the file exists, if not, the program is closed
if(!customerFile.exists()) {
System.out.println("The Customers file doesn't exist.");
System.exit(0);
}
//Counts the number of lines in the Customers.txt file
while (customerInput.hasNextLine()) {
count++;
customerInput.nextLine();
}
And I also have the class of which I'll be placing the tokenized info into;
public class Customer {
private int customerID;
private String surname;
private String firstname;
private String address;
private String suburb;
private int postcode;
public void CustomerInfo(int cID, String lname, String fname, String add, String sub, int PC) {
customerID = cID;
surname = lname;
firstname = fname;
address = add;
suburb = sub;
postcode = PC;
}
But after this point I'm not sure how to place the info into the arrays of the customer. I've tried this but it's not right;
for(i = 0; i < count; i++) {
Customer cus[i] = new Customer;
}
It's telling me the 'i' and the new Customer are errors as it 'can't convert Customer to Customer[]' and 'i' has an error in the token.

first, you need to declare the Customer Array:
Customer[] cus = new Customer[count];
Now, the programm knows, how much space it has to allocate on the memory.
Then, you can use your loop, but you have to call the constructor of the class Customer and give him all the information it needs to create a new one :
for(i = 0; i < count; i++) {
Customer cus[i] = new Customer(cID, lname, fname, add, sub, PC);
}
Another thing you would be asking yourself about is, how do i get the data from the Strings/lines into the array.
for that, you should write all lines in an ArrayList. Like this.
ArrayList<String> strList = new ArrayList<String>();
while (customerInput.hasNextLine()) {
count++;
strList.add(customerInput.nextLine());
}
Now you got all lines as Strings in an ArrayList. But you want to give the single values of each String to your constructor.
take a look at the split method from Strings. (How to split a string in Java).
With split() you can split one line like this:
String[] strArray = "word1,word2,word3".split(",");
then in the strArray you can find your data:
strArray[0] would have the value "word1";
strArray[1] = "word2";
and so on

If it is a CSV file instead of a simple comma separated flie, maybe consider some library like:
Commons CSV
OpenCSV

Related

Shuffling groups of elements in an arraylist

I am working on a group generator and currently I am making an ArrayList from this txt file.
So that, the ArrayList is in the form of [PedroA, Brazil, Male, 10G, Saadia...]
I want to shuffle 4 elements at a time, to randomize this arraylist.
I am storing the info in
ArrayList<String> studentInfo = info.readEachWord(className);
This is very hard to do. It's possible, of course, but difficult.
It is being made difficult because what you want to do is bizarre.
The normal way to do this would be to:
Make a class representing a single entry, let's call it class Person.
Read this data by parsing each line into a single Person instance, and add them all to a list.
Just call Collections.shuffle(list); to shuffle them.
If we have the above, we could do what you want, by then converting your List<Person> back into a List<String>. In many ways this is the simplest way to do the task you ask for, but then you start wondering why you want this data in the form of a list of strings in the first place.
enum Gender {
MALE, FEMALE, OTHER;
public static Gender parse(String in) {
switch (in.toLowerCase()) {
case "male": return MALE;
case "female": return FEMALE;
default: return OTHER;
}
}
class Person {
String name;
String location;
Gender gender;
[some type that properly represents whatever 10G and 10W means];
public static Person readLine(String line) {
String[] parts = line.split("\\s+", 4);
Person p = new Person();
p.name = parts[0];
p.location = parts[1];
p.gender = Gender.parse(parts[2]);
...;
return p;
}
}
you get the idea.

How come my array is null when writing data to it?

I am trying to figure out why my program says my array is null and cannot be written to. I created an Element class to determine what elements would be in the array, so the array is type Element[]. The array takes in data from a file and then is supposed to add it to the array. The program seems to read the data from the file but it will not add it to the array.
class Array extends Element
{
//Global Variables
public static Element[] array;
//Max number of entries
private int numMax;
public int numElements;
//Constructors
public Array()
{
}
public Array(int numMax)
{
//Instantiate the array
array = new Element[numMax];
numElements = 0;
}
This is a function to insert the data into the array:
public void insertValue(String firstName, String lastName,
String company, String address, String city, String state,
String county, String phone, int zip, long key, int rowNum)
{
try
{
//Add elements to array
System.out.println(numElements);
array[numElements].setFirstName(firstName);
array[numElements].setLastName(lastName);
array[numElements].setCompany(company);
array[numElements].setAddress(address);
array[numElements].setCity(city);
array[numElements].setState(state);
array[numElements].setCounty(county);
array[numElements].setPhone(phone);
array[numElements].setZip(zip);
array[numElements].setKey(key);
array[numElements].setRowNum(rowNum);
//Increment number of elements in the array
numElements++;
} catch (Exception e)
{
System.out.println(e.getMessage());
}
}
This is my input function:
public static void readInputFile()
{
//Create a new instance of the array class so that the array can be
//written to without creating a new array for either merge or insert
//sort
Array arr = new Array(1000010);
Element[] array = arr.getArray();
try
{
fileRead = new FileReader(fileLocation);
br = new BufferedReader(new FileReader(fileLocation));
//Allows the first line of the file that includes the titles to
//not be added to the array
String line = br.readLine();
//Counter for iterating through array
int elemCntr = 0;
while (elemCntr != 10)
{
//Variables
String lineline = br.readLine();
//This will split the line into sections based on the
//placement of comas: split data into sections
String[] readLine = lineline.split(",");
firstName = readLine[0];
lastName = readLine[1];
company = readLine[2];
address = readLine[3];
city = readLine[4];
county = readLine[5];
state = readLine[6];
zip = Integer.parseInt(readLine[7]);
phone = readLine[8];
key = Long.parseLong(readLine[9]);
rowNum = arr.numElements + 1;
//Insert data into array
arr.insertValue(firstName, lastName, company, address, city,
state, county, phone, zip, key, rowNum);
}
} catch (Exception e){
// do something
}
}
Can you identify any problems, please?
Try with using ArrayList
You are trying to make dynamic array of class Element which is possible.But it is bad practice as u have to write initialization statement for every element.Initialization are meant to be done in constructors.
Declaration: Element element[] = new Element[5];
Initialization: element[0] = new Element();
;
It is possible to make dynamic arrays of int , string etc easily then of Class.
PS: Try giving different names you are having Arrays as class and arrays as variable also.
your code is n't clear, but if you call readInputFile method first, it will instantiate array and then when you call insertValue method it should work properly, because array is static.

Parsing file and sort lines by property

So basically someone gave me a text file for me to read through Java and I have to print out certain parts of it.
So what I did was I put all of the text file into a String and between every word there's a ":". So i split all of the text with ":" using split function. At first every line looks like this
firstName:Surname:Age:Country
firstName:Surname:Age:Country
firstName:Surname:Age:Country
firstName:Surname:Age:Country
firstName:Surname:Age:Country
firstName:Surname:Age:Country
firstName:Surname:Age:Country
firstName:Surname:Age:Country
After it would be the same thing without the colons.
So now if I say all[0], I would get all the firstNames only.
What I'm trying to get is get the top 3 highest ages but I do not know how to do that.
Explanation
Suppose you have a file with lines like
John:Doe:20:USA
Jane:Doe:35:Germany
Robert:Moe:14:Japan
Larry:Loe:25:China
Richard:Roe:27:India
and you want the 3 lines with the highest age, that would be
Jane:Doe:35:Germany
Richard:Roe:27:India
Larry:Loe:25:China
The procedure is straightforward. First read all lines, split by : and parse the data into a wrapper class like Person. Collect them into some collection like List<Person> and sort them using a Comparator that compares the age. Alternatively you could let Person implement Comparable and then use their natural order.
If efficiency matters you can also do partial sort since you are only interested in the top 3 hits. For this you could use a PriorityQueue, insert all elements and call poll three times.
Solution
First the Person wrapper class
public class Person {
private String mFirstName;
private String mSurname;
private int mAge;
private String mCountry;
public Person(String firstName, String surname, int age, String country) {
this.mFirstName = firstName;
this.mSurname = surname;
this.mAge = age;
this.mCountry = country;
}
// TODO Some getters
public String toString() {
return this.mFirstName + ":" + this.mSurname
+ ":" + this.mAge + ":" + this.mCountry;
}
public static Person parse(String[] data) {
String firstName = data[0];
String surname = data[1];
int age = Integer.parseInt(data[2]);
String country = data[3];
return new Person(firstName, surname, age, country);
}
}
Next we read all lines, split the data and parse them into Person. After that we sort and limit the result to 3. Finally we collect to a List and print the results.
Path file = Paths.get(...);
Pattern separator = Pattern.compile(":");
List<Person> persons = Files.lines(file) // Stream<String>
.map(separator::splitAsStream) // Stream<String[]>
.map(Person::parse) // Stream<Person>
.sorted(Comparator.comparingInt(Person::getAge).reversed())
.limit(3)
.collect(Collectors.toList());
persons.forEach(System.out::println);
Or if you want to use the PriorityQueue as suggested, which will improve runtime:
Path file = Paths.get(...);
Pattern separator = Pattern.compile(":");
PriorityQueue<Person> personQueue = Files.lines(file)
.map(separator::splitAsStream)
.map(Person::parse)
.collect(Collectors.toCollection(() -> {
return new PriorityQueue<>(
Comparator.comparingInt(Person::getAge).reversed());
}));
List<Person> persons = new ArrayList<>(3);
persons.add(personQueue.poll());
persons.add(personQueue.poll());
persons.add(personQueue.poll());
persons.forEach(System.out::println);

Reading a File with Different Data Types Into Tree

I have an object Movie which contains these data members: title(string), year(int), and list of actors(ArrayList). I want to read from the file and create a new Movie object with the information from the file. This is an example text from the file:
Star Wars/1977/Mark Hamill,Carrie Fisher,Harrison Ford
How would I add the file to the tree to meet the conditions of my Constructor:
public class Movie {
private String title;
private int year;
private ArrayList<String> actors;
public Movie( String t, int y, ArrayList<String> a ){
title = t;
year = y;
actors = a;
}
How I am trying to add File (I know it would work if everything was of type String):
try{
Scanner read = new Scanner( new File("movies.txt") );
do{
String line = read.nextLine();
String [] tokens = line.split("/");
//How would I change this to allow for differnt data types.
tree.add( new Movie(tokens[0], tokens[1], tokens[2] );
}while( read.hasNext() );
read.close();
}catch( FileNotFoundException fnf){
System.out.println("File not found.");
}
I am thinking I would need to create my ArrayList here as well as an int.
Convert the type.
1) convert the tokens[1] into integer by using Integer.parseIt(tokens[1]);
2) for array list again spilt the tokens[2] by "," and add it to an arraylist. Use arraylist.add() for adding the values in the arraylist.
3) call the constructor using string int and arraylist variables.
Your Question is not clear, but any way you can add this if I correctly understand you
tree.add( new Movie(tokens[0], Integer. Integer.parseInt(tokens[1]),Arrays.asList(tokens[2].split(",") );

How to organize array with different types?

Hi,
I am new in Java and trying to figure out how to push this data into array(6 rows, 3 columns)?
x1 John 6
x2 Smith 9
x3 Alex 7
y1 Peter 8
y2 Frank 9
y3 Andy 4
Afterwards, I will take numbers from last column for making mathematical calculations.
This is my code...
public class Testing {
public static void main(String[] args) {
Employee eh = new Employee_hour();
Employee_hour [] eh_list = new Employee_hour[6];
eh_list[0] = new Employee_hour("x1", "John", 6);
eh_list[1] = new Employee_hour("x2", "Smith", 9);
eh_list[2] = new Employee_hour("x3", "Alex", 7);
eh_list[3] = new Employee_hour("y1", "Peter", 8);
eh_list[4] = new Employee_hour("y2", "Frank", 9);
eh_list[5] = new Employee_hour("y3", "Andy", 4);
print(eh_list);
}
private static void print(Employee_hour[] mass){
for (int i = 0; i < mass.length; i++) {
System.out.print(mass[i] + " ");
}
System.out.println();
}
}
But I'm getting this as the output...
testing.Employee_hour#1a752144 testing.Employee_hour#7fdb04ed
testing.Employee_hour#420a52f testing.Employee_hour#7b3cb2c6
testing.Employee_hour#4dfd245f testing.Employee_hour#265f00f9
How can I get numbers from last column?
Why not create a specific Java bean for your records?
class Person {
String id;
String name;
int anotherNumber;
// constructor, getters, setters
}
And then use it like this:
Person [] people = new Person[10];
people[0] = new Person("x1", "John", 6);
...
Or better yet employ java.util.List instead of the array.
Field Access
In order to access separate fields, you either need to make your fields public (very bad idea) and simply refer to them as object_instance.field_name, or provide so-called getters:
class Person {
String id;
String name;
int anotherNumber;
// constructor, getters, setters
public int getAnotherNumber() {
return anotherNumber;
}
}
Then call it when printing:
for (int i = 0; i < mass.length; i++) {
System.out.print(mass[i].getAnotherNumber() + " ");
}
Why what you tried didn't work:
System.out.println(mass[0]) in your case will print the whole object representation, by default it prints what it did in your case. To do it nicer you need to override Object's String toString() method:
class Person {
String id;
String name;
int anotherNumber;
// constructor, getters, setters
public String toString() {
return "{id="+id+", name="+name+", anotherNumber="+anotherNumber+"}";
}
}
Java is strongly typed, so you can't just make an array that will accept any type.
However, you could make a multidimensional array of type Object, and use java.lang.Integer for the integer values.
The alternative is to make a class that represents the rows in your table, and make an array of that class.
If you want to store it as array user 2 dimentional array.Here is a sample.
String[][] a2 = new String[10][5];
for (int i=0; i<a2.length; i++) {
for (int j=0; j<a2[i].length; j++) {
a2[i][j] = i;
System.out.print(" " + a2[i][j]);
}
System.out.println("");
}
}
The better approach would be to cretae an Object
class User {
String id;
String userName;
int userSomeValue;
//
}
Then push it to a list
User ob1=new User();
// set the values.
List<User> userList=new ArrayList<User>();
userList.add(ob1);
Use this list for procesing by retriving the contents using
userList.get(index);
Array is a type-safe collection you can use array of generic objects. Other way use collection Api.
There are some ways to store your data in an array but you can only store values of the same type in one Array. For Example just String, int or float. In your case you have to use String but you can't do any calculations with a string type variable even if it contains a number. I would suggest the way maksimov describes.

Categories

Resources