Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
This part is supposed to add a train to the TRAININFO table in my database. I have to use mysql.
So there are some constraints I have to see before adding the train.
jTextField1.getText(); TrainNo. should not have more than 6 characters and it should be an integer.
jTextField2.getText(); TrainName. Should not have more than 30 characters.
jTextField10,jTextField12 have Depttime and araivaltime respectively.
It has 5 characters,"hr:mn" So I have to check if 'hr'<=24 and 'mn'<=59.
If the value of jTextField3.getText()==0 (number of ac1 coaches), then the trainfare for ac1 coaches (tfac1) should also be ==0.
Keeping this in mind I have tried to code it. but it doesn't work.
when ever i run this there is an error message .
Please do tell me where I am wrong.
stacktrace:[Ljava.lang.StackTraceElement;#e596c9
okay heres how it should work:
String m="-",t="-",w="-",th="--",f="-",st="--",s="-",runson;
if(jCheckBox1.isSelected()==true)
{
m="m";
}
if(jCheckBox2.isSelected()==true)
{
t="t";
}
if(jCheckBox3.isSelected()==true)
{
w="w";
}
if(jCheckBox4.isSelected()==true)
{
th="th";
}
if(jCheckBox5.isSelected()==true)
{
f="f";
}
if(jCheckBox6.isSelected()==true)
{
st="st";
}
if(jCheckBox7.isSelected()==true)
{
s="s";
}
runson=m+t+w+th+f+st+s;
int h1=Integer.valueOf(jTextField10.getText().substring(0,2));
int mins1=Integer.valueOf(jTextField10.getText().substring(3,5));
int h2=Integer.valueOf(jTextField12.getText().substring(0,2));
int mins2=Integer.valueOf(jTextField12.getText().substring(2,3));
String time1=jTextField10.getText().substring(0,2)+jTextField10.getText().substring
(2,3)+jTextField10.getText().substring(3,5);
String time2=jTextField12.getText().substring(0,2)+jTextField12.getText().substring
(2,3)+jTextField12.getText().substring(3,5);
String tfac1=jTextField13.getText();
String tfac2=jTextField14.getText();
String tfac3=jTextField15.getText();
String tfsl=jTextField16.getText();
if(Integer.valueOf(jTextField3.getText())==0)
{
tfac1="0";
}
if(Integer.valueOf(jTextField4.getText())==0)
{
tfac2="0";
}
if(Integer.valueOf(jTextField5.getText())==0)
{
tfac3="0";
}
if(Integer.valueOf(jTextField6.getText())==0)
{
tfsl="0";
}
try
{
Class.forName("java.sql.DriverManager");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost/bvdb","root","enter");
Statement stm=con.createStatement();
int n=jTextField1.getText().trim().length();
int m=jTextField2.getText().trim().length();
if( n<=6 && m<=30 && h1<=24 && h2<=24 && mins1<=59 && mins2<=59 )
//This should check the constraints(1,2,3).if the condition is true the following statement will be executed ..else the catch block should be executed. But this doesn't seem to happen when i run the code. There is always an Exception raised.//
{
String q="INSERT INTO TRAININFO VALUE ("+jTextField1.getText()+",'"+jTextField2.getText()+"','"+jTextField9.getText()+"','"+time1+"','"+jTextField11.getText()+"','"+time2+"','"+runson+"',"+tfac1+","+tfac2+ ","+tfac3+","+tfsl+","+jTextField3.getText()+","+jTextField4.getText()+","+jTextField5.getText()+","+jTextField6.getText()+")";
stm.executeUpdate(q);
System.out.print("ADDED");
}
}
catch (Exception e)
{
JOptionPane.showMessageDialog(this,"Enter valid details");
}
s will always be - if !jCheckBox7.isSelected(). Think about it, you have:
if(something) {
...
} else {
s = ...;
}
if(something2) {
...
} else {
s = ...;
}
...
if(somethingN) {
...
} else {
s = "-"; //This will always be executed if !somethingN
}
You might want to have if.. else if instead of if below if.
Also note that it's not a good practice to compare boolean by writing == true. This might lead to problems if you, for example, write = instead of ==. Just write if(isTrue()) instead of if(isTrue() == true).
Basically you need to split your code into many functions. That will make it more readable.
Below is an example of how to structure your code, not a complete working code.
public void InsertTrainInfo() {
String runson = GetRunSon();
Boolean validTime1 = IsTimeValid(jTextField10.getText());
Boolean validTime2 = IsTimeValid(jTextField12.getText());
String time1 = GetTheTime(jTextField10.getText());
String time2 = GetTheTime(jTextField12.getText());
String tfac1 = GetFact(jTextField13.getText());
String tfac2 = GetFact(jTextField14.getText());
String tfac3 = GetFact(jTextField15.getText());
String tfsl = GetFact(jTextField16.getText());
try {
Class.forName("java.sql.DriverManager");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost/bvdb", "root", "enter");
Statement stm = con.createStatement();
if (jTextField1.getText().trim().length() <= 6 && jTextField2.getText().trim().length() <= 30 && validTime1 && validTime2) {
String q = "INSERT INTO TRAININFO VALUE (" + jTextField1.getText() + ",'" + jTextField2.getText() + "','" + jTextField9.getText() + "','" + time1 + "','" + jTextField11.getText() + "','" + time2 + "','" + runson + "'," + tfac1 + "," + tfac2 + "," + tfac3 + "," + tfsl + "," + jTextField3.getText() + "," + jTextField4.getText() + "," + jTextField5.getText() + "," + jTextField6.getText() + ")";
stm.executeUpdate(q);
ResetFOrm();
}
} catch (Exception e) {
GetValidDetails();
}
}
Boolean IsTimeValid(String timetext) {
Boolean isOK = false;
try {
int h1 = Integer.valueOf(timetext.substring(0, 2));
int mins1 = Integer.valueOf(timetext.substring(3, 5));
isOK = (h1 <= 24 && mins1 <= 59);
} catch (Exception e) {
isOK = false;
}
return isOK;
}
String GetTheTime(String timetext) {
// do some basic length checks
return timetext.substring(0, 2) + timetext.substring(2, 3) + timetext.substring(3, 5);
}
String GetFact(String facttext) {
String fact = facttext;
if (Integer.valueOf(fact) == 0) {
fact = "0";
}
return fact;
}
void ResetFOrm() {
jTextField1.setEditable(true);
jButton1.setEnabled(true);
jButton2.setEnabled(false);
jButton4.setEnabled(false);
jTextField2.setEditable(false);
jTextField9.setEditable(false);
jTextField10.setEditable(false);
jTextField11.setEditable(false);
jTextField12.setEditable(false);
jTextField13.setEditable(false);
jTextField14.setEditable(false);
jTextField15.setEditable(false);
jTextField16.setEditable(false);
jTextField3.setEditable(false);
jTextField4.setEditable(false);
jTextField5.setEditable(false);
jTextField6.setEditable(false);
jCheckBox1.setEnabled(false);
jCheckBox2.setEnabled(false);
jCheckBox3.setEnabled(false);
jCheckBox4.setEnabled(false);
jCheckBox5.setEnabled(false);
jCheckBox6.setEnabled(false);
jCheckBox7.setEnabled(false);
jTextField1.setText("");
jTextField2.setText("");
jTextField3.setText("");
jTextField4.setText("");
jTextField5.setText("");
jTextField6.setText("");
jTextField7.setText("");
jTextField8.setText("");
jTextField9.setText("");
jTextField10.setText("");
jTextField11.setText("");
jTextField12.setText("");
jTextField13.setText("");
jTextField14.setText("");
jTextField15.setText("");
jTextField16.setText("");
}
void GetValidDetails() {
JOptionPane.showMessageDialog(this, "Enter valid details");
jTextField9.setEditable(true);
jTextField10.setEditable(true);
jTextField11.setEditable(true);
jTextField12.setEditable(true);
jTextField13.setEditable(true);
jTextField14.setEditable(true);
jTextField15.setEditable(true);
jTextField16.setEditable(true);
jTextField2.setEditable(true);
jTextField3.setEditable(true);
jTextField4.setEditable(true);
jTextField5.setEditable(true);
jTextField6.setEditable(true);
jCheckBox1.setEnabled(true);
jCheckBox2.setEnabled(true);
jCheckBox3.setEnabled(true);
jCheckBox4.setEnabled(true);
jCheckBox5.setEnabled(true);
jCheckBox6.setEnabled(true);
jCheckBox7.setEnabled(true);
jTextField2.setText("");
jTextField3.setText("");
jTextField4.setText("");
jTextField5.setText("");
jTextField6.setText("");
jTextField7.setText("");
jTextField8.setText("");
jTextField9.setText("");
jTextField10.setText("");
jTextField11.setText("");
jTextField12.setText("");
jTextField13.setText("");
jTextField14.setText("");
jTextField15.setText("");
jTextField16.setText("");
jCheckBox1.setSelected(false);
jCheckBox2.setSelected(false);
jCheckBox3.setSelected(false);
jCheckBox4.setSelected(false);
jCheckBox5.setSelected(false);
jCheckBox6.setSelected(false);
jCheckBox7.setSelected(false);
}
String GetRunSon() {
String m = "-", t = "-", w = "-", th = "--", f = "-", st = "--", s = "-", runson;
if (jCheckBox1.isSelected()) {
m = "m";
}
if (jCheckBox2.isSelected()) {
t = "t";
}
if (jCheckBox3.isSelected()) {
w = "w";
}
if (jCheckBox4.isSelected()) {
th = "th";
}
if (jCheckBox5.isSelected()) {
f = "f";
}
if (jCheckBox6.isSelected()) {
st = "st";
}
if (jCheckBox7.isSelected()) {
s = "s";
}
runson = m + t + w + th + f + st + s;
return runson;
}
Related
Database ResultSet example
fclass,geometry,scenario
""elementary_school"","MULTIPOINT(303400.907447057 9044592.97070337)",66
""elementary_school"","MULTIPOINT(302777.056751395 9044333.43169871)",66
""elementary_school"","MULTIPOINT(304182.88271353 9042435.93276122)",66
""elementary_school"","MULTIPOINT(304592.928219703 9041564.59729198)",66
""elementary_school"","MULTIPOINT(311385.417245523 9052785.71100888)",66
""worship"","MULTIPOINT(307397.04764638 9039421.31774996)",66
""worship"","MULTIPOINT(304384.660908793 9047145.34109501)",66
""worship"","MULTIPOINT(304518.616783947 9039859.48619132)",66
""worship"","MULTIPOINT(304689.11878157 9041491.61685193)",66
""worship"","MULTIPOINT(304711.539434326 9047763.53595371)",66
""worship"","MULTIPOINT(303420.353637529 9048419.36252138)",66
Class to be accessed using reflection
public class Amenities {
public Integer amenities_id;
public Integer scenario;
public String fclass;
public String location;
public String buffer;
public TableInfo[] amenity_info;
}
Using reflection
private PostStatus getAmenities(String layerUP, String layer, String[] tableUP, String[] table, String scenarioId) {
PostStatus postStatus=new PostStatus();
String values = "";
for (int i = 0; i < tableUP.length; i++) {
if (tableUP[i].equals("location")) {
//values += "st_astext("+table[i]+")";
values += "st_astext("+table[i]+") as "+table[i];
} else if (tableUP[i].equals("scenario")) {
values += scenarioId+" as scenario";
} else {
values = "property_json->'" + table[i] + "' as "+ table[i] ;
}
if (i < tableUP.length - 1) {
values += ",";
} else {
values = values.replaceAll(",$", "");
}
}
String errorMsg = "";
String query ="";
try (
Connection connection = DriverManager.getConnection(
upURL,
upUser,
upPassword)) {
Statement statement = connection.createStatement();
query="select " + values + " from user_layer\n"
+ "inner join user_layer_data on user_layer.id = user_layer_data.user_layer_id\n"
+ "where user_layer.id=" + layer;
ResultSet data = statement.executeQuery(query);
ArrayList<Amenities> data_in = new ArrayList<>();
while (data.next()) {
Object o = new Amenities();
Class<?> c = o.getClass();
for (int i = 0; i < tableUP.length; i++) {
try {
Field f = c.getDeclaredField(tableUP[i]);
f.setAccessible(true);
if (!tableUP[i].equals("scenario") || !tableUP[i].equals("amenities_id")) {
f.set(o, data.getString(table[i]));
} else if (tableUP[i].equals("scenario")) {
Integer scen=(Integer)data.getInt(tableUP[i]);
f.set(o,scen );
} else if (tableUP[i].equals("location")) {
f.set(o, data.getString(table[i]));
} else if (tableUP[i].equals("amenities_id")) {
}
} catch (IllegalAccessException | IllegalArgumentException | NoSuchFieldException | SecurityException | SQLException e) {
log.error(e, errorMsg);
}
}
log.debug(o, "reflection");
data_in.add((Amenities) o);
}
Tables<Amenities> final_data = new Tables<Amenities>(data_in);
RestTemplate restTemplate = new RestTemplate();
postStatus=restTemplate.postForObject("http://" + upwsHost + ":" + upwsPort + "/amenities/", final_data, PostStatus.class);
return postStatus;
} catch (SQLException ex) {
for (Throwable e : ex) {
if (e instanceof SQLException) {
e.printStackTrace(System.err);
errorMsg += "SQLState: " + ((SQLException) e).getSQLState();
errorMsg += "Error Code: " + ((SQLException) e).getErrorCode();
errorMsg += "Message: " + e.getMessage();
/*Throwable t = ex.getCause();
while (t != null) {
errorMsg += "Cause: " + t;
t = t.getCause();
}*/
}
}
log.error(ex, errorMsg+query);
}catch(Exception e){
log.error(e, errorMsg+query);
}
postStatus.status="Error";
postStatus.message=errorMsg+query;
return postStatus;
}
My code is failing when it sets the value of the integer attribute of the object Amenites using the code Integer scen=(Integer)data.getInt(tableUP[i]); f.set(o,scen );, when I check the results the other values are assigned properly but the value of the field scenario remains in null.
I am sure that the values from the database ResultSet exist, also I tryied setting a static integer value 66, and It only shows the field with a 0value.
Since I am pretty new on Java, I would appreciate you help to find what am I doing wrong?
Currently, I'm am trying to parse from MealMaster files, but I am having an issue where Ingredients are being parsed as:
"Inch thick" due to the next line not having a quantity or unit, and carrying on from the previous
Also, I'm finding ingredients that are listed as "ingredient1 or ingredient2" and I'm not sure how to catagorise these in the parser
Here is an example of a file I'm parsing from and my code below
https://pastebin.com/fhkRczya
public void readIngredients() {
try {
Remover remover = new Remover();
ArrayList<Ingredient> ing = new ArrayList<Ingredient>();
while(!( "".equals(line.trim()))) {
parsedIngredients = line + "\n";
if(!line.contains("---") && !line.contains(":")) {
Ingredient currentIng = splitLine();
if(currentIng.getQuantity().length() == 0 && !ing.isEmpty()) {
Ingredient lastIng = ing.get(ing.size()-1);
if (currentIng.getName().toLowerCase().contains("inch") ) {
//System.out.println(currentIng.getName());
lastIng.setOther(lastIng.getOther() + "," + currentIng.getQuantity() + "," +currentIng.getName());
//System.out.println("OTher " + lastIng.getOther());
}else{
String lastIngName = lastIng.getName();
String addName = lastIngName + " " + currentIng.getName();
lastIng.setName(addName);
lastIng = remover.removeTo(unitWords,lastIng);
lastIng = remover.removeCustomWords(lastIng);
}
}else if (currentIng.getName().startsWith("-") || currentIng.getName().startsWith("For") ){
if(ing.size()>0) {
Ingredient lastIng = ing.get(ing.size()-1);
lastIng.setOther(currentIng.getQuantity() + " " + currentIng.getName());
}
}else {
currentIng = remover.removeTo(unitWords,currentIng);
currentIng = remover.removeCustomWords(currentIng);
//currentIng.setName(currentIng.getName().replace(",", ""));
System.out.println(currentIng.getName());
ing.add(currentIng);
}
}
line = reader.readLine();
}
for(int i = 0; i < ing.size();i++) {
removeCommaColon(ing.get(i));
}
for(int i = 0; i<ing.size();i++) {
ingredientsString = ingredientsString + ing.get(i).getName() + "|" + currentRecipe.getTitle() + " \n";
//ingredientsString = ingredientsString + currentRecipe.getTitle() + "\n";
}
currentRecipe.setIngredients(ing);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
try {
String hour = (String) comboBox.getSelectedItem();
String filename = fileName.getText();
String date = ((JTextField)dateChooser.getDateEditor().getUiComponent()).getText();
String text = txtKeyword.getText();
String newline = "\n";
String directory = Directory.getText();
File path = new File(directory);
File[] faFiles = path.listFiles();
for(File file: faFiles){
**if(file.getName().contains(filename + "-" + date + "[" + hour + "]") == true == true || file.getName().contains(filename + "-" + date) || file.getName().contains(filename)){**
String line = null;
Reader reader = new InputStreamReader(new FileInputStream(file), "utf-8");
BufferedReader br = new BufferedReader(reader);
while ((line = br.readLine()) != null) {
if(line.contains(text)){
jTextArea1.append(line + newline);
btnClear.setEnabled(true);
btnExport.setEnabled(true);
}
}
br.close();
}
}
}
catch(Exception e){
}
Here is my question. I'm trying to use input and loop method to search for a file. The above code works but my problem is lets say I try to find 2 different text files
1. billing-20140527[09].txt has
a)XGMS,2014-05-27 10:08:04,122,PLAYER_VERIFY,VERIFY to LBA,0x580000,0xC0000,253040.
b)XGMS,2034-05-27 30:08:04,122,PLAYER_VERIFY,VERIFY to LBA,0x580000,0xC0000,253040.
2. billing-20140527[10].txt has
a)XCGS,2014-05-27 10:08:04,122,PLAYER_VERIFY,VERIFY to LBA,0x580000,0xC0000,253040.
b)HELO
**I try to find the number 1 in both text files, if lets say I input the text file name is
billing, I can find the number 1 in both text file and output them:**
a) XGMS,2014-05-27 10:08:04,122,PLAYER_VERIFY,VERIFY to LBA,0x580000,0xC0000,253040.
b) XCGS,2014-05-27 10:08:04,122,PLAYER_VERIFY,VERIFY to LBA,0x580000,0xC0000,253040.
**However, if I specify the text file name: billing-20140527[09].txt and find the number 1 inside the text file, it will only output:
a) XGMS,2014-05-27 10:08:04,122,PLAYER_VERIFY,VERIFY to LBA,0x580000,0xC0000,253040.**
Can anyone help me with this? Guide or help?
I would work with the BufferedReader. Because it reads a whole line. And then you can split the line by a delimiter (lets say a space " " ). In your case I would write a split-method which receives a String and search for the regex you want.
private void doSearch(File f2) throws IOException,
fileHandler.FileException {
File[] children = f2.listFiles();
if (children != null && searching)
for (int i = 0; i < children.length; i++) {
if (g.isReady()) {
g.setReady(false);
if (!searching) {
g.setReady(true);
break;
} else if (isDirectory(children[i])) {
g.getActualDirectoryInhalt().setText(children[i].getPath()
.substring(g.root.getText().length()));
counterDirectories++;
doSearch(children[i]);
} else if (advancedSearch && !filterSpecified(children[i])) {
raiseCounterForDirectorySize(children[i]);
continue;
} else if (checkFile(children[i])) {
counterFiles++;
searchThroughFile(children[i], this.regex);
raiseCounterForDirectorySize(children[i]);
} else {
g.getTextAreaUnreachable().setText(
g.getTextAreaUnreachable().getText() + f2
+ "\n");
raiseCounterForDirectorySize(children[i]);
}
} else {
doSearch(children[i]);
}
g.setReady(true);
}
}
And here's the other method:
public static void searchThroughFile(File f2, String regex) throws IOException,
fileHandler.FileException {
try {
InputStream is = new BufferedInputStream(new FileInputStream(f2));
String mimeType = URLConnection.guessContentTypeFromStream(is);
ArrayList<String> linesFromFile = fileHandler.FileReaderer
.readFileIntoStringArrayList(f2);
String line = null;
if (f2.getAbsolutePath().contains(regex)) {
g.getTextAreaAdvanced()
.setText(
g.getTextAreaAdvanced().getText()
+ f2.getPath() + "\n");
}
if (linesFromFile.size() != 0) {
for (int i = 0; i < linesFromFile.size(); i++) {
line = linesFromFile.get(i);
Pattern MY_Pattern = Pattern.compile(regex);
Matcher m = MY_Pattern.matcher(line);
if (!searching) {
break;
}
MarkOne: if (!g.isReady()) {
break MarkOne;
} else {
g.setReady(false);
}
while (m.find() && searching) {
counterFoundPattern++;
g.getFoundFilesInhalt().setText(counterFoundPattern + "");
if (mimeType != null) {
g.getTextAreaAdvanced().setText(
g.getTextAreaAdvanced().getText()
+ f2.getPath() + " " + m.group()
+ " " + mimeType + " " + i+1 + "\n");
} else {
g.getTextAreaAdvanced().setText(
g.getTextAreaAdvanced().getText()
+ f2.getPath() + " " + m.group()
+ " " + i+1 + "\n");
}
}
g.setReady(true);
}
}
} catch (IOException e) {
MarkOne: if (!g.isReady()) {
break MarkOne;
} else {
g.setReady(false);
}
g.getTabpane().setForegroundAt(2, Color.RED);
g.getTextAreaException().setText(
g.getTextAreaException().getText() + e + "\n");
g.setReady(true);
} catch (OutOfMemoryError oute) {
MarkOne: if (!g.isReady()) {
break MarkOne;
} else {
g.setReady(false);
}
g.getTextAreaException().setText(
g.getTextAreaException().getText() + "\n"
+ "Fatal Error encured! The File will be skipped!"
+ "\n" + f2.getAbsolutePath());
g.getTabpane().setSelectedIndex(2);
g.setReady(true);
return;
}
}
How can I split a flat string based on 0102**? string tokenizer is working for only **. Is there any way to split based on 0102**? Please suggest
Here is my complete method
private String handleCibil(InterfaceRequestVO ifmReqDto, String szExtIntType) throws MalformedURLException, org.apache.axis.AxisFault, RemoteException {
/* Declaration and initiliazation */
ConfVO confvo = ifmReqDto.getExtConfVo();
String szResponse = null;
String cibilResponse = null;
String errorResponse = null;
String endpointURL = null;
long timeOut = confvo.getBurMgr().getBurInfo(szExtIntType).getTimeOut();
endpointURL = formWebServiceURL(confvo, szExtIntType);
URL url = new URL(endpointURL);
log.debug("Input xml for cibil "+ifmReqDto.getIfmReqXML());
BasicHttpStub stub= new BasicHttpStub(url,new org.apache.axis.client.Service());
szResponse = stub.executeXMLString(ifmReqDto.getIfmReqXML());
//szResponse=szResponse.replaceAll("&", "&");
log.debug("szResponse "+szResponse);
/* Validate if the obtained response is as expected by IFM */
try {
extDao = new ExtInterfaceXMLTransDAO(ifmReqDto.getSemCallNo(), ifmReqDto.getIdService());
extDao.updateRqstRespXML10g(ifmReqDto.getInterfaceReqNum(), szResponse, GGIConstants.IFM_RESPONSE);
//log.debug("CIBIL_RESPONSE_XPATH " + GGIConstants.CIBIL_RESPONSE_XPATH);
Document xmlDocument = DocumentHelper.parseText(szResponse);
String xPath = GGIConstants.RESPONSE_XPATH;
List<Node> nodes = xmlDocument.selectNodes(xPath);
for (Node node : nodes) {
String keyValue = node.valueOf(GGIConstants.RESPONSE_XPATH_KEY);
// log.debug("keyValue : " + keyValue);
if (keyValue.equalsIgnoreCase(GGIConstants.RESPONSE_XPATH_KEY_VALUE)) {
// log.debug("node value : " + node.getText());
cibilResponse = node.getText();
}
}
log.debug("cibilResponse " + cibilResponse);
String errorResponseXPATH = GGIConstants.CIBIL_ERROR_RESPONSE_XPATH;
List<Node> errorResponseNode = xmlDocument.selectNodes(errorResponseXPATH);
for (Node node : errorResponseNode) {
errorResponse = node.getText();
}
log.debug("errorResponse " + errorResponse);
if(cibilResponse!=null && cibilResponse.length()>0)
{
StringTokenizer cibilResponseResults = new StringTokenizer(cibilResponse,"**");
String tempResponse="";
ArrayList probableMatchList = new ArrayList();
while (cibilResponseResults.hasMoreElements()) {
tempResponse = (String) cibilResponseResults.nextElement();
if(tempResponse.length()>=80)
{
String memberRefNo = tempResponse.substring(69, 80).replaceAll(" ", "");
log.debug("memberRefNo " + memberRefNo);
if (memberRefNo.length() > 0) {
if (Integer.parseInt(memberRefNo) > 0) {
cibilResponse = tempResponse;
cibilResponse = cibilResponse+"**";
}
else
{
probableMatchList.add(tempResponse+"**");
}
}
else
{
probableMatchList.add(tempResponse+"**");
}
}
else
{
cibilResponse = tempResponse+"**";
}
}
log.debug("After finding the Member reference number cibilResponse " + cibilResponse);
log.debug("After finding the Probable reference list " + probableMatchList);
// TKN 008
cibilResponse=StringEscapeUtils.unescapeXml(cibilResponse).replaceAll("[^\\x20-\\x7e]","");
ifmReqDto.setIfmTransformedResult(cibilResponse);
ifmReqDto.setProbableMatchList(probableMatchList);
}
if (errorResponse!=null && errorResponse.length()>0) {
throw new GenericInterfaceException(errorResponse
+ " for the seq_request " + ifmReqDto.getSeqRequest() + " Seq_Interface_req is >> "
+ ifmReqDto.getInterfaceReqNum(),
GGIConstants.SEND_REQUEST_CONSTANT + Strings.padStart(String.valueOf(ifmReqDto.getIdService()), 2, GGIConstants.DEFAULT_NUMBER_STRING)
+ GGIConstants.CIBIL_ERROR_CODE);
}
else if (cibilResponse==null || StringUtils.isEmpty(cibilResponse) ) {
throw new GenericInterfaceException("Cibil TUEF response is empty >> cibil Service "
+ "for the seq_request " + ifmReqDto.getSeqRequest() + "Seq_Interface_req is >> "
+ ifmReqDto.getInterfaceReqNum(),
GGIConstants.SEND_REQUEST_CONSTANT + Strings.padStart(String.valueOf(ifmReqDto.getIdService()), 2, GGIConstants.DEFAULT_NUMBER_STRING)
+ GGIConstants.INTERFACE_ERROR_RESPONSE);
}
/* Setting Instinct response to ifmReqDto object */
} catch (SQLException e) {
log.error("SQLException while connecting to DataBase. Exception message is ", e);
throw new GenericInterfaceException("SQLException >> Instinct Service "
+ "for the seq_request " + ifmReqDto.getSeqRequest() + "Seq_Interface_req is >> "
+ ifmReqDto.getInterfaceReqNum(),
GGIConstants.SEND_REQUEST_CONSTANT + Strings.padStart(String.valueOf(ifmReqDto.getIdService()), 2, GGIConstants.DEFAULT_NUMBER_STRING)
+ GGIConstants.DB_OPERATION_ERROR);
} catch (GenericInterfaceException exp) {
log.error("Exception occured while valid:", exp);
throw exp;
} catch (Exception exp) {
log.error("Exception occured while valid:", exp);
throw new GenericInterfaceException("GeneralException >> Instinct Service "
+ "for the seq_request " + ifmReqDto.getSeqRequest() + "Seq_Interface_req is >> "
+ ifmReqDto.getInterfaceReqNum(),
GGIConstants.SEND_REQUEST_CONSTANT + Strings.padStart(String.valueOf(ifmReqDto.getIdService()), 2, GGIConstants.DEFAULT_NUMBER_STRING)
+ GGIConstants.UNKNOWN_ERROR);
}
return szResponse;
}
I recommend checking out the Java documentation, it provides a really good reference to start with. The .split method uses a regex to split up a string based on a delimiter.
String[] tokens = myString.split("0102\\*\\*");
For now I suspect that you forgot to escape * in split regex.
Try maybe
String[] resutl = yourString.split("0102\\*\\*");
In case you want * to represent any character then use . instead of *
String[] resutl = yourString.split("0102..");
In case you want * to represent any digit use \\d instead
String[] resutl = yourString.split("0102\\d\\d");
String string = "blabla0102**dada";
String[] parts = string.split("0102\\*\\*");
String part1 = parts[0]; // blabla
String part2 = parts[1]; // dada
Here we have a String: "blabla0102**dada", we call it string. Every String object has a method split(), using this we can split a string on anything we desire.
Do you mean literally split by "0102**"? Couldn't you use regex for that?
String[] tokens = "My text 0102** hello!".split("0102\\*\\*");
System.out.println(tokens[0]);
System.out.println(tokens[1]);
Hey guys can somebody show me a way good way of concatenating these strings with commas
Basically Im building a header criteria string showing which forms variables have been selected. I need to put commas in between the values and keep the break tags in place...can somebody see a better way to do it. I didnt want commas if there were just on value
This is what it looks like currently formatted:
protected final String getCriteriaHeader(MetricFilterCriteriaForm form)
{
String filterCriteria = "<br/>";
}
if (form.isSacNone() || form.isSac1() || form.isSac2() || form.isSac3())
{
filterCriteria = filterCriteria + "SAC:";
}
if (form.isSacNone())
{
filterCriteria = filterCriteria + " NONE";
}
if (form.isSac1())
{
filterCriteria = filterCriteria + " 1";
}
if (form.isSac2())
{
filterCriteria = filterCriteria + " 2";
}
if (form.isSac3())
{
filterCriteria = filterCriteria + " 3";
}
if (form.isSac1() || form.isSac2() || form.isSac3())
{
filterCriteria = filterCriteria + "<br/>";
}
if (form.isRegularScheduleType() || form.isLotScheduleType() || form.isBatchScheduleType())
{
filterCriteria = filterCriteria + "Schedule Type:";
}
if (form.isRegularScheduleType())
{
filterCriteria = filterCriteria + " Regular";
}
if (form.isLotScheduleType())
{
filterCriteria = filterCriteria + " Lot";
}
if (form.isBatchScheduleType())
{
filterCriteria = filterCriteria + " Batch";
}
return filterCriteria;
}
There are different ways to concatenate a set of values in a string with a separator.
With StringBuilder
Add the values with the comma, then remove the last comma manually.
StringBuilder sb = new StringBuilder();
if (/*condition1*/) {
sb.add("A,"); // value with comma
}
if (/*condition2*/) {
sb.add("B,");
}
sb.delete(sb.length()-1, sb.length()); // remove last character, which is the comma.
String result = sb.toString(); // get the result string.
With Guava's Joiner
Put it all in a List and use Joiner.
List<String> list = Lists.newArrayList();
if (/*condition1*/) {
list.add("A"); // no comma here
}
if (/*condition2*/) {
list.add("B");
}
String result = Joiner.on(",").join(list); // use Joiner to join elements of the list.
Alternatively to Guava, there is StringUtils.Join from Apache Common Lang. See #Iswanto San's answer.
You can use StringUtils.Join from Apache Common Lang
Example :
protected final String getCriteriaHeader(MetricFilterCriteriaForm form)
{
String filterCriteria = "<br/>";
List<String> sacs = new ArrayList<String>();
List<String> schedules = new ArrayList<String>();
if (form.isSacNone() || form.isSac1() || form.isSac2() || form.isSac3())
{
filterCriteria = filterCriteria + "SAC:";
}
if (form.isSacNone())
{
filterCriteria = filterCriteria + " NONE";
}
if (form.isSac1())
{
sacs.add(" 1");
}
if (form.isSac2())
{
sacs.add(" 2");
}
if (form.isSac3())
{
sacs.add(" 3");
}
filterCriteria += StringUtils.join(saces, ",");
if (form.isSac1() || form.isSac2() || form.isSac3())
{
filterCriteria = filterCriteria + "<br/>";
}
if (form.isRegularScheduleType() || form.isLotScheduleType() || form.isBatchScheduleType())
{
filterCriteria = filterCriteria + "Schedule Type:";
}
if (form.isRegularScheduleType())
{
schedules.add(" Regular");
}
if (form.isLotScheduleType())
{
schedules.add(" Lot");
}
if (form.isBatchScheduleType())
{
schedules.add(" Batch");
}
filterCriteria+=StringUtils.join(schedules, ",");
return filterCriteria;
}
At first avoid creating so much String instances by using StringBuilder. Then nest the conditions to speed things up a bit and to get more structure.
protected final String getCriteriaHeader(MetricFilterCriteriaForm form)
{
StringBuilder filterCriteria = new StringBuilder("<br/>");
if (form.isSacNone() || form.isSac1() || form.isSac2() || form.isSac3())
{
filterCriteria.append("SAC:");
if (form.isSacNone())
filterCriteria.append(" NONE");
if (form.isSac1() || form.isSac2() || form.isSac3())
{
if (form.isSac1())
filterCriteria.append(" 1,");
if (form.isSac2())
filterCriteria.append(" 2,");
if (form.isSac3())
filterCriteria.append(" 3,");
if(','==filterCriteria.charAt(filterCriteria.length-1) )
filterCriteria.deleteCharAt(filterCriteria.length-1)
filterCriteria.append("<br/>");
}
}
if (form.isRegularScheduleType() || form.isLotScheduleType() || form.isBatchScheduleType())
{
filterCriteria.append("Schedule Type:");
if (form.isRegularScheduleType())
filterCriteria.append(" Regular,");
if (form.isLotScheduleType())
filterCriteria.append(" Lot,");
if (form.isBatchScheduleType())
filterCriteria.append(" Batch,");
if(','==filterCriteria.charAt(filterCriteria.length-1) )
filterCriteria.deleteCharAt(filterCriteria.length-1)
}
return filterCriteria.toString();
}
If only one condition can be true,you can also use else if instead of cascades of if.
You could use a StringBuilder to build the string, it's better than simple string concatenation :
StringBuilder sb = new StringBuilder();
if(XX) {
sb.append("XX");
}
return sb.toString();
Hope this helps :)
PS: Note that StringBuilder is faster than StringBuffer, but the latter is Thread-safe.
EDIT
I re-read your question, and it seems I don't answer it well, although I provided useful advice (IMHO). I don't understand exactly what you need.
I would suggest whacking the thing into a List then using a StringBuilder:
protected final String getCriteriaHeader(MetricFilterCriteriaForm form) {
final StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("<br/>");
final List<String> sacList = new LinkedList<String>();
if (form.isSacNone() || form.isSac1() || form.isSac2() || form.isSac3()) {
stringBuilder.append("SAC: ");
}
if (form.isSacNone()) {
sacList.add("NONE");
}
if (form.isSac1()) {
sacList.add("1");
}
if (form.isSac2()) {
sacList.add("2");
}
if (form.isSac3()) {
sacList.add("3");
}
final Iterator<String> sacIter = sacList.iterator();
while (sacIter.hasNext()) {
stringBuilder.append(sacIter.next());
if (sacIter.hasNext()) {
stringBuilder.append(", ");
}
}
if (form.isSac1() || form.isSac2() || form.isSac3()) {
stringBuilder.append("<br/>");
}
final List<String> scheduleTypeList = new LinkedList<String>();
if (form.isRegularScheduleType() || form.isLotScheduleType() || form.isBatchScheduleType()) {
scheduleTypeList.add("Schedule Type: ");
}
if (form.isRegularScheduleType()) {
scheduleTypeList.add("Regular");
}
if (form.isLotScheduleType()) {
scheduleTypeList.add("Lot");
}
if (form.isBatchScheduleType()) {
scheduleTypeList.add("Batch");
}
final Iterator<String> scheduleTypeIter = scheduleTypeList.iterator();
while (scheduleTypeIter.hasNext()) {
stringBuilder.append(scheduleTypeIter.next());
if (scheduleTypeIter.hasNext()) {
stringBuilder.append(", ");
}
}
return stringBuilder.toString();
}