Compare two strings and store the index in integer array - java

I have :
String1[] having Number,Quantity,Unit of Measure,Find Number parameters
String2[] having Action,Level,Number,Organization ID,Container,Revision,View,Quantity,Unit of Measure,Reference Designators,Trace Code,Find Number,Line Number,Component Reference,Quantity Option,Inclusion Option,Type
this parameters I have compare both the strings split them by commas using for loop. I want string1 found in string2 at which index. I want to store those index in one integer.
Please give any idea.
String[] col=col_name.split(",");
BufferedReader br = new BufferedReader(new FileReader("file.csv"));
String header = br.readLine();
if(header!=null)
{
String[] two = header.split(",");
System.out.println(header);
// String[] columns = header.split(",");
int[] indices = new int[20];
for (int i = 0; i < two.length; i++) {
for (int j = 0; j < col.length; j++) {
if(two[i].equals(col[j])){
System.out.println("("+i+","+j+")");
indices[i]=i;
}
}
Thanks in Advance

You can use the list.indexOf(Object o) method. Example:
String[] col=col_name.split(",");
BufferedReader br = new BufferedReader(new FileReader("file.csv"));
String header = br.readLine();
if(header!=null)
{
String[] two = header.split(",");
System.out.println(header);
int[] indices = new int[col.length];
for(int j = 0; j < col.length; j++){
indices[j]=Arrays.asList(two).indexOf(col[j]);
}
System.out.println(Arrays.toString(indices));
}

Related

How do I find the longest words in a string?

I want to find the longest words in a given String.
The following code checks for the longest word, but I want every other word with the same length as well.
try (BufferedReader fileInputReader = new BufferedReader(new FileReader(filePath))){
String line = fileInputReader.readLine();
line = line.replaceAll("[^äÄöÖüÜßa-zA-Z ]", "");
String[] sentence = line.split(" ");
String longestWord = "";
for (int i = 0; i < sentence.length; i++) {
if (sentence[i].length() > longestWord.length()) {
longestWord = sentence[i];
}
}
System.out.println(longestWord);
}
Then you have to use a collection of these longestWords, e.g.
ArrayList<String> longestWords = new ArrayList<String>();
int longestWordLength = 0;
for (int i = 0; i < sentence.length; i++) {
if (sentence[i].length() > longestWordLength) { // longer
longestWordLength = sentence[i].length();
longestWords.clear();
longestWords.add(sentence[i]);
}
else if (sentence[i].length() == longestWordLength) { // same length
longestWords.add(sentence[i]);
}
}
for (int i = 0; i < longestWords.size(); ++i)
System.out.println(longestWords.get(i));
try(BufferedReader fileInputReader = new BufferedReader(new FileReader(filePath))){
String line = fileInputReader.readLine();
line = line.replaceAll("[^äÄöÖüÜßa-zA-Z ]", "");
String[] sentence = line.split(" ");
ArrayList<String> longestWord = new ArrayList<>();
int maxLength = 1;
for(int i = 0; i < sentence.length; i++){
if(sentence[i].length() > maxLength){
longestword.clear();
longestWord.add(sentence[i]);
maxLength=sentece[i].length();
}
else if(sentence[i].length() == maxLength)
{
longestWord.add(sentence[i]);
}
}
System.out.println(longestWord);
}

Searching in arraylist<String[]> from user input

I want to search in an arraylist from a user input but my if condition doesn't seem to work. Using boolean and .contains() doesn't work for my programme either. This is the coding:
String phone;
phone=this.text1.getText();
System.out.println("this is the phone: " + phone);
BufferedReader line = new BufferedReader(new FileReader(new File("C:\\Users\\Laura Sutardja\\Documents\\IB DP\\Computer Science HL\\cs\\data.txt")));
String indata;
ArrayList<String[]> dataArr = new ArrayList<String[]>();
while ((indata = line.readLine()) != null) {
String[] club = new String[2];
String[] value = indata.split(",", 2);
//for (int i = 0; i < 2; i++) {
int n = Math.min(value.length, club.length);
for (int i = 0; i < n; i++) {
club[i] = value[i];
}
boolean aa = dataArr.contains(this.text1.getText());
if(aa==true)
text2.setText("The data is found.");
else
text2.setText("The data is not found.");
dataArr.add(club);
}
for (int i = 0; i < dataArr.size(); i++) {
for (int x = 0; x < dataArr.get(i).length; x++) {
System.out.printf("dataArr[%d][%d]: ", i, x);
System.out.println(dataArr.get(i)[x]);
}
}
}
catch ( IOException iox )
{
System.out.println("Error");
}
Your dataArr is a list of String[], and you are searching for a String. The two are different kind of objects.
I don't really know how the content of the club array looks like, but you should either change dataArr in order to hold plain String, or to write a method which looks iteratively in dataArr for a String[] containing the output of this.text1.getText().
There is a lot wrong with the program. I assume you want to read a textfile and store each line in the arraylist. To do this you have to split each line of the textfile and store that array in the arrayList.
String[] value;
while ((indata = line.readLine()) != null) {
value = indata.split(",");
dataArr.add(value);
}
Now you have the contents of the file in the arrayList.
Next you want to compare the userinput with each element of the arraylist.
int j = 0;
for (int i = 0; i < dataArr.size(); i++) {
String[] phoneData = dataArr.get(i);
if (phoneData[1].equals(phone)) { // i am assuming here that the phone number is the 2nd element of the String[] array, since i dont know how the textfile looks.
System.out.println("Found number.");
club[j++] = phoneData[1];
} else if (i == dataArr.size()-1) {
System.out.println("Didn't find number.");
}
}
Edit:
As requested:
String phone;
phone = "38495";
System.out.println("this is the phone: " + phone);
BufferedReader line = new BufferedReader(new FileReader(new File("list.txt")));
String indata;
ArrayList<String[]> dataArr = new ArrayList<>();
String[] club = new String[2];
String[] value;// = indata.split(",", 2);
while ((indata = line.readLine()) != null) {
value = indata.split(",");
dataArr.add(value);
}
int j = 0;
for (int i = 0; i < dataArr.size(); i++) {
String[] phoneData = dataArr.get(i);
if (phoneData[1].equals(phone)) {
System.out.println("Found number.");
club[j++] = phoneData[1];
break;
} else if (i == dataArr.size()-1) {
System.out.println("Didn't find number.");
}
}
I hope this makes sense now.

Printing ListArrays to a txt file

I have a method that is suppose to take 3 arrays and save them to a txt file. But it doesnt print to the list. Here is my code for the method
public static void saveAndExit(int count, String[] makeArray, String[] moduleArray, double [] msrpArray) throws IOException{
File carList = new File("cars_list.txt");
PrintWriter pw = new PrintWriter(carList);
int index = 0;
String[] finalMSRPArray = new String[12];
for (int i = 0; i < msrpArray.length; i++){
finalMSRPArray[i] = String.valueOf(msrpArray[i]);
}
while(count < makeArray.length && count < moduleArray.length && count < msrpArray.length){
pw.write(makeArray[index]+"\n");
pw.write(moduleArray[index]+"\n");
pw.write(finalMSRPArray[index]+"\n");
index++;
}
pw.close();
}
Any help is much appreciated!

How to write only the 5th value from a list into a csv

I am reading several csv sheet with the opencsv libary. I am storing the "read" csv file in hugeList = reader.readAll(); Now I only want to only write the 5th value of this huge csv sheet columnwise in another sheet.
At the moment I am standing at:
//reading all entries in a huge list
//-740 as it would take to much time to run it in "dev mode"
for (int j = 0; j < (fileList.size() - 740); j++) {
String csvFile = "C:\\Users\\" + fileList.get(j);
reader = new CSVReader(new FileReader(csvFile), ';');
hugeList = reader.readAll();
List<String[]> data = new ArrayList<String[]>();
// for(int m = 0; m < hugeList.size(); m++) {
// String[] value = hugeList.get(m);
data.add(hugeList.get(5));
// }
writer.writeAll(data);
}
However I have no idea how to write them into another column and just take the 5th value?
I really appreciate your answer!
UPDATE 1
Goal: I have saved all values from one sheet at the time in hugeList. Now I want to
write only the 5th column into a new sheet.
Problem: The logic behind this goal.
UPDATE 2
This is what my code looks like right now:
//reading all entries in a huge list
for (int j = 0; j < (fileList.size() - 740); j++) {
String csvFile = "C:\\" + fileList.get(j);
reader = new CSVReader(new FileReader(csvFile), ';');
hugeList = reader.readAll();
List<String[]> data = new ArrayList<String[]>();
List<String> tmp= new ArrayList<String>();
for(int m = 0; m < hugeList.size(); m++) {
String[] values = hugeList.get(m);
tmp.add(values[0]);
}
data.add(tmp.toArray(new String[0]));
writer.writeAll(data);
}
As you can see I get my data still vertically... Why?
I thing you are already on the right way.
You have 2 possibilities.
1. data.add(hugeList.get(4));
2. for(int m = 0; m < hugeList.size(); m++) {
if(m==4){
String[] values = hugeList.get(m);
data.add(values);
break;
}
}
UPDATE
Goal: I have saved all values from one sheet at the time in hugeList. Now I want to write only the 5th column into a new sheet. Problem: The logic behind this goal.
My Approach for a result in rows
List<String[]> data = new ArrayList<String[]>();
List<String> tmp= new ArrayList<String>();
for(int m = 0; m < hugeList.size(); m++) {
String[] values = hugeList.get(m);
tmp.add(values[4]);
}
data.add(tmp.toArray(new String[0]));
}
My Approach for a result in Column
for (int j = 0; j < fileList.size(); j++) {
String csvFile = readPath + fileList.get(j);
System.out.println("Read: " + csvFile);
reader = new CSVReader(new FileReader(csvFile), ';');
hugeList = reader.readAll();
String[] data = new String[1];
for (int m = 0; m < hugeList.size(); m++) {
String[] values = hugeList.get(m);
data[0] = values[0];
writer.writeNext(data);
}
}

Reading from file/array. No values. No errors

Any ideas what I am missing here? I am reading from a file array. The values in the text file don't get stored and there is no output. All I get is "names and totals" but no values.
I don't know.
private int[] totals;
private String[] names;
private String[] list;
private int count;
public void readData() throws IOException {
BufferedReader input = new BufferedReader(new FileReader("cookies.txt"));
//create the arrays
totals = new int[count];
names = new String[count];
list = new String[count];
//read in each pair of values
String quantityString = input.readLine();
for (int i = 0; i < count; i++) {
names[i] = input.readLine();
list[i] = input.readLine();
quantityString = input.readLine();
totals[i] = Integer.parseInt(quantityString);
}
}
public void display() {
System.out.println("names totals")
for (int i = 0; i < count; i++)
System.out.println(list[i] + " \t " + names[i] + " \t" + totals[i]);
}
//called to compute and print the result
public void printResults() {
//find the best teacher
int maxIndex = 0;
int maxValue = 0;
//for each record stores
for (int i = 0; i < count; i++) {
//if we have a new MAX value so far, update variables
if (maxValue < totals[i]) {
maxValue = totals[i];
maxIndex = i;
}
}
}
You never give the variable count a value, so it initialized to 0 by Java. This means that your arrays are of size 0 also.
So since count is zero, you never read anything from the file, which is why nothing is stored in your arrays and also why nothing is printed out.
Example: Reading a File line-by-line
// create temporary variable to hold what is being read from the file
String line = "";
// when you don't know how many things you have to read in use a List
// which will dynamically grow in size for you
List<String> names = new ArrayList<String>();
List<Integer> values = new ArrayList<Integer>();
// create a Reader, to read from a file
BufferedReader input = new BufferedReader(new FileReader("cookies.txt"));
// read a full line, this means if you line is 'Smith 36'
// you read both of these values together
while((line = input.readLine()) != null)
{
// break 'Smith 36' into an array ['Smith', '36']
String[] nameAndValue = line.split("\\s+");
names.add(nameAndValue[0]); // names.add('Smith')
values.add(Integer.parseInt(nameAndValue[1]); // values.add(36);
}

Categories