Copy one element of string array into another java - java

Hi I'm essentially trying to copy an element of one array into another array. I have the array lineOfData which holds data from a csv file (id, size, custom label) and I want a new array ids that just holds the ids. I have tried ids = lineOfData[0]; but to no avail. what is the best way to do this?
Code:
public class Merge {
String filePath;
public Merge() {
}
public static void main(String[] args) throws FileNotFoundException {
Frame myFrame = new Frame();
FileDialog fileBox = new FileDialog(myFrame, "Open", FileDialog.LOAD);
fileBox.setVisible(true);
String filename = fileBox.getFile();
String directoryPath = fileBox.getDirectory();
if ( filename !=null )
{
String filePath = directoryPath + filename;
//testFile(filePath);
mergeFile(filePath);
}
}
public static void mergeFile(String... filePaths) throws FileNotFoundException {
String[] lineOfData = null;
String[] ids = null;
for(String filePath : filePaths)
{
String path = filePath;
Scanner scanner = new Scanner(new File(path));
String columnTitle = scanner.nextLine();
while(scanner.hasNextLine())
{
//scanner.useDelimiter(",");
String line = scanner.nextLine();
lineOfData = line.split(",");
ids[0] = lineOfData[0];
System.out.println(Arrays.toString(ids));
}
scanner.close();
}
}

You mentioned that you're getting that "The value ids can only be null at this location". This is because you haven't initialized the ids array. Right now, ids isn't pointing to any array. In order to fix this, you
String line = scanner.nextLine();
lineOfData = line.split(",");
ids = new String[lineOfData.length];
ids[0] = lineOfData[0];
if you're going to be adding all the values of lineOfData to ids, or
String line = scanner.nextLine();
lineOfData = line.split(",");
ids = new String[1];
ids[0] = lineOfData[0];
if you only want to copy one element of lineOfData into ids.
Also, notice that lineOfData also starts out by not pointing to any array. However, the lineOfData = line.split(","); line fixes that, and makes it point to an array of Strings. Ask if you have any questions.

Related

Object needs to created from the file and placed into an array

I am trying to create an object for each line of text and as each object is created, place it into an array. I'm struggling to place it into an array. This is my code:
File inFile = new File("shareholders.txt");
Scanner inputFile = new Scanner(inFile);
String str;
Shareholder shareholder = new Shareholder();
while (inputFile.hasNext()) {
str = inputFile.nextLine();
String tokens[] = str.split(",");
shareholder.setID(tokens[0]);
shareholder.setName(tokens[1]);
shareholder.setAddress(tokens[2]);
shareholder.setPortfolioID(tokens[3]);
}
If you have a fixed number of shareholders, you can do this -
File inFile = new File("shareholders.txt");
Scanner inputFile = new Scanner(inFile);
String str;
int i=0;
Shareholder[] shareholder = new Shareholder[n];
while (inputFile.hasNext()) {
str = inputFile.nextLine();
String tokens[] = str.split(",");
shareholder[i++] = new Shareholder(tokens[0],tokens[1],tokens[2],tokens[3]);
}
Or if dont know the number of shareholders, then you can use list -
File inFile = new File("shareholders.txt");
Scanner inputFile = new Scanner(inFile);
String str;
List<Shareholder> list = new ArrayList<>();
while (inputFile.hasNext()) {
Shareholder shareholder = new Shareholder();
str = inputFile.nextLine();
String tokens[] = str.split(",");
list.add(new Shareholder(tokens[0],tokens[1],tokens[2],tokens[3]));
}
I think a list of shareholder objects might make the most sense here:
File inFile = new File("shareholders.txt");
Scanner inputFile = new Scanner(inFile);
String str;
List<Shareholder> list = new ArrayList<>();
while (inputFile.hasNext()) {
Shareholder shareholder = new Shareholder();
str = inputFile.nextLine();
String tokens[] = str.split(",");
shareholder.setID(tokens[0]);
shareholder.setName(tokens[1]);
shareholder.setAddress(tokens[2]);
shareholder.setPortfolioID(tokens[3]);
list.add(shareholder);
}
The reason a list makes sense here is because you might not know how many shareholders are present in the input file. Hence, an array might not work so well in this case (and even if the number of shareholders were fixed it could change at some later date).
Before reading the file, you can not know how many lines the file has.
The information about the number of lines is important to initialize your array with that specific size or otherwise you would need to extend your array multiple times by creating a new, bigger one. Which is bad practice and bad performance.
But instead of working with an array itself, use an arraylist for easier usage and just return a simple array, which can be received from the arraylist you worked with.
My suggestion as a solution for this issue is the following. Please note that the following code is not 100% complete and will not run in it's state. It is your job to complete it and make it run.
public void readFileIntoArray(String filename, Shareholder[] targetArray)
{
File sourceFile = new File(filename);
// Read in the file to determine the number of lines (int numberOfLines)
ArrayList<Shareholder> lines = new ArrayList<>(numberOfLines);
Shareholder sh;
while(file.hasNext())
{
sh = new Shareholder();
//Parse data into Shareholderobject
lines.add(sh);
}
return lines.toArray();
}

Null when splitting a string

I need to create my own sort method for an array, and I begin my splitting the text file into an array filled with the words. The file format is: an integer n, followed by n words.
Here's an example: 4 hello hello world hello
However, my array prints: [null4, hello, hello, world, hello]
WHY! I don't understand why there is a null before. And, if I remove the number 4 (which plays no role in my program at the moment) I get: [nullhello, hello, world, hello]
Can you please help me remove this null? Thanks in advance!
public static void main(String[] args) throws FileNotFoundException {
filePath = "***TEXT FILE HERE***";
fileInput = new Scanner(new File(filePath));
convertFile(fileInput);
}
public static void convertFile(Scanner file) {
String line;
while (fileInput.hasNextLine()) {
line = fileInput.nextLine();
fileData = fileData + line;
}
String[] array = createArray(fileData);
System.out.println(Arrays.toString(array));
}
public static String[] createArray(String data) {
String[] dataArray = data.split("\\s+");
return dataArray;
}
You did not initialise the fileData variable before using it.
try
fileData = "";
fileData = fileData + line;
this is not the best choise for building a string... try to replace it with a StringBuilder
StringBuilder fileData = new StringBuilder(); // to instantiate
fileData.append(line + "\n"); // to add lines
String finalString = fileData.toString(); // to build the string
for larger strings your method of concatenation will become very slow

Scanning, spliting and assigning values from a text file

I'm having trouble scanning a given file for certain words and assigning them to variables, so far I've chosen to use Scanner over BufferedReader because It's more familiar. I'm given a text file and this particular part I'm trying to read the first two words of each line (potentially unlimited lines) and maybe add them to an array of sorts. This is what I have:
File file = new File("example.txt");
Scanner sc = new Scanner(file);
while (sc.hasNextLine()) {
String line = sc.nextLine();
String[] ary = line.split(",");
I know It' a fair distance off, however I'm new to coding and cannot get past this wall...
An example input would be...
ExampleA ExampleAA, <other items seperated by ",">
ExampleB ExampleBB, <other items spereated by ",">
...
and the proposed output
VariableA = ExampleA ExampleAA
VariableB = ExampleB ExampleBB
...
You can try something like this
File file = new File("D:\\test.txt");
Scanner sc = new Scanner(file);
List<String> list =new ArrayList<>();
int i=0;
while (sc.hasNextLine()) {
list.add(sc.nextLine().split(",",2)[0]);
i++;
}
char point='A';
for(String str:list){
System.out.println("Variable"+point+" = "+str);
point++;
}
My input:
ExampleA ExampleAA, <other items seperated by ",">
ExampleB ExampleBB, <other items spereated by ",">
Out put:
VariableA = ExampleA ExampleAA
VariableB = ExampleB ExampleBB
To rephrase, you are looking to read the first 2 words of a line (everything before the first comma) and store it in a variable to process further.
To do so, your current code looks fine, however, when you grab the line's data, use the substring function in conjunction with indexOf to just get the first part of the String before the comma. After that, you can do whatever processing you want to do with it.
In your current code, ary[0] should give you the first 2 words.
public static void main(String[] args)
{
File file = new File("example.txt");
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
String line = "";
List l = new ArrayList();
while ((line = br.readLine()) != null) {
System.out.println(line);
line = line.trim(); // remove unwanted characters at the end of line
String[] arr = line.split(",");
String[] ary = arr[0].split(" ");
String firstTwoWords[] = new String[2];
firstTwoWords[0] = ary[0];
firstTwoWords[1] = ary[1];
l.add(firstTwoWords);
}
Iterator it = l.iterator();
while (it.hasNext()) {
String firstTwoWords[] = (String[]) it.next();
System.out.println(firstTwoWords[0] + " " + firstTwoWords[1]);
}
}

Compare values in two files

I have two files Which should contain the same values between Substring 0 and 10 though not in order. I have Managed to Outprint the values in each file but I need to Know how to Report say id the Value is in the first File and Notin the second file and vice versa. The files are in these formats.
6436346346....Other details
9348734873....Other details
9349839829....Other details
second file
8484545487....Other details
9348734873....Other details
9349839829....Other details
The first record in the first file does not appear in the second file and the first record in the second file does not appear in the first file. I need to be able to report this mismatch in this format:
Record 6436346346 is in the firstfile and not in the secondfile.
Record 8484545487 is in the secondfile and not in the firstfile.
Here is the code I currently have that gives me the required Output from the two files to compare.
package compare.numbers;
import java.io.*;
/**
*
* #author implvcb
*/
public class CompareNumbers {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
File f = new File("C:/Analysis/");
String line;
String line1;
try {
String firstfile = "C:/Analysis/RL001.TXT";
FileInputStream fs = new FileInputStream(firstfile);
BufferedReader br = new BufferedReader(new InputStreamReader(fs));
while ((line = br.readLine()) != null) {
String account = line.substring(0, 10);
System.out.println(account);
}
String secondfile = "C:/Analysis/RL003.TXT";
FileInputStream fs1 = new FileInputStream(secondfile);
BufferedReader br1 = new BufferedReader(new InputStreamReader(fs1));
while ((line1 = br1.readLine()) != null) {
String account1 = line1.substring(0, 10);
System.out.println(account1);
}
} catch (Exception e) {
e.fillInStackTrace();
}
}
}
Please help on how I can effectively achieve this.
I think I needed to say that am new to java and may not grab the ideas that easily but Am trying.
Here is the sample code to do that:
public static void eliminateCommon(String file1, String file2) throws IOException
{
List<String> lines1 = readLines(file1);
List<String> lines2 = readLines(file2);
Iterator<String> linesItr = lines1.iterator();
while (linesItr.hasNext()) {
String checkLine = linesItr.next();
if (lines2.contains(checkLine)) {
linesItr.remove();
lines2.remove(checkLine);
}
}
//now lines1 will contain string that are not present in lines2
//now lines2 will contain string that are not present in lines1
System.out.println(lines1);
System.out.println(lines2);
}
public static List<String> readLines(String fileName) throws IOException
{
List<String> lines = new ArrayList<String>();
FileInputStream fs = new FileInputStream(fileName);
BufferedReader br = new BufferedReader(new InputStreamReader(fs));
String line = null;
while ((line = br.readLine()) != null) {
String account = line.substring(0, 10);
lines.add(account);
}
return lines;
}
Perhaps you are looking for something like this
Set<String> set1 = new HashSet<>(FileUtils.readLines(new File("C:/Analysis/RL001.TXT")));
Set<String> set2 = new HashSet<>(FileUtils.readLines(new File("C:/Analysis/RL003.TXT")));
Set<String> onlyInSet1 = new HashSet<>(set1);
onlyInSet1.removeAll(set2);
Set<String> onlyInSet2 = new HashSet<>(set2);
onlyInSet2.removeAll(set1);
If you guarantee that the files will always be the same format, and each readLine() function is going to return a different number, why not have an array of strings, rather than a single string. You can then compare the outcome with greater ease.
Ok, first I would save the two sets of strings in to collections
Set<String> s1 = new HashSet<String>(), s2 = new HashSet<String>();
//...
while ((line = br.readLine()) != null) {
//...
s1.add(line);
}
Then you can compare those sets and find elements that do not appear in both sets. You can find some ideas on how to do that here.
If you need to know the line number as well, you could just create a String wrapper:
class Element {
public String str;
public int lineNr;
public boolean equals(Element compElement) {
return compElement.str.equals(str);
}
}
Then you can just use Set<Element> instead.
Open two Scanners, and :
final TreeSet<Integer> ts1 = new TreeSet<Integer>();
final TreeSet<Integer> ts2 = new TreeSet<Integer>();
while (scan1.hasNextLine() && scan2.hasNexLine) {
ts1.add(Integer.valueOf(scan1.nextLigne().subString(0,10));
ts1.add(Integer.valueOf(scan1.nextLigne().subString(0,10));
}
You can now compare ordered results of the two trees
EDIT
Modified with TreeSet
Put values from each file to two separate HashSets accordingly.
Iterate over one of the HashSets and check whether each value exists in the other HashSet. Report if not.
Iterate over other HashSet and do same thing for this.

Basic File Reading to Array Storage

I have a simple Java questions and I need a simple answer, if possible. I need to input the data from the file and store the data into an array. To do this, I will have to have the program open the data file, count the number of elements in the file, close the file, initialize your array, reopen the file and load the data into the array. I am mainly having trouble getting the file data stored as an array. Here's what I have:
The to read file is here: https://www.dropbox.com/s/0ylb3iloj9af7qz/scores.txt
import java.io.*;
import java.util.*;
import javax.swing.*;
import java.text.*;
public class StandardizedScore8
{
//Accounting for a potential exception and exception subclasses
public static void main(String[] args) throws IOException
{
// TODO a LOT
String filename;
int i=0;
Scanner scan = new Scanner(System.in);
System.out.println("\nEnter the file name:");
filename=scan.nextLine();
File file = new File(filename);
//File file = new File ("scores.txt");
Scanner inputFile = new Scanner (file);
String [] fileArray = new String [filename];
//Scanner inFile = new Scanner (new File ("scores.txt"));
//User-input
// System.out.println("Reading from 'scores.txt'");
// System.out.println("\nEnter the file name:");
// filename=scan.nextLine();
//File-naming/retrieving
// File file = new File(filename);
// Scanner inputFile = new Scanner(file);
I recommend you use a Collection. This way, you don't have to know the size of the file beforehand and you'll read it only once, not twice. The Collection will manage its own size.
Yes, you can if you don't care about the trouble of doing things twice. Use while(inputFile.hasNext()) i++;
to count the number of elements and create an array:
String[] scores = new String[i];
If you do care, use a list instead of an array:
List<String> list = new ArrayList<String>();
while(inputFile.hasNext()) list.add(inputFile.next());
You can get list elements like list.get(i), set list element like list.set(i,"string") and get the length of list list.size().
By the way, your line of String [] fileArray = new String [filename];is incorrect. You need to use an int to create an array instead of a String.
/*
* Do it the easy way using a List
*
*/
public static void main(String[] args) throws IOException
{
Scanner scan = new Scanner(System.in);
System.out.println("\nEnter the file name:");
String filename = scan.nextLine();
FileReader fileReader = new FileReader(filename);
BufferedReader reader = new BufferedReader(fileReader);
List<String> lineList = new ArrayList<String>();
String thisLine = reader.readLine();
while (thisLine != null) {
lineList.add(thisLine);
thisLine = reader.readLine();
}
// test it
int i = 0;
for (String testLine : lineList) {
System.out.println("Line " + i + ": " + testLine);
i++;
}
}
We can use the ArrayList collection to store the values from the file to the array without knowing the size of the array before hand.
You can get more info on ArrayList collections from the following urls.
http://docs.oracle.com/javase/tutorial/collections/implementations/index.html
http://www.java-samples.com/showtutorial.php?tutorialid=234

Categories