Java-How to optimize else if using Map collection in java - java

Below is my else if ladder.
Please tell me how to optimize else if ladder using Map
for (String p1: data) {
p1 = p1.replace("#", "");
if (p1.startsWith("Year")) {
Year = p1.substring(p1.lastIndexOf(":") + 1);
System.out.print(Year);
} else if (p1.startsWith("Department")) {
Department = p1.substring(p1.lastIndexOf(":") + 1);
System.out.print(Department);
} else if (p1.startsWith("Division")) {
Division = p1.substring(p1.lastIndexOf(":") + 1);
System.out.print(Division);
} else if (p1.startsWith("Subject Code")) {
SubjectCode = p1.substring(p1.lastIndexOf(":") + 1);
System.out.print(SubjectCode);
} else if (p1.startsWith("Teacher Code")) {
int k = p1.indexOf(" ", p1.indexOf(" ") + 1);
String res = p1.substring(0, k);
System.out.print("Characters ::" + res);
String TeacherCode1 = p1.substring(p1.lastIndexOf(":") + 1);
int m = TeacherCode1.indexOf(" ", TeacherCode1.indexOf(" ") + 1);
System.out.println(m);
TeacherCode = TeacherCode1.substring(0, m);
System.out.println("Value of p2 ::" + TeacherCode.trim());
} else if (p1.startsWith("Date")) {
Date = p1.substring(p1.lastIndexOf(":") + 1);
System.out.print(Date);
}
}
The above code is too lengthy.
I want to optimize it for better performance using Map
Now I attached Image file,that i converted into text file using OCR and I wanted to split data,to save into database like Year:THIRD ,Department: INFO. TECH ,Date:18/08/2017,Subject Code: TBGOZ like that But in Optimize code using Map.

May be following will be helpful:
for (String p1: data)
{
p1 = p1.replace("#", "");
String[] vals = p1.split(":");
int lastIndx = vals.length-1;
switch(vals[0])
{
case "Year":
Year = vals[lastIndx];
System.out.print(Year);
break;
case "Department":
Department = vals[lastIndx];
System.out.print(Department);
break;
case "Division":
Division = vals[lastIndx];
System.out.print(Division);
break;
case "Subject Code":
SubjectCode = vals[lastIndx];
System.out.print(SubjectCode);
break;
case "Date":
Date = vals[lastIndx];
System.out.print(Date);
break;
case "Teacher Code":
int k = p1.indexOf(" ", p1.indexOf(" ") + 1);
String res = p1.substring(0, k);
System.out.print("Characters ::" + res);
String TeacherCode1 = vals[lastIndx];;
int m = TeacherCode1.indexOf(" ", TeacherCode1.indexOf(" ") + 1);
System.out.println(m);
TeacherCode = TeacherCode1.substring(0, m);
System.out.println("Value of p2 ::" + TeacherCode.trim());
break;
}
}

The logic for Year, Department, Division, Subject Code and Date is the same.
So you can do the other parts first, and then else for these common bits
if (p1.startsWith("Teacher Code")) {
int k = p1.indexOf(" ", p1.indexOf(" ") + 1);
String res = p1.substring(0, k);
System.out.print("Characters ::" + res);
String TeacherCode1 = p1.substring(p1.lastIndexOf(":") + 1);
int m = TeacherCode1.indexOf(" ", TeacherCode1.indexOf(" ") + 1);
System.out.println(m);
TeacherCode = TeacherCode1.substring(0, m);
System.out.println("Value of p2 ::" + TeacherCode.trim());
} else {
String other = p1.substring(p1.lastIndexOf(":") + 1);
System.out.print(other);
}
BTW, "I want to optimize it for better performance using Map" - There will be no noticeable performance benefit.

As you may know, maps contain key value pairs. In this case, your keys will be strings like Year, Department, Division etc. I suggest you put these strings into an array, except the teacher code because that needs special handling:
String[] keys = {"Year", "Department", "Division" ...};
Now, create your map:
Map<String, String> map = new HashMap<>();
You can then loop through this array:
for (String key : keys) {
if (p1.startsWith("Teacher Code")) {
int k = p1.indexOf(" ", p1.indexOf(" ") + 1);
String res = p1.substring(0, k);
System.out.print("Characters ::" + res);
String TeacherCode1 = p1.substring(p1.lastIndexOf(":") + 1);
int m = TeacherCode1.indexOf(" ", TeacherCode1.indexOf(" ") + 1);
System.out.println(m);
map.put("Teacher Code", TeacherCode1.substring(0, m));
System.out.println("Value of p2 ::" + TeacherCode.trim());
} else if (p1.startsWith(key)) {
String value = p1.substring(p1.lastIndexOf(":") + 1);
map.put(key, value);
System.out.println(value);
}
}

If variable assignment is not important. here is how you can generate map.
Function<String, String> keyFunction = p1 -> {
return p1.substring(0, p1.indexOf(":") + 1);
};
Function<String, String> valueFunction = p1 -> {
return p1.substring(p1.lastIndexOf(":") + 1);
};
Map<String, String> map =data.stream().collect(Collectors.toMap(keyFunction, valueFunction));

Related

Barchart doesn't show my values when filtered

I don't know if I'm using the correct way of filtering a barchart, or even if my code is properly written.
But I have problem, when I open my dashboard, I have 3 charts, one of the piecharts can filter the barchart, and depending on which was selected, the barchart only shows the piechart selected, otherwise shows all.
My problem is when I filter those, I'm getting the correct filter, but I can't get the labels to appear, they just appear when I got only one, for example if I have 1Yellow, 15 Reds, its only a bar to show, but it only shows the label for the yellow one, but if yellow2 and 15 reds, it doesn't show any of them.
It should be a easy fix, I just can't see where is the error.
ArrayList<Integer> colors_to_add_type = new ArrayList<>();
ArrayList<Integer> colors_to_add_type_MINOR = new ArrayList<>();
ArrayList<Integer> colors_to_add_type_MEDIUM = new ArrayList<>();
ArrayList<Integer> colors_to_add_type_MAJOR = new ArrayList<>();
ArrayList<Integer> colors_to_add_type_OTHER = new ArrayList<>();
Iterator<String> defects_colors_keys;
defects_colors_keys = colors_type.keys();
while (defects_colors_keys.hasNext()){
String key = defects_colors_keys.next();
Log.e("COLOR_KEY", "onResponse: " + key );
int to_add = Color.parseColor(colors_type.getString(key));
int to_add_MINOR = Color.parseColor("#00FF00");
int to_add_MEDIUM = Color.parseColor("#FFFF00");
int to_add_MAJOR = Color.parseColor("#FF0000");
int to_add_OTHER = Color.parseColor("#800080");
Log.e("COLOR_NAME", "onResponse: " + colors_type.getString(key));
colors_to_add_type.add(to_add);
colors_to_add_type_MAJOR.add(to_add_MAJOR);
colors_to_add_type_MEDIUM.add(to_add_MEDIUM);
colors_to_add_type_MINOR.add(to_add_MINOR);
colors_to_add_type_OTHER.add(to_add_OTHER);
}
List<LegendEntry> legends_type = new ArrayList<>();
List<LegendEntry> legends_type_MINOR = new ArrayList<>();
List<LegendEntry> legends_type_MEDIUM = new ArrayList<>();
List<LegendEntry> legends_type_MAJOR = new ArrayList<>();
List<LegendEntry> legends_type_OTHER = new ArrayList<>();
type_of_defects = by_type.keys();
int c = 0;
if(!map_defects_by_type_count.isEmpty()){
map_defects_by_type_count.clear();
}
Log.e("DEFECTS", defects_list.toString());
Log.e("DEFECTS",String.valueOf(defects_list.size()));
while(type_of_defects.hasNext()) {
String key = type_of_defects.next();
Log.e("DEFECTS_type", key.toString());
map_defects_by_type_count.put(key, by_type.getInt(key));
map_get_defect_type.put(c, key);
LegendEntry legendEntry = new LegendEntry();
legendEntry.label = key;
legendEntry.formColor = colors_to_add_type.get(c);
legends_type.add(legendEntry);
arr_by_type.add(new BarEntry((float)c + 1, (int)by_type.getInt(key), (String)key));
c++;
for (int i = 0; i < defects_list.size(); i++){
if (defects_list.get(i).getStringProperty("defect").equals(key)){
if (defects_list.get(i).getStringProperty("criticality").equals("MAJOR")){
arr_by_type_MAJOR.add(new BarEntry((float)c +1, (int)by_type.getInt(key), (String)key));
legends_type_MAJOR.add(legendEntry);
break;
}
if (defects_list.get(i).getStringProperty("criticality").equals("MEDIUM")){
arr_by_type_MEDIUM.add(new BarEntry((float)c +1 , (int)by_type.getInt(key), (String)key));
legends_type_MEDIUM.add(legendEntry);
break;
}
if (defects_list.get(i).getStringProperty("criticality").equals("MINOR")){
arr_by_type_MINOR.add(new BarEntry((float)c +1, (int)by_type.getInt(key), (String)key));
legends_type_MINOR.add(legendEntry);
break;
}
if (defects_list.get(i).getStringProperty("criticality").equals("OTHER")){
arr_by_type_OTHER.add(new BarEntry((float)c +1, (int)by_type.getInt(key), (String)key));
legends_type_OTHER.add(legendEntry);
break;
}
}
}
}
TOTAL_DEFECTS = TOTAL_BY_CRIT;
if(TOTAL_BY_CRIT != 0){
if(MAJOR != 0){
major_percent = (float) MAJOR / TOTAL_BY_CRIT;
}
if(MEDIUM != 0){
medium_percent = (float) MEDIUM / TOTAL_BY_CRIT;
}
if(MINOR != 0){
minor_percent = (float) MINOR / TOTAL_BY_CRIT;
}
if(OTHER != 0){
other_percent = (float) OTHER / TOTAL_BY_CRIT;
}
}
TOTAL_SOURCE = TOTAL_H_M;
if(TOTAL_H_M != 0){
if(HUMAN != 0){
human_percent = (float) HUMAN / TOTAL_H_M;
}
if(MACHINE != 0){
machine_percent = (float) MACHINE / TOTAL_H_M;
}
}
arr_by_defect.add(new PieEntry(MAJOR, "MAJOR"));
arr_by_defect.add(new PieEntry(MEDIUM, "MEDIUM"));
arr_by_defect.add(new PieEntry(MINOR, "MINOR"));
arr_by_defect.add(new PieEntry(OTHER, "OTHER"));
arr_by_source.add(new PieEntry(HUMAN, "HUMAN"));
arr_by_source.add(new PieEntry(MACHINE, "MACHINE"));
dataSet_by_defect = new PieDataSet(arr_by_defect, "");
dataSet_by_source = new PieDataSet(arr_by_source, "");
dataSet_by_type = new BarDataSet(arr_by_type, "");
dataSet_by_type_MAJOR = new BarDataSet(arr_by_type_MAJOR, "");
dataSet_by_type_MEDIUM = new BarDataSet(arr_by_type_MEDIUM, "");
dataSet_by_type_MINOR = new BarDataSet(arr_by_type_MINOR, "");
dataSet_by_type_OTHER = new BarDataSet(arr_by_type_OTHER, "");
//GET THE COLORS
String colorMajor = colors.getString("MAJOR");
String colorMedium = colors.getString("MEDIUM");
String colorMinor = colors.getString("MINOR");
String colorOther = colors.getString("OTHER");
String colorHuman = human_machine_colors.getString("human");
String colorMachine = human_machine_colors.getString("machine");
final int[] sliceColors = {Color.parseColor(colorMajor), Color.parseColor(colorMedium), Color.parseColor(colorMinor), Color.parseColor(colorOther)};
ArrayList<Integer> colorsSet = new ArrayList<>();
for (int color : sliceColors){
colorsSet.add(color);
}
Log.e("COLORS_TO ADD", "MAJOR" + colorMajor);
Log.e("COLORS_TO ADD", "MEDIUM" + colorMedium);
Log.e("COLORS_TO ADD", "MINOR" + colorMinor);
Log.e("COLORS_TO ADD", "OTHER" + colorOther);
dataSet_by_defect.setColors(colorsSet);
final int[] sliceColors_hm = {Color.parseColor(colorHuman), Color.parseColor(colorMachine)};
ArrayList<Integer> colorsSet_hm = new ArrayList<>();
for (int color : sliceColors_hm){
colorsSet_hm.add(color);
}
dataSet_by_source.setColors(colorsSet_hm);
dataSet_by_type.setColors(colors_to_add_type);
dataSet_by_type_MINOR.setColors(colors_to_add_type_MINOR);
dataSet_by_type_MEDIUM.setColors(colors_to_add_type_MEDIUM);
dataSet_by_type_MAJOR.setColors(colors_to_add_type_MAJOR);
dataSet_by_type_OTHER.setColors(colors_to_add_type_OTHER);
dataSet_by_type.setAxisDependency(YAxis.AxisDependency.RIGHT);
dataSet_by_type_MINOR.setAxisDependency(YAxis.AxisDependency.RIGHT);
dataSet_by_type_MEDIUM.setAxisDependency(YAxis.AxisDependency.RIGHT);
dataSet_by_type_MAJOR.setAxisDependency(YAxis.AxisDependency.RIGHT);
dataSet_by_type_OTHER.setAxisDependency(YAxis.AxisDependency.RIGHT);
final PieData data_defect = new PieData(dataSet_by_defect);
final PieData data_source = new PieData(dataSet_by_source);
final BarData data_type = new BarData(dataSet_by_type);
final BarData data_type_MINOR = new BarData(dataSet_by_type_MINOR);
final BarData data_type_MEDIUM = new BarData(dataSet_by_type_MEDIUM);
final BarData data_type_MAJOR = new BarData(dataSet_by_type_MAJOR);
final BarData data_type_OTHER = new BarData(dataSet_by_type_OTHER);
data_type.setDrawValues(true);
data_type_MAJOR.setDrawValues(true);
data_type_MEDIUM.setDrawValues(true);
data_type_MINOR.setDrawValues(true);
data_type_OTHER.setDrawValues(true);
data_defect.setDrawValues(false);
data_source.setDrawValues(false);
//data_type.setBarWidth(.75f);
piechart_defects.setDrawHoleEnabled(true);
piechart_defects.setHoleColor(Color.TRANSPARENT);
piechart_defects.setDrawEntryLabels(false);
piechart_defects.setDrawMarkers(false);
piechart_defects.setCenterText(String.valueOf(TOTAL_DEFECTS) + " TOTAL");
piechart_defects.setCenterTextSize(10);
piechart_defects.getDescription().setEnabled(false);
Legend l_defect = piechart_defects.getLegend();
l_defect.setVerticalAlignment(Legend.LegendVerticalAlignment.TOP);
l_defect.setHorizontalAlignment(Legend.LegendHorizontalAlignment.RIGHT);
l_defect.setOrientation(Legend.LegendOrientation.VERTICAL);
l_defect.setDrawInside(false);
l_defect.setEnabled(true);
l_defect.setFormSize(4f);
l_defect.setTextColor(Color.WHITE);
l_defect.setTextSize(.5f);
piechart_source.setDrawHoleEnabled(true);
piechart_source.setDrawEntryLabels(false);
piechart_source.setHoleColor(Color.TRANSPARENT);
piechart_source.setDrawMarkers(false);
piechart_source.setCenterText(String.valueOf(TOTAL_SOURCE) + " TOTAL");
piechart_source.setCenterTextSize(10);
piechart_source.getDescription().setEnabled(false);
piechart_source.setTransparentCircleRadius(10f);
Legend l_source = piechart_source.getLegend();
l_source.setVerticalAlignment(Legend.LegendVerticalAlignment.TOP);
l_source.setHorizontalAlignment(Legend.LegendHorizontalAlignment.RIGHT);
l_source.setOrientation(Legend.LegendOrientation.VERTICAL);
l_source.setDrawInside(false);
l_source.setEnabled(true);
l_source.setFormSize(4f);
l_source.setTextColor(Color.WHITE);
l_source.setTextSize(.5f);
dataSet_by_type.setValueTextColor(Color.WHITE);
dataSet_by_type_MAJOR.setValueTextColor(Color.WHITE);
dataSet_by_type_MEDIUM.setValueTextColor(Color.WHITE);
dataSet_by_type_MINOR.setValueTextColor(Color.WHITE);
dataSet_by_type_OTHER.setValueTextColor(Color.WHITE);
dataSet_by_type.setValueTextSize(7f);
dataSet_by_type_MINOR.setValueTextSize(7f);
dataSet_by_type_MEDIUM.setValueTextSize(7f);
dataSet_by_type_MAJOR.setValueTextSize(7f);
dataSet_by_type_OTHER.setValueTextSize(7f);
data_type.setBarWidth(.5f);
data_type.setValueFormatter(new ValueFormatter() {
#Override
public String getBarLabel(BarEntry barEntry) {
int barEntryY = (int) barEntry.getY();
return (String)barEntry.getData() + " " + "(" + String.valueOf(barEntryY) + ")";
}
});
Legend l_type_MAJOR = barchart_type.getLegend();
l_type_MAJOR.setCustom(legends_type_MAJOR);
l_type_MAJOR.setWordWrapEnabled(true);
l_type_MAJOR.setDrawInside(true);
data_type_MAJOR.setValueFormatter(new ValueFormatter() {
#Override
public String getBarLabel(BarEntry barEntry) {
int barEntryY = (int) barEntry.getY();
return (String)barEntry.getData() + " " + "(" + String.valueOf(barEntryY) + ")";
}
});
data_type_MAJOR.setBarWidth(.5f);
Legend l_type_OTHER = barchart_type.getLegend();
l_type_OTHER.setCustom(legends_type_OTHER);
l_type_OTHER.setWordWrapEnabled(true);
l_type_OTHER.setDrawInside(true);
data_type_OTHER.setValueFormatter(new ValueFormatter() {
#Override
public String getBarLabel(BarEntry barEntry) {
int barEntryY = (int) barEntry.getY();
return (String)barEntry.getData() + " " + "(" + String.valueOf(barEntryY) + ")";
}
});
data_type_OTHER.setBarWidth(.5f);
Legend l_type_MINOR = barchart_type.getLegend();
l_type_MINOR.setCustom(legends_type_MINOR);
l_type_MINOR.setWordWrapEnabled(true);
l_type_MINOR.setDrawInside(true);
data_type_MINOR.setValueFormatter(new ValueFormatter() {
#Override
public String getBarLabel(BarEntry barEntry) {
int barEntryY = (int) barEntry.getY();
return (String)barEntry.getData() + " " + "(" + String.valueOf(barEntryY) + ")";
}
});
Legend l_type_MEDIUM = barchart_type.getLegend();
l_type_MEDIUM.setCustom(legends_type_MEDIUM);
l_type_MEDIUM.setWordWrapEnabled(true);
l_type_MEDIUM.setDrawInside(true);
data_type_MEDIUM.setValueFormatter(new ValueFormatter() {
#Override
public String getBarLabel(BarEntry barEntry) {
int barEntryY = (int) barEntry.getY();
return (String)barEntry.getData() + " " + "(" + String.valueOf(barEntryY) + ")";
}
});
barchart_type.setRenderer(new MyRenderer(barchart_type, barchart_type.getAnimator(), barchart_type.getViewPortHandler()));
Legend l_type = barchart_type.getLegend();
l_type.setCustom(legends_type);
l_type.setWordWrapEnabled(true);
l_type.setDrawInside(true);
piechart_defects.setData(data_defect);
piechart_defects.invalidate();
piechart_source.setData(data_source);
piechart_source.invalidate();
barchart_type.getAxisLeft().setEnabled(false);
barchart_type.setScaleEnabled(false);
barchart_type.getAxisRight().setEnabled(false);
barchart_type.getAxisRight().setDrawGridLines(false);
barchart_type.getXAxis().setDrawLabels(false);
barchart_type.getXAxis().setDrawGridLines(false);
barchart_type.getDescription().setEnabled(false);
barchart_type.getLegend().setEnabled(false);
barchart_type.setBorderColor(Color.BLACK);
barchart_type.setDrawBorders(false);
barchart_type.setData(data_type);
barchart_type.setMinimumHeight(arr_by_type.size()*250);
barchart_type.invalidate();
Log.e("INFO BAR", data_type.toString());
piechart_defects.setOnChartValueSelectedListener(new OnChartValueSelectedListener() {
#Override
public void onValueSelected(Entry e, Highlight h) {
String value = String.valueOf((int)h.getY());
String toShow = "";
if(h.getX() == 0){
toShow = " MAJOR \n" + value;
chartSelectedDefect = "MAJOR";
barchart_type.setData(data_type_MAJOR);
}else if(h.getX() == 1){
toShow = " MEDIUM \n" + value;
chartSelectedDefect = "MEDIUM";
barchart_type.setData(data_type_MEDIUM);
barchart_type.invalidate();
}else if(h.getX() == 2){
toShow = " MINOR \n" + value ;
chartSelectedDefect = "MINOR";
barchart_type.setData(data_type_MINOR);
}else if(h.getX() == 3){
toShow = " OTHER \n" + value;
chartSelectedDefect = "OTHER";
barchart_type.setData(data_type_OTHER);
How it appears when I show all:

How can I set the x-axis and y-axis in charts

How can I set the x-axis and y-axis in charts?
Here labels are displayed. But I want to display the x-axis and y-axis names(label) in the chart graph.
public class ChartUtils {
public static HashMap<String, String> getChartData(String projectName, String questionnaireName, String questionId,
String questionValue) throws Exception {
HashMap<String, String> cMap = new HashMap<String, String>();
String dailyResponseCounts = "";
String responseStringValues = "";
String responseStringValuesForTable = "";
int cumulativeCount = 0;
String questionniareSql = "Select questionnairedetails from questionnairedetails where projectname='"
+ projectName + "' and questionnairename='" + questionnaireName + "'";
String sql = " SELECT response, count(*) as count FROM surveyresponsedetails where isduplicate is null and surveydetailsid in ("
+ " select generalkey from surveydetails where questionnaireid in ("
+ " select generalkey from questionnairedetails where projectname='" + projectName
+ "' and questionnairename='" + questionnaireName + "' " + " )and question like '"
+ StringEscapeUtils.escapeSql(org.apache.commons.lang3.StringEscapeUtils.unescapeHtml4(questionValue))
+ "') " + " and response is not null and response <> '' group by response order by count asc";
// String legendString="";
String tableHTML = "";
String questionnaireJsonDB = "";
JsonArray optionsArray = new JsonArray();
boolean isMultiChoice = false;
try {
// Get the questionnaire JSON for this entry.
questionnaireJsonDB = new ConnectionFactory().getString(questionniareSql);
// Condition :1 && 2
if (!questionnaireJsonDB.equals("") && questionnaireJsonDB.contains(questionValue)) {
JsonObject questionnaireJson = (JsonObject) new JsonParser().parse(questionnaireJsonDB);
for (String key : questionnaireJson.keySet()) {
if (!key.equals("questionnaireTitle")) {
JsonObject sections = (JsonObject) questionnaireJson.get(key);
// get the questions
for (String key1 : sections.keySet()) {
if (key1.equals("questions")) {
JsonArray questions = (JsonArray) sections.get(key1);
for (int i = 0; i < questions.size(); i++) {
JsonObject indQuestions = (JsonObject) questions.get(i);
String questName = indQuestions.get("questionTitle").getAsString();
if (!questName.equals(questionValue)) {
continue;
}
// Condition 3
String qType = indQuestions.get("questionType").getAsString();
if (qType.equals("radio") || qType.equals("checkbox")) {
optionsArray = indQuestions.get("options").getAsJsonArray();
isMultiChoice = true;
}
}
}
}
}
}
} // End of condition 1 & 2
} catch (Exception e) {
System.out.println("Exception during retrieval of Questionnaire details with SQL : " + questionniareSql);
}
// Get the data values for the charts.
List<Map<String, String>> records = new ConnectionFactory().getArrayForSql(sql);
int i = 0;
final DecimalFormat df = new DecimalFormat("0.00");
float totalCount = 0;
if (records.size() > 0) { // Check if any records are returned from the DB.
tableHTML = "<TR><TH>Response</TH><TH>Count</TH></TR>";
HashMap<String, String> tableMap = new HashMap<String, String>();
for (Map<String, String> record : records) {
String countString = record.get("count");
int countPer = StringUtils.getIntFromString(countString);
totalCount = countPer + totalCount;
System.out.println("totalCount "+totalCount);
}
for (Map<String, String> record : records) {
String responseString = record.get("response");
String countString = record.get("count");
if (isMultiChoice) {
tableMap.put(responseString, countString);
} else {
tableHTML = tableHTML + "<TR id=" + questionId + "_piechart" + "_" + i + "><TD>"
+ StringEscapeUtils.escapeJava(responseString) + "</TD><TD>" + countString + "</TD></TR>";
// legendString=legendString+"<span class='dot' style='background-color:"+
// customColors[i % customColors.length]+"'></span><span
// style='margin-left:10px;margin-left:3px;'>"+ responseString +"</span>";
i++;
int count = StringUtils.getIntFromString(countString);
cumulativeCount = cumulativeCount + count;
//dailyResponseCounts = dailyResponseCounts + "" + count + ",";
if(count!=0) {
String per = df.format((count/totalCount)*100);
System.out.println(totalCount);
dailyResponseCounts = dailyResponseCounts + "" + per + ",";
System.out.println(dailyResponseCounts);
}
String responseStringVal = "\"" + StringEscapeUtils.escapeJava(responseString) + "\"";
responseStringValuesForTable = responseStringValuesForTable + responseStringVal + ",";
// String [] responseStringArray = responseString.split(" ");
if (responseString.length() > 15) {
responseStringVal = "\"" + StringEscapeUtils.escapeJava(responseString.substring(0, 14))
+ "...\"";
} else {
responseStringVal = "\"" + StringEscapeUtils.escapeJava(responseString) + "\"";
}
responseStringValues = responseStringValues + "" + responseStringVal + ",";
}
}
if (isMultiChoice) {
for (int s = 0; s < optionsArray.size(); s++) {
JsonObject indOptions = (JsonObject) optionsArray.get(s);
String optionValue = indOptions.get("value").getAsString();
String optionValue1 = optionValue;
for (char c : optionValue.toCharArray()) {
if (c > 127) {
int sIndex = optionValue.indexOf(c);
// System.out.println(sIndex);
String replaced = optionValue.substring(sIndex);
optionValue1 = optionValue.replace(replaced, "");
// System.out.println(optionValue1);
break;
}
}
tableHTML = tableHTML + "<TR id=" + questionId + "_piechart" + "_" + s + "><TD>" + optionValue1
+ "</TD><TD>" + ObjectUtils.defaultIfNull(tableMap.get(optionValue), "0") + "</TD></TR>";
int count = StringUtils
.getIntFromString((String) ObjectUtils.defaultIfNull(tableMap.get(optionValue), "0"));
cumulativeCount = cumulativeCount + count;
//dailyResponseCounts = dailyResponseCounts + "" + count + ",";
if(count!=0) {
String per = df.format((count/totalCount)*100);
System.out.println(totalCount);
dailyResponseCounts = dailyResponseCounts + "" + per + ",";
System.out.println(dailyResponseCounts);
}
String responseStringVal = "\"" + optionValue1 + "\"";
responseStringValuesForTable = responseStringValuesForTable + responseStringVal + ",";
// String [] responseStringArray = optionValue.split(" ");
if (optionValue1.length() > 15) {
// if (responseStringArray.length > 1) {
responseStringVal = "\"" + optionValue1.substring(0, 14) + "...\"";
} else {
responseStringVal = "\"" + optionValue1 + "\"";
}
responseStringValues = responseStringValues + "" + responseStringVal + ",";
// legendString=legendString+"<span class='dot' style='background-color:"+
// customColors[i % customColors.length]+"'></span><span
// style='margin-left:10px;margin-left:3px;'>"+ optionValue +"</span>";
i++;
}
}
} else {
// No records
}
cMap.put("responseStringValues", responseStringValues);
cMap.put("dailyResponseCounts", dailyResponseCounts);
cMap.put("responseStringValuesForTable", responseStringValuesForTable);
cMap.put("tableHTML", tableHTML);
return cMap;
}
public static String getChartHTMLString(String projectName, String questionnaireName, String questionId,
String questionValue, String chartType) throws Exception {
String retVal = "";
String dailyResponseCounts = "[";
String responseStringValues = "[";
String responseStringValuesForTable = "[";
String questionnaireJsonDB = "";
JsonArray optionsArray = new JsonArray();
String sql = "Select questionnairedetails from questionnairedetails where projectname='" + projectName
+ "' and questionnairename='" + questionnaireName + "'";
// Get the questionnaire JSON for this entry.
questionnaireJsonDB = new ConnectionFactory().getString(sql);
HashMap<String, String> dataValues = getChartData(projectName, questionnaireName, questionId, questionValue);
if (!StringUtils.trimEndingComma(dataValues.get("dailyResponseCounts")).equals("")) {
dailyResponseCounts = dailyResponseCounts
+ StringUtils.trimEndingComma(dataValues.get("dailyResponseCounts")) + "]";
responseStringValues = responseStringValues
+ StringUtils.trimEndingComma(dataValues.get("responseStringValues")) + "]";
responseStringValuesForTable = responseStringValuesForTable
+ StringUtils.trimEndingComma(dataValues.get("responseStringValuesForTable")) + "]";
// Constant strings across chart types.
String cToolbar = "toolbar: {show: true,offsetX: 0,offsetY: 0,tools: { download: true,selection: true,zoom: true,zoomin: true,zoomout: true, pan: true,customIcons: []}},";
String cFill = "fill: {colors: customColors},";
String cColors = "colors: customColors,";
String cLegend = "legend: {show: true,offsetY: -5,position: 'right',height:'100%'}";
// Only for Pie charts, the series and xaxis fields vary. Hence check and
// continue
if (chartType.equals("pie")) {
retVal = "\n" + "<script> var " + questionId + "_options = {" + " series: "
+ dailyResponseCounts + "," + " chart: { width: 480,height: 550,"
+ " type: '" + chartType + "'," + " data: "
+ dailyResponseCounts + "," + cToolbar +
" events: {"
+ " dataPointMouseEnter: function(event, chartContext, config) {"
+ " highlightRowfunc(chartContext.el.id, config.dataPointIndex,1);"
+ " },"
+ " dataPointMouseLeave: function(event,chartContext,config){"
+ " highlightRowfunc(chartContext.el.id, config.dataPointIndex,0);"
+ " }" + " }" + " }," + cColors
+ " labels: " + responseStringValues + "," + cLegend + " };";
} else {
retVal = "\n" + "<script> var " + questionId + "_options = {"
+ " series:[{ name: 'Count'," + " type: '" + chartType
+ "'," + " data:" + dailyResponseCounts + "" + " }],"
+ " chart: { width: 480,height: 550," + " type: '"
+ chartType + "'," + " data: " + dailyResponseCounts + ","
+ " xaxis: {categories:" + responseStringValues + ",}, " + cToolbar
+ " events: {"
+ " dataPointMouseEnter: function(event, chartContext, config) {"
+ " highlightRowfunc(chartContext.el.id, config.dataPointIndex,1);"
+ " },"
+ " dataPointMouseLeave: function(event,chartContext,config){"
+ " highlightRowfunc(chartContext.el.id, config.dataPointIndex,0);"
+ " }" + " }" + " }," + cFill
+ cColors + " tooltip: {intersect: true,shared: false}, markers: {size: 4},"
+ " labels: " + responseStringValues + "," + cLegend + " };";
}
// Render the chart
retVal = retVal + "var " + questionId + "_chart = new ApexCharts(document.querySelector(\"#" + questionId
+ "_piechart\")," + questionId + "_options);" + questionId + "_chart.render();";
// Render the table content
retVal = retVal + " document.getElementById('table_" + questionId + "').innerHTML=\""
+ dataValues.get("tableHTML") + "\"\n";
// Render the Legend
// if (chartType.equals("pie")) {
// retVal = retVal + "document.getElementById('legend_" + questionId +
// "').innerHTML=\""+ legendString+"\"\n";
// }
retVal = retVal + "" + "" + "" + "</script>";
// retVal = retVal + legendString;
} else {// Return No records Found
retVal = "<script> document.getElementById('table_" + questionId
+ "').innerHTML='<TR><TH>No Records Found</TH></TR>'\n" + "document.getElementById('legend_"
+ questionId + "').innerHTML=\"\"\n </script>";
}
return retVal;
}
public static String getCrossTabChartHTMLString(String projectName, String questionnaireName, String questionId,
String questionValue, String crossTabQuestionValue, boolean stackedStyle) throws Exception {
String retVal = "";
String sql = " SELECT A.surveydetailsid as id, A.response as question1, B.response as question2, count(*) as count FROM surveyresponsedetails "
+ " as A Right Join surveyresponsedetails As B on A.surveydetailsid = B.surveydetailsid"
+ " where A.isduplicate is null and A.surveydetailsid in ("
+ " select generalkey from surveydetails where questionnaireid in ("
+ " select generalkey from questionnairedetails where projectname='" + projectName
+ "' and questionnairename='" + questionnaireName + "')" + " ) and A.question like '"
+ StringEscapeUtils.escapeSql(org.apache.commons.lang3.StringEscapeUtils.unescapeHtml4(questionValue))
+ "'" + " and B.question like '"
+ StringEscapeUtils.escapeSql(
org.apache.commons.lang3.StringEscapeUtils.unescapeHtml4(crossTabQuestionValue))
+ "'"
+ " and A.response is not null and A.response <> '' group by A.response, B.response order by A.response asc;";
String legendString = "";
String tableHTML = "";
// Constant Strings of the Chart Settings
String chartPart1 = "chart: { width:800, type: 'bar',stacked: true,";
String chartPart2 = "stackType: '100%',";
String chartPart3 = "toolbar: { show: true }, },";
String chart = "";
// If the stackedStyle is set to true, then display the chart with percentages.
// else with absolute numbers.
if (stackedStyle) {
chart = chartPart1 + chartPart2 + chartPart3;
} else {
chart = chartPart1 + chartPart2 + chartPart3;
}
String responsive = "responsive: [{ breakpoint: 480, options: { legend: { position: 'bottom', offsetX: -10, offsetY: 0}}}],";
String plotOptions = "plotOptions: {bar: {borderRadius: 8,horizontal: false, },},";
String legendNFill = "legend: {position: 'bottom',offsetX: 40},fill: {opacity: 1} ";
String xaxis = "xaxis: {categories:[";
// Create the series String. This is provide the data for the chart.
String series = "[";
List<Map<String, String>> recordsa = new ConnectionFactory().getArrayForSqlForCrossTab(sql);
System.out.println(recordsa);
if (recordsa.size() > 0) { // Check if any records are returned from the DB.
tableHTML = "<TR><TH>" + questionValue + "</TH><TH>" + crossTabQuestionValue + "</TH><TH>Count</TH></TR>";
// Get the unique options for Question1 and Question2
List<String> listQuestion1 = new ArrayList<String>(); // question1 containing duplicates options
List<String> listQuestion2 = new ArrayList<String>(); // question2 containing duplicates options
List<String> listQuestion3 = new ArrayList<String>(); // question3 containing duplicates options for legends
List<String> listQuestion4 = new ArrayList<String>(); // question4 containing duplicates options for legends
for (Map<String, String> record : recordsa) {
String question1Response = StringEscapeUtils.escapeJava(record.get("question1"));
String question1Response1 = record.get("question1");
for(char c: question1Response1.toCharArray()) {
if(c > 127) {
int sIndex = question1Response1.indexOf(c);
//System.out.println(sIndex);
String replaced = question1Response1.substring(sIndex);
question1Response1 = question1Response1.replace(replaced, "");
System.out.println(question1Response1);
break;
}
}
String question2Response = StringEscapeUtils.escapeJava(record.get("question2"));
String question2Response1 = record.get("question2");
System.out.println(question2Response1);
for(char c: question2Response1.toCharArray()) {
if(c > 127) {
int sIndex = question2Response1.indexOf(c);
System.out.println(sIndex);
String replaced = question2Response1.substring(sIndex);
question2Response1 = question2Response1.replace(replaced, "");
System.out.println(question2Response1);
break;
}
}
listQuestion1.add(question1Response);
//System.out.println(listQuestion1);
listQuestion2.add(question2Response);
listQuestion3.add(question1Response1);
listQuestion4.add(question2Response1);
tableHTML = tableHTML + "<TR><TD>" + question1Response1 + "</TD><TD>" + question2Response1 + "</TD><TD>"
+ record.get("count") + "</TD></TR>";
}
Set<String> setQuestion1 = new HashSet<String>(listQuestion1);
Set<String> setQuestion2 = new HashSet<String>(listQuestion2);
listQuestion1.clear();
listQuestion1.addAll(setQuestion1);
for (String qString : setQuestion2) {
// Initialize the temporary series count list.
List<String> seriesCount = new ArrayList<String>(listQuestion1.size());
for (int y = 0; y < listQuestion1.size(); y++) {
seriesCount.add("");
}
series = series + "{name: '" + qString + "', data: ";
for (Map<String, String> record : recordsa) {
String countString = record.get("count");
String questionString = StringEscapeUtils.escapeJava(record.get("question1"));
String crossTabquestionString = StringEscapeUtils.escapeJava(record.get("question2"));
if (qString.equals(crossTabquestionString)) {
seriesCount.set(listQuestion1.indexOf(questionString), countString);
}
}
for (int t = 0; t < listQuestion1.size(); t++) {
if (seriesCount.get(t) == null || seriesCount.get(t).equals("")) {
seriesCount.set(t, "0");
}
}
series = series + seriesCount.toString() + "},";
}
series = StringUtils.trimEndingComma(series) + "]";
String xAxisLegend = "";
for (int t = 0; t < listQuestion1.size(); t++) {
xAxisLegend = xAxisLegend + "'" + listQuestion1.get(t) + "',";
}
xaxis = xaxis + StringUtils.trimEndingComma(xAxisLegend) + "]},";
// return only stacked Bar graph
retVal = "\n" + "<script> var " + questionId + "_options = {" + " series: " + series + ","
+ chart + responsive + plotOptions + xaxis + legendNFill + " }; ";
// Render the chart
retVal = retVal + "var " + questionId + "_chart = new ApexCharts(document.querySelector(\"#" + questionId
+ "_piechart\")," + questionId + "_options);" + questionId + "_chart.render();";
// Render the table content
retVal = retVal + " document.getElementById('table_" + questionId + "').innerHTML=\"" + tableHTML + "\"\n";
// Render the Legend
retVal = retVal + "document.getElementById('legend_" + questionId + "').innerHTML=\"" + legendString
+ "\"\n";
retVal = retVal + "" + "" + "" + "</script>";
// retVal = retVal + legendString;
} else {// Return No records Found
retVal = "<script> document.getElementById('table_" + questionId
+ "').innerHTML='<TR><TH>No Records Found</TH></TR>'\n" + "document.getElementById('legend_"
+ questionId + "').innerHTML=\"\"\n </script>";
}
return retVal;
}
}

My "for loop" on java only return the result on the first row of jtable and repeat it for the rest number of row

So I have some issue on my for loop. It only work on the first row of jtable and printed the same result to the whole rows. here's my code:
try {
int row = tblHasil.getRowCount();
for (int i = 0; i < row; i++) {
String tempA = (String) tblHasil.getModel().getValueAt(i, 3);
String tempB = (String) tblHasil.getModel().getValueAt(i, 4);
String tempC = (String) tblHasil.getModel().getValueAt(i, 5);
double a = Double.parseDouble(tempA);
double b = Double.parseDouble(tempB);
double c = Double.parseDouble(tempC);
VNilaiRataRata.setNilaiRataRata(a);
VTanggungan.setTanggungan(b);
VPenghasilan.setPenghasilan(c);
Rules.hitung_u();
Rules.hitung_z();
DecimalFormat df = new DecimalFormat("#########.###");
double hasildef = Double.parseDouble(df.format(Rules.defuzzifikasi()));
VKeterangan.setKeterangan(hasildef);
double keterangan = VKeterangan.getKeterangan();
double tidakLolos = VKeterangan.tidaklolos();
double cadangan = VKeterangan.cadangan();
double lolos = VKeterangan.lolos();
String desc;
if (lolos > cadangan && lolos > tidakLolos) {
desc = "Lolos";
tblHasil.setValueAt(desc, i, 6);
} else if (cadangan > tidakLolos && cadangan > lolos) {
desc = "Cadangan";
tblHasil.setValueAt(desc, i, 6);
} else {
desc = "Tidak Lolos";
tblHasil.setValueAt(desc, i, 6);
}
System.out.println("Nama : " + tblHasil.getModel().getValueAt(i, 1));
System.out.println("Hasil Fuzzi : " + hasildef);
System.out.println("Keterangan Value : " + keterangan);
System.out.println("Keterangan Tidak Lolos : " + tidakLolos);
System.out.println("Keterangan Cadangan : " + cadangan);
System.out.println("Keterangan Lolos : " + lolos);
System.out.println("Nilai Rata2 : " + VNilaiRataRata.getNilaiRataRata());
System.out.println("Tangungan : " + VTanggungan.getTanggungan());
System.out.println("Penghasilan : " + VPenghasilan.getPenghasilan());
System.out.println("Keterangan : " + desc);
System.out.println("================================");
System.out.println();
Connection cn = DriverManager.getConnection("jdbc:mysql://localhost/db_siswa", "root", "");
int nis = Integer.parseInt(tblHasil.getModel().getValueAt(i, 0).toString());
String sql = "UPDATE nilaisiswa SET hasil='" + desc + "' WHERE nis = '" + nis + "'";
cn.createStatement().executeUpdate(sql);
}
} catch (Exception e) {
e.printStackTrace();
java.util.logging.Logger.getLogger(Proses.class.getName()).log(Level.SEVERE, null, e);
}
And here's the result (marked with red circle) :
i don't know how to use this thing

Check last element of hash map

I want to use a function for the update operation. So to create SQL query I must make sure the last element does not get coma(,)
I tried this
public Boolean updateSingleClient(Map map, String id) {
String updateSet = "";
int count = 0;
for (Object key : map.keySet()) {
String value = (String) map.get(key);
System.out.println("Count is " + count);
count = count + 1;
if (count == map.size()) {
updateSet = updateSet + key + "='" + value + "'";
} else {
updateSet = updateSet + key + "='" + value + "',";
}
}
System.out.println(updateSet);
return false;
}
Is there any way to check if this is the last element of HashMap?
Because this code is not working fine for me.
The last element in the iteration will be at map.size() - 1, not at map.size().
But note you can save a lot of this boilerplate code by streaming the map in to Collectors.joining:
String result =
map.entrySet()
.stream()
.map(e -> e.getKey() + " = '" + e.getValue() + "'"
.collect(Collectors.joining(","));
You can use a StringBuilder:
Append elments to StringBuilder
Remove last ,
Sample code:
public Boolean updateSingleClient(Map map, String id) {
StringBuilder updateSet = new StringBuilder();
for (Object key : map.keySet()) {
String value = (String) map.get(key);
updateSet.append(key + "='" + value + "',");
}
updateSet.deleteCharAt(updateSet.lastIndexOf(","));
System.out.println(updateSet);
return false;
}

Splitting String based on this six characters 0102**

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]);

Categories