Scriptella: using collections and for each loop - java

How can I write the following code in scriptella?
It looks like it thinks that I'm trying to compare Set and String, and it does not like the last for loop.
And what is the way to write logical expressions like &&.
Thank you.
<connection id="java" driver="scriptella.driver.janino.Driver"/>
<script connection-id="java>
//some code
if(finalOrderCounter < numberOfEntries){
Set <String> set = new HashSet <String>();
for(int i = 0; i < fieldNames.length; i++){
set.add(fieldNames[i]);
}
for(int i = 0; i < fieldNamesFromXML.length; i++){
set.remove(fieldNamesFromXML[i]);
}
String exception = "";
for(String element:set)
exception += element +"\n";
throw new IOException("Field(s)\n" + exception + "do(es) not exits in the source database");
}

Maybe you can try the "classic" 'for' loop syntax?
StringBuffer exception = new StringBuffer();
for (int i = 0; i < set.size(); ++i) {
String element = (String) set.get(i);
exception.append(element);
exception.append("\n");
}
throw new IOException("Field(s)\n" + exception.toString() + "do(es) not exits in the source database");
BTW, what error are you getting?

Related

my code runs for 15mins but only white output?

I'm doing a stop word code for data cleaning. I followed a tutorial in YouTube: https://www.youtube.com/watch?v=ckQUlI7x7hI his code works and shows output but mine doesn't
I'm using english stop words, example of my stop words are "a", "an", "away", "keeps". the input will be "An apple a day keeps the doctor away" output should be "apple day the doctor".
this is the content of my file: https://ufile.io/gikev
Here is the code:
import java.io.FileInputStream;
import java.util.ArrayList;
public class DataCleaning {
public static void main(String[] args) {
ArrayList sw = new ArrayList<>();
try{
FileInputStream x = new FileInputStream("/Users/Dan/Desktop/DATA/stopwords.txt");
byte b[] = new byte[x.available()];
x.read(b);
x.close();
String data[] = new String(b).split("\n");
for(int i = 0; i < data.length; i++)
{
sw.add(data[i].trim());
}
FileInputStream xx = new FileInputStream("/Users/Dan/Desktop/DATA/cleandata.txt");
byte bb[] = new byte[xx.available()];
xx.read(bb);
xx.close();
String dataa[] = new String(bb).split("\n");
for(int i = 0; i < dataa.length; i++)
{
String file = "";
String s[] = dataa[i].split("\\s");
for(int j = 0; j < s.length; i++)
{
if(sw.contains(s[j].trim().toLowerCase()))
{
file=file + s[j] + " ";
}
}
System.out.println(file + "\n");
}
} catch(Exception a){
a.printStackTrace();
}
}
}
and when I run mine it only does this:
what should I do?
There are 3 issues with your code :
You are incrementing the wrong variable in the innermost loop thus
resulting in an infinite loop as j will always be lesser that
s.length and you are never incrementing j. Change this line :
for (int j = 0; j < s.length; i++) {
to
for (int j = 0; j < s.length; j++) {
To print words that are not stopwords you need to negate your if
condition as follows :
if (!sw.contains(s[j].trim().toLowerCase()))
Also, make sure the file stopwords.txt is separated by \n(new
line) because you are splitting it based on that and not like the
file in the link shared by you.
I recommend you to indent your code and also use meaningful names to name your variables. Debugging issues like this will be much simpler.

How to check if a string is contained in another substring using "indexOf" and "for" iterator in Java Language?

I'm new to programming in Java so I'd like some help on this matter, thank you very much for your time :)
I want to check if "CheckAutonomy" is contained in a substring using indexOf and a for iterator to iterate trough my objects,(ambient contains 4 objects everytime, this is the "wouldbe" code :
ReEdit: I added more details, i hope this will be enough , i really don't know how to grasp it :|
public static void scrivi(JSONArray jsa, String nome, String versione ) throws IOException{
for(int j = 0; j < jsa.length(); j++){
JSONArray endpoint = jsa.getJSONArray(j);
bsrURI = getObjectValueFromJSONArrayEndpointData(endpoint, "bsrURI");
String query = normalizeQuery(QUERY_GET_BSRURI, null, null, null, bsrURI);
JSONArray jsaUriBSR = queryExecutor(query);
/*???
for(i = o; i < 3; i++){
if (ambient.contains("CheckAutonomy")){
}
}
???*/
String ambient = jsaUriBSR.get(0).toString()
.substring( jsaUriBSR.get(0).toString().indexOf('#') + 1, jsaUriBSR.get(0).toString().length() - 2 );
System.out.println(ambient);
}*/
String line = ambient + ";\n";
bw.write(line);
}
}
Solved it with something like this:
for(int i = 0; i < result.length(); i++){
if (risultato.get(i).toString().contains("CheckAutonomy"))
ambient = result.get(i).toString()
.substring( result.get(i).toString().indexOf('#') + 1,
result.get(i).toString().length() - 2 );
}
Nevertheless, thank you for your time ! :P

Program Overwriting Array with Null

For a project in school (intro to java), we have to make a program using arrays. I decided to make a login program that stores logins. It works perfectly, except when deleting items. This is my code
public void delete() throws FileNotFoundException{
int p;
c.clear();
c.print("Please enter a website to delete it's login info: ");
String delete_name = c.readLine();
Boolean found = false;
// Search for the search key, and display the matching elements
c.println("Searching for " + delete_name + "...");
for (int i = 0; i < pass.length; i++)
if (pass[i][0].equals(delete_name)) {
c.println("Deleting login for " + pass[i][0]);
String new_array[][] = new String[pass.length - 1][3];
//remove an element
for (int w = 0; i < new_array.length; i++)
for (int j = 0; j <= 2; j++) {
p = w;
if (i >= p) {
new_array[w][j] = pass[w + 1][j];
} else {
new_array[w][j] = pass[w][j];
}
}
found = true;
pass = new_array;
}
if (found == false) {
c.println("No luck! " + delete_name + " wasn't found, please try again.");
delete();
}
fileWriter();
}
When it writes to the file, anything after the part that should have been deleted gets changed to "null".
Sorry if the format is awful, I'm just starting with java :) Any help is greatly appreciated, thanks!
When deleting a row of a 2D array in Java, you can use this shortcut (no for-loops needed)
List<String[]> tempArr = new ArrayList<String[]>(Arrays.asList(pass));
//Remove row at index of "delete_name":
for(int i = 0; i < pass.length; i++){
if(pass[i][0].equals(delete_name)){
tempArr.remove(i);
}
}
String[][] new_array = tempArr.toArray(new String[][]{});
However, this solution only works if you are only deleting one object in the List. I would suggest looking into "iterators" to make this solution better.
EDIT:
Here is an example with an iterator
String[][] pass = new String[][]{{"Name","data1","data2"}};
List<String[]> tempArr = new ArrayList<String[]>(Arrays.asList(pass));
for (Iterator<String[]> iterator = tempArr.iterator(); iterator.hasNext();) {
String id = iterator.next()[0];
if (id.equals(delete_name)){
iterator.remove();
}
}

Troubles getting results from ResultSet

How can I have a var which contains all the records I get from a resultset?
So far I have this code:
while (rs.next()) {
for (int i = 1; i <= columnCount; i++) {
String resultado = "";
resultado = rs.getString(i);
columnValue += resultado;
}
jTextPane2.setText(jTextPane2.getText() + columnValue + ", ");
}
I want that when resultado gets the value from the rs.getString(i), fills the var columnValue so that I have a var which SHOULD have all the records I get from the rs, but is not working. Any help?
The result I get is:
(id_tlf, cod_area)
1+58, 1+582+104, 1+582+1043+60
so as you see, the first 2 results repeat in every row
Please prefer a StringBuilder to creating lots of String temporary values (they pollute the intern cache for one thing). Next, you don't need to store each column in another local variable. Basically, I would do something like
StringBuilder sb = new StringBuilder();
while (rs.next()) {
for (int i = 1; i <= columnCount; i++) {
if (i != 1) {
sb.append(", ");
}
sb.append(rs.getString(i));
}
sb.append(System.lineSeparator());
}
jTextPane2.setText(sb.toString());
Note the above clears jTextPane2, if you intend to append then you could change the first line to to something like
StringBuilder sb = new StringBuilder(jTextPane2.getText());
sb.append(System.lineSeparator()); // <-- start the next line... and then iterate rs
Not sure if I understand right, but it could be something like this:
while (rs.next()) {
for (int i = 1; i <= columnCount; i++) {
String resultado = "";
resultado = rs.getString(i);
columnValue+=resultado;
}
columnValue+=", ";
}
jTextPane2.setText(columnValue);
your problem is your columnValue and your jTextPane.
When you want to add the text to your jTextPane, you are adding the text you already have inside the textpane AND you add add the columnValue text (which is already within the textpane).
Within your for loop, you write the following to get the result:
columnValue+=resultado;
Here you should write
columnValue=resultado;
This should fix your problem.
I hope that I could help you.
Best regards. Levkaz
You are accumulation the column value each inner iteration (without reinitializing to the empty string each outer iteration):
columnValue+=resultado;
And you are accumulation the total message each outer iteration:
jTextPane2.setText(jTextPane2.getText() + columnValue + ", ");
Pick one :-)
I'd recommend using (Java 8) StringJoiner, and only updating jTextPane2 at the end of the loop:
StringJoiner sj = new StringJoiner(", ");
while (rs.next()) {
StringBuilder columnValue = new StringBuilder();
for (int i = 1; i <= columnCount; i++) {
columnValue.append(rs.getString(i));
}
sj.add(columnValue.toString());
}
jTextPane2.setText(sj.toString());

Java JTextArea multiline help

one problem I'm having is i have 2 JTextAreas and i need to add a list of items to them.
The problem I'm running into is the string doesn't automatically move to the next line when it reaches the end of the JTextArea. So to solve this problem I tried this: (sorry if my code is kinda sloppy.)
public void setIncludeAndExclude(ArrayList<JComboBox> boxes){
String in = "",ex = "";
String[] inSplit, exSplit;
boolean[] include = new boolean[boxes.get(0).getModel().getSize()-1];
for(int i = 0; i < boxes.size(); i ++){
if(boxes.get(i).getSelectedIndex() != 0){
include[boxes.get(i).getSelectedIndex() -1] = true;
}
}
for(int i = 0; i < include.length; i ++){
if(include[i]){
//numToItem is a method that turns an int into a string e.g. 1 = "Acesss Doors"
in += (numToItem(i+1)+ ", ");
}else{
ex += (numToItem(i+1)+ ", ");
}
}
//take off the last comma
in = in.substring(0,in.lastIndexOf(","));
ex = ex.substring(0,ex.lastIndexOf(","));
//get how many lines there should be
inSplit = new String[(in.length()/100) +1];
exSplit = new String[(ex.length()/100) +1];
String temp;
int istart = 0, iend = Math.min(100, in.length()), estart = 0, eend = Math.min(100, ex.length());
for(int i = 0; i < inSplit.length; i ++){
try{
temp = in.substring(istart, iend);
int Iindex = temp.lastIndexOf(",");
temp = ex.substring(estart, eend);
int Eindex = temp.lastIndexOf(",");
inSplit[i] = in.substring(istart, Iindex);
exSplit[i] = ex.substring(estart, Eindex);
istart = Iindex; iend = Math.min(iend + 100, in.length());
estart = Eindex; eend = Math.min(eend + 100, ex.length());
}catch(Exception e){
e.printStackTrace();
}
}
//reset in and ex to ""
in = ""; ex = "";
//set in and ex to the new string with newline characters
for(int i = 0; i < inSplit.length; i ++){
in += inSplit[i] + "\n";
ex += exSplit[i] + "\n";
}
//set the text of the JTextAreas
Include.setText(in);
Exclude.setText(ex);
}
any help on what i could do different or change would be much appreciated
JTextArea has setLineWrap(...) and the setWrapStyleWord(...) methods. Perhaps all you need to do is call these on your JTextArea's setting both to true.
One bit of criticism: your code is very hard to interpret as you give no indication which variables are JTextAreas (which I'm guessing are "Include" and "Exclude"), and no comments as to what is doing what. Please write your questions here with the idea that we know nothing about your code and can't read minds. The clearer your question, usually the easier it is to answer. Thanks.
Maybe a better solution is to use JList. See How to Use Lists.
The code you posted is not complete. If you still want to use a text area solution then post your SSCCE that demonstrates the problem.

Categories