Using split function to split the string but not getting desired result - java

want to split the string
String vv = "class="fcg">1.6M";
String[] breakvv = vv.split(">");
String breakvv0 = parts[0];
String breakvv1 = parts[1];
System.out.println(breakvv0);
System.out.println(breakvv1);
Output which i am getting is breakvv0 = an and breakvv1 = class="fcg">1.6M

String vv = "class=\"fcg\">1.6M";
String[] breakvv = vv.split(">");
String breakvv0 = breakvv[0];
String breakvv1 = breakvv[1];
System.out.println(breakvv0);
System.out.println(breakvv1);

public static void main(String args[]) {
String vv = "class=\"fcg\">1.6M";
String[] breakvv = vv.split(">");
String breakvv0 = breakvv[0];
String breakvv1 = breakvv[1];
System.out.println(breakvv0);
System.out.println(breakvv1);
}
}

Related

How to take input in expected form in java?

I want to take a string input in
%d+%d
format in java.How do i do it?
I know that I can do this with string.split() method. But I feel that it is going to be way more complex if I had to deal with more strings in input. Like
%d+%d-%d
I am looking for solutions that are close to a scanf solution for c.
I tried this for %d+%d
Scanner scanner = new Scanner(System.in);
String str = scanner.next();
String first,second;
String[] arr = str.split("\\+");
first = arr[0];
second = arr[1];
scanner.close();
And this for %d+%d-%d+%d..........=%d-%d+%d.....+%d...
private final String[] splitLoL(String txt) {
LinkedList<String> strList1 = new LinkedList<String>();
LinkedList<String> strList2 = new LinkedList<String>();
LinkedList<String> strList3 = new LinkedList<String>();;
strList1.addAll(Arrays.asList(txt.split("\\+")));
for(String str : strList1) {
String[] proxy = str.split("-");
strList2.addAll(Arrays.asList(proxy));
}
for(String str : strList2) {
String[] proxy = str.split("=");
strList3.addAll(Arrays.asList(proxy));
}
String[] strArr = new String[strList3.size()];
for(int i = 0; i < strArr.length; i++) {
strArr[i] = new String(strList3.get(i));
}
return strArr;
}
Try this:
String str = scanner.nextLine();
List<String> str2 = new ArrayList();
Matcher m = Pattern.compile("\\d+").matcher(str);
while(m.find()) {
str2.add(m.group());
}
Or you can do the following using JDK 9+:
import java.util.Scanner;
public class ScannerTrial {
public static void main(String[] args) {
Scanner scanner = new Scanner(" 4 z zz ggg 22 e");
scanner.findAll("\\d+").forEach((e) -> System.out.println(e.group()));
}
}
This would print
4 22

Java if-statement

public void searchKlijenta(KlijentiFormEvent klijentiFormEvent) throws SQLException {
String nazivK = klijentiFormEvent.getNaziv();
String adresaK = klijentiFormEvent.getAdresa();
String gradK = klijentiFormEvent.getGrad();
String drzavaK = klijentiFormEvent.getDrzava();
String telefonK = klijentiFormEvent.getTelefon();
String faxK = klijentiFormEvent.getFax();
String mailK = klijentiFormEvent.getMail();
String mobitelK = klijentiFormEvent.getMobitel();
String oibK = klijentiFormEvent.getOib();
String ugovorK = klijentiFormEvent.getUgovor();
String osobaK = klijentiFormEvent.getOsoba();
if (nazivK.length() == 0)
nazivK = null;
if (adresaK.length() == 0)
adresaK = null;
if (gradK.length() == 0)
gradK = null;
if (drzavaK.length() == 0)
drzavaK = null;
if (telefonK.length() == 0)
telefonK = null;
if (faxK.length() == 0)
faxK = null;
if (mailK.length() == 0)
mailK = null;
if (mobitelK.length() == 0)
mobitelK = null;
if (oibK.length() == 0)
oibK = null;
if (ugovorK.length() == 0)
ugovorK = null;
if (osobaK.length() == 0)
osobaK = null;
klijentiSearchModel.clear();
String sql = "select * from zavrsni.klijenti where naziv like '"+nazivK+"' or adresa like '"+adresaK+"' or grad like '"+gradK+"' or drzava like '"+drzavaK+"' or telefon like '"+telefonK+"' or fax like '"+faxK+"' or mail like '"+mailK+"' or mobitel like '"+mobitelK+"' or oib like '"+oibK+"' or ugovor like '"+ugovorK+"' or osoba like '"+osobaK+"' ";
Statement selectStmt = con.createStatement();
ResultSet result = selectStmt.executeQuery(sql);
while(result.next()) {
int id = result.getInt("id");
String naziv = result.getString("naziv");
String adresa = result.getString("adresa");
String grad = result.getString("grad");
int posBr = result.getInt("posBr");
String drzava = result.getString("drzava");
String telefon = result.getString("telefon");
String fax = result.getString("fax");
String mail = result.getString("mail");
String mobitel = result.getString("mobitel");
String oib = result.getString("oib");
String ugovor = result.getString("ugovor");
String osoba = result.getString("osoba");
KlijentiModelSearch klijentSearch = new KlijentiModelSearch(id, naziv, adresa, grad, posBr, drzava, telefon, fax, mail, mobitel, oib, ugovor, osoba);
klijentiSearchModel.add(klijentSearch);
}
result.close();
selectStmt.close();
}
Can i write this code shorter? I think of "if" statement?
Perhaps through a while loop?
Method that is use for search some client in database. This method work fane but this if-statement i want write shorter.
Thanks
EDIT SOLVED:
public void traziKlijenta(KlijentiFormEvent klijentiFormEvent) throws SQLException {
String nazivK = returnNullIfEmptys(klijentiFormEvent.getNaziv());
String adresaK = returnNullIfEmptys(klijentiFormEvent.getAdresa());
String gradK = returnNullIfEmptys(klijentiFormEvent.getGrad());
String drzavaK = returnNullIfEmptys(klijentiFormEvent.getDrzava());
String telefonK = returnNullIfEmptys(klijentiFormEvent.getTelefon());
String faxK = returnNullIfEmptys(klijentiFormEvent.getFax());
String mailK = returnNullIfEmptys(klijentiFormEvent.getMail());
String mobitelK = returnNullIfEmptys(klijentiFormEvent.getMobitel());
String oibK = returnNullIfEmptys(klijentiFormEvent.getOib());
String ugovorK = returnNullIfEmptys(klijentiFormEvent.getUgovor());
String osobaK = returnNullIfEmptys(klijentiFormEvent.getOsoba());
klijentiSearchModel.clear();
String sql = "select * from zavrsni.klijenti where naziv like '%"+nazivK+"%' or adresa like '%"+adresaK+"%' or grad like '%"+gradK+"%' or drzava like '%"+drzavaK+"%' or telefon like '%"+telefonK+"%' or fax like '%"+faxK+"%' or mail like '%"+mailK+"%' or mobitel like '%"+mobitelK+"%' or oib like '%"+oibK+"%' or ugovor like '%"+ugovorK+"%' or osoba like '%"+osobaK+"%' ";
Statement selectStmt = con.createStatement();
ResultSet result = selectStmt.executeQuery(sql);
while(result.next()) {
int id = result.getInt("id");
String naziv = result.getString("naziv");
String adresa = result.getString("adresa");
String grad = result.getString("grad");
int posBr = result.getInt("posBr");
String drzava = result.getString("drzava");
String telefon = result.getString("telefon");
String fax = result.getString("fax");
String mail = result.getString("mail");
String mobitel = result.getString("mobitel");
String oib = result.getString("oib");
String ugovor = result.getString("ugovor");
String osoba = result.getString("osoba");
KlijentiModelSearch klijentSearch = new KlijentiModelSearch(id, naziv, adresa, grad, posBr, drzava, telefon, fax, mail, mobitel, oib, ugovor, osoba);
klijentiSearchModel.add(klijentSearch);
}
result.close();
selectStmt.close();
}
private String returnNullIfEmptys(String value) {
if (value == null || value.length() == 0) {
return null;
}
return value;
}
With your actual code, #khelwood proposition in your comment question is the best approach.
Other solutions have overhead and change your design without bringing a added value .
public static String returnNullIfEmpty(String value){
if (value == null || value.length() == 0){
return null;
}
return value;
}
Then you can call it in this way :
nazivK = returnNullIfEmpty(nazivK);
adresaK= returnNullIfEmpty(adresaK);
EDIT
With the edit of your question, you could include processing as the time where you retrieve the value from the klijentiFormEvent object :
String nazivK = returnNullIfEmpty(klijentiFormEvent.getNaziv());
String adresaK = returnNullIfEmpty(klijentiFormEvent.getAdresa());
...
You simply have to put your arrays/lists ... whatever those things are ... into another array or list.
Then you iterate that array/list.
Done.
And hint: your naming could be improved dramatically. Your names should indicate what the "thing" behind the variable actually is.
Also you can use Map<String, List<?>> to store your lists/arrays/strings. for example with List:
Map<String, List<?>> map = new HashMap<>();
map.put("nazivK", new ArrayList<>());
map.put("adresaK", new ArrayList<>());
//.....
//replace all lists with null
map.replaceAll((s, list) -> list.isEmpty() ? null : list);
//or just remove it
for(Iterator<Map.Entry<String, List<?>>> it = map.entrySet().iterator(); it.hasNext(); ) {
Map.Entry<String, List<?>> entry = it.next();
if(entry.getValue().isEmpty()) {
it.remove();
}
}
As it was suggested by GhostCat, put your values into array/list.
You can do for example something like this (I suppose those values are Strings):
/* Order in array nazivK, adresaK, gradK, drzavaK, telefonK,
faxK, mailK, mobitelK, oibK, ugovorK, osobaK */
String values[] = new String[11];
for (String val: values) {
if (val == null || val.length() == 0) {
val = null;
}
}

java split string into string array produce first value wrong

Input string:
-;Lokacija;-;Pozicija;Grad;-;-;
Code:
public static ArrayList<String> sortList = new ArrayList<String>();
//Load
String Row = new String("-;Lokacija;-;Pozicija;Grad;-;-;");
String[] RowAsList;
RowAsList = Row.split(";");
sortList.add( RowAsList[0] );
// Check
StringBuffer minus = new StringBuffer( "-");
String itm = sortList.get(0);
if( !itm.contentEquals( minus ) )
// not minus
else
.....
Problem: this code says there is no minus on first item (0), subsequent minuses are recognized correctly.
Anyone has any ideas as to why ?
Thanks,
Kajko
Remove the static modifier before the sortList member:
public List<String> sortList = new ArrayList<String>();
Thats what you want
public class Test
{
public static ArrayList<String> sortList = new ArrayList<String>();
public static void main(String a[])
{
//Load
String Row = new String("-;Lokacija;-;Pozicija;Grad;-;-;");
String[] RowAsList;
RowAsList = Row.split(";");
for(int i=0;i<RowAsList.length-1;i++) {
sortList.add(RowAsList[i]);
}
System.out.println(sortList);
// Check
StringBuffer minus = new StringBuffer("-");
String itm = sortList.get(0);
if( itm.contentEquals( minus ) )
System.out.println(sortList.get(0));
// not minus
else
System.out.println("not found...");
}
}
Try :
String Row = new String("-;Lokacija;-;Pozicija;Grad;-;-;");
ArrayList<String> sortList = new ArrayList<String>();
String[] RowAsList= Row .split(";");
sortList.add( RowAsList[0]);
StringBuffer minus = new StringBuffer( "-");
String itm = sortList.get(0);
if( itm.equals( minus.toString())){
System.out.println("Get Here" + itm);
}
else{
System.out.println("Not Here"+ itm);
}

Parsing an array to String Tokeniser

I have an object declared in this format
StringTokenizer star = new StringTokenizer(st , SEPARATOR); //separator is '/'
Session s1 = new Session(int SessionID, String [] cineName, String[] cineType, String movieName, String date, int time);
int SessionID = Integer.parseInt(star.nextToken().trim()); //for integer
String movieName = star.nextToken().trim(); //for string
String [] cineName = ? //how about string array?
Thus, I wish to ask how I can implement the parsing of a cineName array.
You can store the tokens of a String which delimits tokens with "/" in cineArray as follows:
int tokens = star.countTokens();
for (int i=0;i<tokens;i++)
{
cineName[i] = star.nextToken().trim();
}
String [] cineName = star.nextToken().trim().split(CINE_NAME_ARRAY_SEPARATOR);

Insert array data into database using Java

I have problem with this code..I want to extract data from flat file and store it into database. flat file format is like this:-
DT|00000001|TMDWH|UNIFI|00380520160|MAH SIEW YIN|11 |JALAN PP 2/8|TAMAN PUTRA PRIMA|PUCHONG|SELANGOR|47100|MALAYSIA|801110-14-5498||||||VOBB||A||11|JALAN PP 2/8|||TAMAN PUTRA PRIMA
DT|00000002|TMDWH|UNIFI|00322012091|JUNITA BINTI JAMAL|6 10 KONDOMINIUM FAJARIA|JALAN PANTAI BARU|KUALA LUMPUR|KUALA LUMPUR|WILAYAH PERSEKUTUAN|59200|MALAYSIA|800129-09-5078||||||VOBB||A|||JALAN PANTAI BARU|6|KONDOMINIUM FAJARIA|KUALA LUMPUR
Code:
public void massageData(String tmp) {
String RecordType = "";
String RecordNumber = "";
String sourceSystemId = "";
String targetSystemId = "";
String TelNo = "";
String Name = "";
String Addr1 = "";
String Addr2 = "";
String Addr3 = "";
String TownCity = "";
String State = "";
String PostalCd = "";
String Country = "";
String NewICNo = "";
String OldICNo = "";
String PassportNo = "";
String BRN = "";
String Latitude = "";
String Longitude = "";
String ServiceType = "";
String IndicatorType = "";
//add
String CreateDate = "";
String Filler = "";
String CRNL = "";
String HouseNo = "";
String LotNo = "";
String StreetName = "";
String AptNo = "";
String BuildingName = "";
//add
String LowID = "";
String HighID = "";
String SectionName = "";
tmp = tmp.replace("\""," "); // remove " with blank
tmp = tmp.replace("\'","\'\'");
String[] recArray = tmp.split("\\|");
RecordType = recArray[1].trim();
RecordNumber = recArray[2].trim();
sourceSystemId = recArray[3].trim();
targetSystemId = recArray[4].trim();
TelNo = recArray[5].trim();
Name = recArray[6].trim();
Addr1 = recArray[7].trim();
Addr2 = recArray[8].trim();
Addr3 = recArray[9].trim();
TownCity = recArray[10].trim();
State = recArray[11].trim();
PostalCd = recArray[12].trim();
Country = recArray[13].trim();
NewICNo = recArray[14].trim();
OldICNo = recArray[15].trim();
PassportNo = recArray[16].trim();
BRN = recArray[17].trim();
Latitude = recArray[18].trim();
Longitude = recArray[19].trim();
ServiceType = recArray[20].trim();
IndicatorType = recArray[21].trim();
//add
CreateDate = recArray[22].trim();
Filler = recArray[23].trim();
CRNL = recArray[24].trim();
//
HouseNo = recArray[25].trim();
LotNo = recArray[26].trim();
StreetName = recArray[27].trim();
AptNo = recArray[28].trim();
BuildingName = recArray[29].trim();
//add
LowID = recArray[30].trim();
HighID = recArray[31].trim();
//
SectionName = recArray[32].trim();
Connection conn = null;
ResultSet rs = null;
PreparedStatement stmt = null;
logger.info("masuk messageData");
// get actual telephone number
String actualMSISDN = parseMSISDN(TelNo);
String [] aNo = getAreaCode(actualMSISDN).split("\\|");
String iCtr = getiCtr(actualMSISDN);
iCtr = recArray[0].trim();
String stateCode = lookupStateCode(State);
String sQuery = "insert into DATA_999 (ID,RecordType,RecordNumber,SourceSystemApplicationId,TargetApplicationId,TelNo,Name,HouseNo,StreetName,AppartmentSuite,TownCity,State,PostalCode,Country,NewIC,OldIC,PassportNo,BRN,LatitudeDecimal,LongitudeDecimal,ServiceType,IndicatorType,CreateDate,Filler,Cr_Nl,HouseNo_New,LotNo_New,StreetName_New,AptNo_New,BuildingName_New,LowIDRange,HighIDRange,SectionName) values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
try {
conn = ds.getConnection();
// insert post process data to data_999 table
logger.info("start Query");
stmt = conn.prepareStatement(sQuery);
stmt.setString(0,iCtr);
stmt.setString(1,RecordType);
stmt.setString(2,RecordNumber);
stmt.setString(3,sourceSystemId);
stmt.setString(4,targetSystemId);
stmt.setString(5,TelNo);
stmt.setString(6,Name);
stmt.setString(7,Addr1);
stmt.setString(8,Addr2);
stmt.setString(9,Addr3);
stmt.setString(10,TownCity);
stmt.setString(11,State);
stmt.setString(12,PostalCd);
stmt.setString(13,Country);
stmt.setString(14,NewICNo);
stmt.setString(15,OldICNo);
stmt.setString(16,PassportNo);
stmt.setString(17,BRN);
stmt.setString(18,Latitude);
stmt.setString(19,Longitude);
stmt.setString(20,ServiceType);
stmt.setString(21,IndicatorType);
//add
stmt.setString(22,CreateDate);
stmt.setString(23,Filler);
stmt.setString(24,CRNL);
//
stmt.setString(25,HouseNo);
stmt.setString(26,LotNo);
stmt.setString(27,StreetName);
stmt.setString(28,AptNo);
stmt.setString(29,BuildingName);
//add
stmt.setString(30,LowID);
stmt.setString(31,HighID);
//
stmt.setString(32,SectionName);
//stmt = conn.prepareStatement(sQuery);
int dbStat = stmt.executeUpdate();
conn.close();
} catch (SQLException s){
logger.error(s.getMessage());
}
finally {
try {if (stmt != null) stmt.close();} catch (SQLException e) {}
try {if (conn != null) conn.close();} catch (SQLException e) {}
}
I really2 hope anyone here can help me.
Current result:
No data store into database, the code was successfully compiled!
Expected result
All the data will store into database DATA_999.
The SQL API, unlike every other java API I can think of which is zero-based, is one-based - meaning it starts counting from one. Your code is trying to set the zeroth field, which should be exploding.
As a side note, because there's hardy any special processing for each field, you could replace all that code with just a few lines by simply iterating over the fields and setting the stmt params - ie don't use variables for each field:
// fyi, the regex of this split trims automatically
String[] fields = tmp.replace("\""," ").replace("\'","\'\'").trim().split("\\s*\\|\\s*");
// Do any special field processing (most need none)
field[0] = getiCtr(parseMSISDN(field[5])); // for example - just do what you need
// Now set all the SQL params
int col = 0;
for (String field : fields) {
stmt.setString(++col, field); // Note: SQL API is 1-based (not zero-based)
}
Indexes for prepared statements are 1-based:
Change stmt.setString(0,iCtr); to stmt.setString(1,iCtr);. (And adjust the following)
And please post the exception you get. It will give us more hints what might went wrong
EDIT:
Are all fields in your table of type varchar? There are values in your lines that might be modeled as ints.

Categories