multidimensional String[][] array java - java

I have an array that is from .split command and want to put it into an array called String[][] datatabvars, I do not know how to turn datatabvars into a two dimensional array and put the data into it.
public String[] getList() {
String file_name = "path";
String[] links = null;
String[][] datatabvars = null; // this var
int numberOfDatatabs = 0;
try {
ReadFile file = new ReadFile(file_name);
String[] aryLines = file.OpenFile();
int i;
for(i=0; i < aryLines.length; i++) { //aryLines.length
if (aryLines[i].substring(0, 7).equals("datatab")) {
aryLines[i] = aryLines[i].replace("datatab["+Integer.toString(numberOfDatatabs)+"] = new Array(", "");
aryLines[i] = aryLines[i].replace(");", "");
datatabvars = aryLines[i].split(","); // this split array
numberOfDatatabs++;
}
}
System.out.println(datatabvars[0]);
}catch (IOException e) {
System.out.println( e.getMessage() );
}
return links;
}

Update the two lines(I added comment) as below: (I am assuming that rest of your code is working)
String[][] datatabvars = null; // this var
int numberOfDatatabs = 0;
try {
ReadFile file = new ReadFile(file_name);
String[] aryLines = file.OpenFile();
datatabvars = new String[aryLines.length][]; // INITIALIZED
int i;
for(i=0; i < aryLines.length; i++) { //aryLines.length
if (aryLines[i].substring(0, 7).equals("datatab")) {
aryLines[i] = aryLines[i].
replace("datatab["+Integer.toString(numberOfDatatabs)+"] =
new Array(", "");
aryLines[i] = aryLines[i].replace(");", "");
datatabvars[i] = aryLines[i].split(","); // this split array: ASSIGNED
numberOfDatatabs++;
}
}
System.out.println(datatabvars[0]);

In general, arrays are to avoided like the plague - use collections if possible:. In this case, split() returns a String[], so use that, but use List<String[]> to store multiple String[]:
List<String[]> datatabvars = new ArrayList<String[]>();
...
String[] array = input.split(",");
datatabvars.add(array);
You find life is much easier using collections than arrays.

Related

Java get java.awt.Color from string

So I have a string that looks something like this:
text java.awt.Color[r=128,g=128,b=128]text 1234
How could I pop out the color and get the rgb values?
You can get the rgb values from that string with this:
String str = "text java.awt.Color[r=128,g=128,b=128]text 1234";
String[] temp = str.split("[,]?[r,g,b][=]|[]]");
String[] colorValues = new String[3];
int index = 0;
for (String string : temp) {
try {
Integer.parseInt(string);
colorValues[index] = string;
index++;
} catch (Exception e) {
}
}
System.out.println(Arrays.toString(colorValues)); //to verify the output
The above example extract the values in an array of Strings, if you want in an array of ints:
String str = "text java.awt.Color[r=128,g=128,b=128]text 1234";
String[] temp = str.split("[,]?[r,g,b][=]|[]]");
int[] colorValues = new int[3];
int index = 0;
for (String string : temp) {
try {
colorValues[index] = Integer.parseInt(string);
index++;
} catch (Exception e) {
}
}
System.out.println(Arrays.toString(colorValues)); //to verify the output
As said before, you will need to parse the text. This will allow you to return the RGB values from inside the string. I would try something like this.
private static int[] getColourVals(String s){
int[] vals = new int[3];
String[] annotatedVals = s.split("\\[|\\]")[1].split(","); // Split the string on either [ or ] and then split the middle element by ,
for(int i = 0; i < annotatedVals.length; i++){
vals[i] = Integer.parseInt(annotatedVals[i].split("=")[1]); // Split by the = and only get the value
}
return vals;
}

Remove all java keywords from a file

I am going through a project where I need to remove all java keywords from a java file. First I create a keyword.java file and store all java keywords into this file.Like abstract continue for new switch assert default goto package etc which I store keyword.java file. I have another file named newFile.java and I read all data from newFile.java as a String. I have to remove all java keywords from newFile.java file. As far I tried:
public void processFile() throws IOException {
String data = "";
data = new String(Files.readAllBytes(Paths.get("H:\\java\\Clone\\newFile.java"))).trim();
String rmvPunctuation = removePunctuation(data);
String newLineRemove = rmvPunctuation.replace("\n", "").replace("\r", "");
String spaceRemove = newLineRemove.replaceAll("( ){2,}", " ");
removeKeyword(spaceRemove);}
public void removeKeyword(String fileAsString) throws FileNotFoundException, IOException {
ArrayList<String> keyWordList = new ArrayList<>();
ArrayList<String> methodContentList = new ArrayList<>();
FileInputStream fis = new FileInputStream("H:\\java\\keyword.java");
byte[] b = new byte[fis.available()];
fis.read(b);
String[] keyword = new String(b).trim().split(" ");
String newString = "";
for (int i = 0; i < keyword.length; i++) {
keyWordList.add(keyword[i].trim());
}
String[] p = fileAsString.split(" ");
for (int i = 0; i < p.length; i++) {
if (!(keyWordList.contains(p[i].trim()))) {
newString = newString + p[i] + " ";
}
}
System.out.println("" + newString);
}
But I could not found my desired output. All the java keywords are not removed from newFile.java file. I think StackOverflow community help me to solve this. I am also a beginner.
I also tried:
public void removeKeyword(String fileAsString) throws IOException {
String keyWord = new String(Files.readAllBytes(Paths.get("H:\\java\\keyword.java"))).trim();
String text = fileAsString.trim();
ArrayList<String> wordList = new ArrayList<>();
ArrayList<String> keyWordList = new ArrayList<>();
wordList.addAll(Arrays.asList(text.split(" ")));
keyWordList.addAll(Arrays.asList(keyWord.split(" ")));
wordList.removeAll(keyWordList);
System.out.println("" + wordList.toString());
}

How can I store columns of a text in an array with which I can then make calculations?

community,
I am currently stuck on a homework assignment which requires me to read a text file and then make further calculations with it, my questions are now.
How do I read a text file and store the columns in several arrays to make further calculations?
I have written a piece of code which already reads the file, but doesn't seem to store the columns in arrays as I keep getting "ArrayOutOfBoundsException".
I have already tried the given code below, which doesn't give me what I need.
Unfortunately, I haven't found anything that was able to solve the problem.
The columns are separated by Tabs.
This is what the table looks like
Date Open High Low Close Volume
29.12.2017 12.980,09 12980.74 12.911,773 12.917.64 1.905.806.208
....
....
....
and so on
try {
ArrayList < String > KursDaten = new ArrayList<String>();
String Zeile = null;
while ((Zeile = in.readLine()) != null) {
Zeile = Zeile.replaceAll("\u0000", "");
Zeile = Zeile.replaceAll("�", "");
String[] columns = in.readLine().split(" ");
columns = in.readLine().split("\t");
String data = columns[columns.length - 1];
KursDaten.add(data);
out.println(Zeile);
}
int size = KursDaten.size();
out.println(KursDaten.size());
String[] arr1 = new String[size];
String[] arr2 = new String[size];
String[] arr3 = new String[size];
String[] arr4 = new String[size];
String[] arr5 = new String[size];
String[] arr6 = new String[size];
for (int i = 0; i < size; i++) {
String[] temp = KursDaten.get(i).split("\t\t");
temp = KursDaten.get(i).split("\t");
arr1[i] = temp[0];
arr2[i] = temp[1];
arr3[i] = temp[2];
arr4[i] = temp[3];
arr5[i] = temp[4];
arr6[i] = temp[5];
System.out.println(Arrays.toString(arr1));
}
}
catch (NullPointerException e) {
}
I expect the columns of the list to be stored in the different arrays, with which I then can make further calculations as needed.

Transffering data from multiple arraylist to a multidimensional array

I need help transferring data from 4 ArrayLists to a multi-dimensional array. Please look at the comments in my variables.
I need to put the data from all the arraylists into card[][] in this format:
card[][] = {{questions,answers,category,essay}};
codes:
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JFileChooser;
public class Test {
static JFileChooser chooser = new JFileChooser();
//these need to go into card[][]
static List<String> questions = new ArrayList<String>();
static List<String> answers = new ArrayList<String>();
static List<String> categories = new ArrayList<String>();
static List<String> essays = new ArrayList<String>();
static String[][] card;
public static void main(String[] args) {
OpenFile();
}
public static void OpenFile() {
int retrival = chooser.showOpenDialog(null);
if (retrival == JFileChooser.APPROVE_OPTION) {
String line;
try (BufferedReader br = new BufferedReader(new FileReader(
chooser.getSelectedFile()))) {
while ((line = br.readLine()) != null) {
String[] splitted = line.split("Question: ");
String[] splittedAnswer = line.split("Answer: ");
String[] splittedCategory = line.split("Category: ");
String[] splittedEssay = line
.split("Essay Question Possibility: ");
if (splittedAnswer.length == 2) {
answers.add(splittedAnswer[1]);
} else if (splitted.length == 2) {
questions.add(splitted[1]);
} else if (splittedCategory.length == 2) {
categories.add(splittedCategory[1]);
} else if (splittedEssay.length == 2) {
essays.add(splittedEssay[1]);
}
}
br.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
}
Assuming all the array list are of same size you can do as below,
String[][] card = new String[4][questions.size()];
for (int i = 0; i < questions.size(); i++) {
card[0][i] = questions.get(i);
card[1][i] = answers.get(i);
card[2][i] = categories.get(i);
card[3][i] = essays.get(i);
}
Suggestion
But I advice you to use Object oriented data structure for holding your data. Using multiple list or 2D arrays are not advisable.
You can simply define your structure as
public class Card {
String question;
String answer;
String categories;
String essay;
}
And you have have the list as.
List<Card> cards = new ArrayList<Cards>();
I think that all arraylists have one size. If 'not' you should first find minimal size of arraylists and then use it instead questions.size():
card = new String[questions.size()][4];
for (int i = 0; i < card.length; i++){
card[i][0] = questions.get(i);
card[i][1] = answers.get(i);
card[i][2] = categories.get(i);
card[i][3] = essays.get(i);
}
Result will be like this:
{{"q1","a1","c1","e1"}, {"q2","a2","c2","e2"}, {"q3","a3","c3","e3"}, {"q4","a4","c4","e4"}, ...};
Try this ,
String card[][] ;
List<String> questions = new ArrayList<String>();
List<String> answers = new ArrayList<String>();
List<String> categories = new ArrayList<String>();
List<String> essays = new ArrayList<String>();
questions.add("11");
questions.add("12");
questions.add("13");
answers.add("21");
answers.add("22");
answers.add("23");
categories.add("31");
categories.add("32");
categories.add("33");
essays.add("41");
essays.add("42");
essays.add("43");
card=new String [essays.size()][4];
for(int i=0;i<questions.size();i++)
{
card[i][0]=questions.get(i);
card[i][1]=answers.get(i);
card[i][2]=categories.get(i);
card[i][3]=essays.get(i);
}
Output will be
{{"11","21","31","41"}, {"12","22","32","42"}, {"13","23","33","43"}, ...};

Putting multiple String into an ArrayList

So I'm doing this:
int len = lv.getCount();
List<String> Cool = null;
SparseBooleanArray checked = lv.getCheckedItemPositions();
for (int i = 0; i < len; i++)
if (checked.get(i)) {
String item = String.valueOf(names.get(i));
int start = item.lastIndexOf('=') + 1;
int end = item.lastIndexOf('}');
String TEST = item.substring(start, end);
Log.d("Log", TEST);
Cool = new ArrayList<String>();
Cool.add(TEST);
}
String NEW = StringUtils.join(Cool, ',');
Log.d("Log", NEW);
Which evey time replaces the thing in the list with whatever the next item is. How do i make it put the strings after each other.
Thanks for the help.
List<String> Cool = new ArrayList<String>();
create the list at the top
Cool = new ArrayList<String>();
and delete this line because it will always create a new list what you dont want
You're constructing a new ArrayList in every iteration of your for loop
Log.d("Log", TEST);
Cool = new ArrayList<String>(); // NOT HERE!!!!
Cool.add(TEST);
construct it once, outside the loop
List<String> Cool = new ArrayList<String>(); // also Cool should be cool.
the reason it keeps resetting the list is because you initialized the List in a loop.
Initialize it outside the loop and the algorithm will work.
Initialization:
Cool = new ArrayList();
Corrected code:
int len = lv.getCount();
List<String> Cool = new ArrayList<String>();
SparseBooleanArray checked = lv.getCheckedItemPositions();
for (int i = 0; i < len; i++)
if (checked.get(i)) {
String item = String.valueOf(names.get(i));
int start = item.lastIndexOf('=') + 1;
int end = item.lastIndexOf('}');
String TEST = item.substring(start, end);
Log.d("Log", TEST);
Cool.add(TEST);
}
String NEW = StringUtils.join(Cool, ',');
Log.d("Log", NEW);

Categories

Resources