Coordinating reading lines from a file and using obtained data - java

Here is my code for reading lines from a CSV file :
private void input()throws IOException
{
//FILE READER FIELDS
StringTokenizer st=null;
BufferedReader b=new BufferedReader(new FileReader(csvfile));
String line=null;
int count=0;
while((line=b.readLine())!=null)
{
count+=1;
if(count==1)
{
continue;
}
else
{
String[] arr=new String[19];
st=new StringTokenizer(line,",");
int i=0;
while(st.hasMoreTokens())
{
arr[i]=st.nextToken();
i++;
}
for(int j=2;j<arr.length;j++)
{
if(j==11)
{
calib_g=Double.parseDouble(arr[j]);
}
if(j==12)
{
coolant_temp=Double.parseDouble(arr[j]);
}
if(j==13)
{
engineRPM=Double.parseDouble(arr[j]);
}
}
}
}
}
As can be inferred from the code, the objective of the above input method is to read the file starting from the second line store the tokens obtained from the perused line in an array whose length is predetermined. Then, select elements from the array are used to update the static variables calib_g ,engineRPM and coolant_temp.
These variables are then used by the below method which updates COSM(previously pachube now xively) with these values :
private void update(int feedid) throws PachubeException, IOException
{
Feed f = this.pachube.getFeed(feedid);
System.out.println("XML is :" + f.toXML());
input();
flag=false;
System.out.println("updating ...");
f.updateDatastream(8345, calib_g);
f.updateDatastream(6274, coolant_temp);
f.updateDatastream(1044, engineRPM);
System.out.println("updated");
}
Problem :
When the input method is called from within the update method, while((line=b.readLine())!=null) iterates over the entire loop and returns the values only from the last line.
Objective :
I want to upload data from a single line when the upload method calls the input method.Thus the flow of the program should be like this
update method is called every 5 seconds using a Timer in the main method.
The update method calls the input method.
The compiler executes the while loop.While loop reads one line from
the csv file.The line is tokenized and stored in the array.Selected
elements of the array are used to update the static variables.
The update method updates XIVELY with the aforementioned static
variables.
Go to step 1 .The update method is called again.
The input method is subsequently called again . This time the next
line of the csv file is used to update the static variables

Related

Duplicate Book Titles using Exceptions

I was given a file that I have to find the duplicates and put them into a new text file. That is the gist of what I am trying to accomplish. Here are the directions I was given:
Your client owns a bookstore, and you will find attached; a text file called Samsbooks.txt with
titles of all the books in the store. Write and Print all the duplicate titles to a file called
SamsDuplicate.txt.
EXAMPLE OUTPUT:
Duplicate Books
Sam’s Bookstore 2021
Jack and Jill
Peter Pan
My Little Pony
Here is my code:
enter code here
//In this program, I will write and print all the duplicate book titles to a new file called
SamsDuplicate.txt.
import java.io.*;
public class bookstore {
public static void main(String[] args) throws IOException {
//Printwriter object for the output file that is called SamsDuplicate.txt.
PrintWriter duplicates = new PrintWriter("SamsDuplicate.txt");
//Bufferreader object for the input file that is called SamsBookstore.txt.
BufferedReader original = new BufferedReader(new
FileReader("C:\\Users\\patti\\Desktop\\Patricks dcom101class\\CSIT
210\\SamsBookstore.txt.docx"));
String begin = original.readLine();
//This while loop will read each line of the SamsBookstore.txt file.
while(begin != null) {
boolean in_stock = false;
//This Bufferreader object is for the output file SamsDuplicate.txt.
BufferedReader output = new BufferedReader(new FileReader("SamsDuplicate.txt"));
String mid = output.readLine();
//This while loop will read each line of the SamsDuplicate.txt file.
while(mid != null) {
if(begin.equals(mid)) {
in_stock = true;
break;
}
mid = output.readLine();
}
//This if statement is if the boolean is false and will also write line from SamsBookstore
file to SamsDuplicate file.
if(!in_stock) {
duplicates.println(begin);
}
begin = original.readLine();
}
//Closing both files.
original.close();
duplicates.close();
System.out.println("Duplicate Books");
System.out.println("Sam's Bookstore 2021");
System.out.println();
System.out.println();
}
}
I cannot use HashMaps or anything of that nature since I have not learned about it yet. I have tried putting in the last System.out.println line: my printerwriter (duplicates), my bufferreader(output), even the name of the new file I created called SamsDuplicate.txt none of them will display the duplicates. Am I missing something here? Any help would be appreciated thanks!
Can you use Set?
Based on your code, it seems that the Samsbooks.txt has a book name per line, right?
Set has a method add, declared boolean add(E e). It returns true if the element was added and false if it was not because it already exists in the collection.
If you cannot use Set, you can implement similar functionality by storing each book name in an array. You'll need to first check if the current book name is already in the array. If it is not, then resize the array +1 and add the new book name to the end.

How do I access an array within an array?

Say I have a .txt file that has information being split by a comma as such:
IN,Indiana,6634007
While this is a snippet which accesses that file and splits it:
for(int i=0; i < count; i++) {
line = bufferedReader2.readLine();
String space[] = line.split(",");
String abb = space[0];
String nme = space[1];
int pop = Integer.parseInt(space[2]);
states[i] = new State(abb, nme, pop);
}
The purpose of that was so that all the information in the txt file could be accessed, so for example this code would print exactly whats present on the .txt file:
System.out.println(states[0]);
would print:
IN,Indiana,6634007
My question is, how would I have it so that I can access the specific part of the array as in how would I print lets say just the name "Indiana" or the population "6634007"?
P.S I'm sorry if the title of my question did not make sense, I did not exactly know how to word it.
Somewhere, you have a class called State. states is an Array of this class. So you can add a getter to State:
public int getPop() {
return pop;
}
And call it on your Object like this:
System.out.println(states[0].getPop());
as states[0] is simply a State object.
Add more getters to access different fields.
if you just want to print every single line, you can try this like below:
public static void main(String[] args) throws Exception {
BufferedReader reader = new BufferedReader(new FileReader("data.txt"));
String line = null;
List<String> list = new ArrayList<String>();
while((line = reader.readLine()) != null ) {
list.add(line);
}
System.out.println(list.get(0));
// TODO realease resources
}
From your question what i can realise is, you are using State class to store the information. In such case, check the state class where the first parameter value is stored. Later to print the corresponding information, access its object variable as SapuSeven mentioned.
For eg.
public class State{
public String a;
public String b;
public int c;
public State(String x, String y, int z){
a=x;
b=y;
c=z;
}
}
now u can access like
System.out.println(states[0].b);
for printing the name of city
OR
you can simply print the value using index like this
System.out.println(states[0].split(",")[2]);

How can I parse lines of data from file to populate objects for each?

I have a text file with the list inside, every line has data that I need insert in the new objects. So data looks like somename=3000 or another type with the slash data another type = 6000.
I have particular class "Item" that has String and int variable. Data need to be inserted into them. Every new object has to be added to the ArrayList<Item>.
// Calculate the lines for next for each loop
int lineCount = 0;
while (sc.hasNextLine()) {
lineCount++;
sc.nextLine();
}
for (int i = 0; i < lineCount; i++) {
// creating the object
Item item = new Item();
// add item object to items ArrayList
items.add(item);
// add line to String variable lineToString,
while (scaner.hasNextLine()) {
String lineToString = scaner.nextLine();
sc.nextLine();
}
So, I figured out that to do this, I need to
copy the whole line and put into some string variable;
split it for integer and string variable;
insert string parts to the String variable and numbers to the int variable in particular object that was created in iteration time of "for loop".
add the object with a data inside to the ArrayList.
I used Scanner to read a text file. When I try to insert the scaner.nextLine to the String it's doesn't work; I mean it's executing but variable String lineToString doesn't have the line from a text file.
Could somebody help with an idea of how better to proceed with this problem? Maybe there is some simpler way to insert the 2 different type of data from the text file line in the object and put it into the ArrayList? Every line in the text file has different data and has to be in different objects.
You didn't mention clearly the line format from the text file. I assume so far you have text file in which each line is like
someone=140000
And you are trying to read those lines of the text and parse each of them to an object of Item which contains a String property (I assume you name it name) and an int property (I assume you name it number)
If this is it, you fisrt need to read your text file line by line and process it further. There are several ways to read a text file line by line.
BufferReader
This is a very common and so far most appropriate way to read a text file in consider of performance.
List<Item> particulatItems = new ArrayList<>();
// using try-with-resource that will help closing BufferedReader by own
try (BufferedReader br = new BufferedReader(new FileReader(file))) {
String line;
while ((line = br.readLine()) != null) {
particularItems.add(processLine(line));
}
}
Scanner
You could use Scanner too.
try (Scanner scanner = new Scanner(new File(fileName))) {
while (scanner.hasNext()) {
particularItems.add(processLine(line));
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
You should extract the line processing logic to a independent function. This is good practice of clean coding.
public static Item processLine(Strinng line) {
String[] tokens = line.split("=");
Item item = new Item(tokens[0], tokens[1]);
}
Assuming you have that particular object defined as Item and you are populating a List of this type
public class Item {
String name;
int number;
public Item(String name, String numtxt) {
this.name = name;
this.number = Integer.parseInt(numtxt);
}
// setter getter
}
More reading:
How to read a large text file line by line using Java?
Different ways of Reading a text file in Java
Difference between Scanner vs BufferReader
Try-with-resources in Java 7
Looks like you have already scanned full file in below code snippet:
while (sc.hasNextLine()) {
lineCount++;
sc.nextLine();
}
After this, you are again iterating in for-loop but with same scanner, which has read last line
So the following may return false:
while (scaner.hasNextLine())
I it may never enter while loop
You should reset scanner before iterating lines again .. or may be use something else than scanner to count lines
Apart from what #Ashish Mishra mentioned, you are doing the second while loop in a for loop, why? Isn't one loop sufficient?
int lineCount = 0;
while (sc.hasNextLine()) {
lineCount++;
String lineToString = sc.nextLine();
Item item = new Item();
//convert lineToString to item
items.add(item);
}

Reading from Array and using Recursive method to check for Palindromes

I've been tasked with creating an array by reading from a text file created by myself. The program in concept, is supposed to read the words i entered, and store them in an array. Following, I am to create a recursive method to check and see if each line is a palindrome and print the result. Currently, I'm getting a stack overflow error. Sorry if the code is not commented on too much.
package palindrome;
import java.util.*;
import java.io.*;
/**
*
* #author alexanderrivera
*/
public class Palindrome {
// Static variables can be used in ALL instances of a class
public static String [] Palindromes;
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws Exception {
// Establishes a value to Palindromes
Palindromes = new String[10];
int i=0;
// calls the readFile method to read the file
readFile("Palindrome.txt");
FindPalindrome(Palindromes[i]);
}// end of main method
// begining of the readFile method
public static void readFile(String fileName)
{
// sets the int variable to zero
int i = 0;
// establishes the java input for reading the file
java.io.File inputFile = new java.io.File(fileName);
// being try catch block
try{
// establishes instance of the scanner to read the file
Scanner fileReader = new Scanner(inputFile);
// being while statement
while(fileReader.hasNextLine())
{
Palindromes[i] = fileReader.nextLine();
i++;
}// end while statement
// closes the file reader
fileReader.close();
// print the index to see if it was read
}catch (FileNotFoundException e){
System.out.println("Sorry, cannot find the file");
}// end error message
} // end the method
public static void FindPalindrome(String FoundPalindrome) {
int i=0;
{
if (Palindromes[i].length() == 0 || Palindromes[i].length() == 1) {
System.out.println(Palindromes[i] + " This is a Palindrome\n");
}
if (Palindromes[i].charAt(0) == Palindromes[i].charAt(Palindromes[i].length() - 1)) {
FindPalindrome(Palindromes[i].substring(1, Palindromes[i].length() - 1));
}
// otherwise
System.out.println("This is not a Palindrome \n");
}
}
}
In recursive calls to your FindPalindrome method, you're passing strings which you never use, since the FindPalindrome method looks at the first entry in the original array of strings and ignores its parameter. So it just repeatedly calls itself with the same argument until it overflows the stack.
Everywhere in FindPalindrome that you reference Palindromes[i], you should likely be referencing instead the parameter FoundPalindrome, and then it might actually work.

printing arrays

Okay, I'm trying to get file scanner to return the array itemList.
However, I don't understand why everytime I get to return itemList and try with a println form.
It returns:
[Ljava.lang.String;#3d3b5a3a
[Ljava.lang.String;#10cb42cf
[Ljava.lang.String;#482d59a3
[Ljava.lang.String;#18f42160
When the file I'm reading it contains stuff like
apples 10
fish 20
import java.io.*;
import java.util.*;
class loadInventory{ /*This class is used for loading the inventory */
private String[] itemList; /*The lines of the inventory are stored in this array */
private int numItems; /* The number of items is stored in this variable */
public loadInventory(String fileName){ /*We can do everything in the constructor. It gets the fileName from the superMarket
object */
itemList = new String[100]; /*We assume there are not more than 100 items in the inventory */
numItems=0; /*initialize numItems to 0*/
/*Read the file using the try-catch block below. We are not specifically catching any exception.
We will not cover reading or writing of files and exceptions in this unit. So you
don't need to understand this piece of code. */
try{
BufferedReader reader = new BufferedReader(new FileReader(fileName)); /*standard code for reading a file */
String line = reader.readLine(); /*read the next line from the file and store in line */
while (line != null){ /*as long as there are lines */
itemList[numItems]= line; /*store the line in the current location of the array */
numItems++; /*increment the number of items */
line = reader.readLine(); /*read the next line */
}
reader.close(); /*close the reader */
} catch (IOException e){ /*we don't catch any exception */
}
System.out.println(itemList);
}
public String[] getItemList() {
return itemList;
}
}
Print the array of instances like this:
System.out.println(Arrays.toString(itemList));
An array itself uses the default toString() from Object, so it does not print its contents. You will need to use java.util.Arrays.toString(Object[]) to print out the content of the array (or loop over it yourself).
int length = itemList.length;
int count =0;
while(count<length)
{
System.out.println(itemList[count]);
count++;
}
thats a simplest way to iterate the list.
Because you are trying to print the whole array object while doing:
System.out.println(itemList);
Instead you need to print the single String elements stored inside the array:
System.out.println(Arrays.toString(itemList));
Don't print the String[] value directly. use like this,
for (int i = 0; i < itemList.length; i++) {
System.out.println("Value::> " +itemList[i]);
}
Pay attention on this code
while (line != null)
{
itemList[numItems]= line;
numItems++;
line = (String)reader.readLine();
}
Try this.

Categories