I am splitting the XML elements using String.split() method. The format of the XML elements are mentioned below:
start:23 | stop:43 | name:abc def
After splitting the strings, I'm trying to trim and assign like the following:
String[] parts = oneLine.split("\\s*\\|\\s*"); // splits into 3 strings
for (int x = 0; x < parts.length; x++) {
String tmp = parts[0];
if (tmp.startsWith("start:")) {
tmp = tmp.substring("start:".length());
try {
this.begin = Integer.parseInt(tmp);
}
catch (NumberFormatException nfe) {
nfe.printStackTrace();
}
}
else {
System.err.println("Wrong format");
}
String tmp1 = parts[1];
if ( tmp1.startsWith("stop:")) {
tmp1 = tmp1.substring("stop:".length());
try {
this.end = Integer.parseInt(tmp1);
}
catch ( NumberFormatException nfe ) {
nfe.printStackTrace();
}
}
else {
System.err.println("Wrong format"+tmp1);
}
Strint tmp2 = parts[2];
if ( tmp2.startsWith("name:")) {
tmp2 = tmp2.substring("name:".length());
try {
this.name = tmp2;
}
catch ( NumberFormatException nfe ) {
nfe.printStackTrace();
}
}
else {
System.err.println("Wrong format"+tmp2);
}
This returns an error Wrong format. Is this the problem with assignments String tmp1 = parts[0]?
Answer to my question.
String[] parts= oneLine.split("\\s*\\|\\s*");
//System.out.println(parts[0]);
String tmp=parts[0].substring("start:".length());
this.begin=Integer.parseInt(tmp);
String tmp1=parts[1].substring("stop:".length());
this.end=Integer.parseInt(tmp1);
String tmp2=parts[2].substring("name:".length());
this.uri=tmp2;
Above code snippet solves my problem
Related
I have one JSON file and having some issue in it. When parsing the json file I will get the ParserException. From parser exception I have extracted the position where the is problem.
Now I want the line number of the that particular position in file.
JSONObject json;
try {
if (!file.exists()) {
throw new ExceptionDoesNotExist(file);
}
scanner = new Scanner(file, Charset.defaultCharset().toString());
String data = scanner.useDelimiter("\\Z").next();
json = (JSONObject) new JSONParser().parse(data);
return json;
} catch (ParseException e) {
this.log.logException(e);
int position = e.getPosition();
String reason = e.getUnexpectedObject().toString();
return new JSONObject();
}
if (!file.exists()) {
throw new ExceptionDoesNotExist(file);
}
scanner = new Scanner(file, Charset.defaultCharset().toString());
String data = scanner.useDelimiter("\\Z").next();
try {
return new JSONParser().parse(data);
} catch (ParseException e) {
String lineAndColumn = lineAndColumn(data, e, 4);
...;
return new JSONObject();
}
public static String lineAndColumn(String text, ParseException e, int tabSize) {
int position = e.getPosition();
int lineNo = 1 + (int) text.substring(0, position).codePoints()
.filter(cp -> cp == '\n')
.count();
int columnNo = 1 + text.substring(0, position).lastIndexOf('\n') + 1; // no \n okay too.
// Tabs
int cI = 0;
for (int i = 0; i < columnNo - 1; ++i) {
if (text.charAt(posion - (columnNo - 1) + i) == '\t') {
cI += tabSize;
cI %= tabSize;
} else {
++cI;
}
}
columnNo = cI + 1;
return String.format("%d:%d"), lineNo, ColumnNo);
}
I am facing a issue when fatch the value from xl after that print under the for loop scope then printed. when declare the in return statement and call the method only first cell value print. I want 8 cell value.
public String Sheet_Infor() {
ReadConfig readconfig = new ReadConfig();
String excelPath = readconfig.getExcelPath();
int Row =0;
String s = "";
try {
Row = XLUtils.getRowCount(excelPath,"Course 7");
} catch (IOException e) {
e.printStackTrace();
}
for (Row = 20; Row<28; Row++) {
try {
s = XLUtils.getCellData(excelPath,"Course 7", Row,1);
return s;
} catch (IOException e) {
e.printStackTrace();
}
//System.out.println("sss="+s);
}
return s;
}
You can use if(condition) to break/return the required value. For ex, I have a for loop interating upto 10. At value 6 I want to stop and return the value. It can be done as:
private test() {
for (int i = 10; i > 10; i++) {
if(i==5) {
return i;
}
}
}
If you want all the 8 cell values then you will have to hold those values in a list/array. You can do it as:
public List<String> Sheet_Infor() {
ReadConfig readconfig = new ReadConfig();
String excelPath = readconfig.getExcelPath();
int Row = 0;
String s = "";
try {
Row = XLUtils.getRowCount(excelPath, "Course 7");
} catch (IOException e) {
e.printStackTrace();
}
List<String> items = new ArrayList<String>();
for (Row = 20; Row < 28; Row++) {
try {
s = XLUtils.getCellData(excelPath, "Course 7", Row, 1);
items.add(s);
return s;
} catch (IOException e) {
e.printStackTrace();
}
// System.out.println("sss="+s);
}
return items;
}
I have written the following method to validate an input String and output it as an int array. The method works completely as I need it to but I would like to add some extra validation to it so that it only allows integers and commas in the input so there are no errors.
An example correct input would be:
"7,23,62,8,1130"
The method is:
public static int[] validator (String [] check) {
int [] out = new int[5];
try
{
if (0 < Integer.parseInt(check[0]) && Integer.parseInt(check[0]) < 100)
{
out[0] = Integer.parseInt(check[0]);
}
else
{
throw new InvalidMessageException();
}
}
catch (InvalidMessageException ex)
{
System.err.println("Invalid instruction message");
return null;
}
try
{
if (0 < Integer.parseInt(check[1]))
{
out[1] = Integer.parseInt(check[1]);
}
else
{
throw new InvalidMessageException();
}
}
catch (InvalidMessageException ex)
{
System.err.println("Invalid instruction message");
return null;
}
try
{
if(0 < Integer.parseInt(check[2]))
{
out[2] = Integer.parseInt(check[2]);
}
else
{
throw new InvalidMessageException();
}
}
catch (InvalidMessageException ex)
{
System.err.println("Invalid instruction message");
return null;
}
try
{
if (0 <= Integer.parseInt(check[3]) && Integer.parseInt(check[3]) < 256)
{
out[3] = Integer.parseInt(check[3]);
}
else
{
throw new InvalidMessageException();
}
}
catch (InvalidMessageException ex)
{
System.err.println("Invalid instruction message");
return null;
}
try
{
if(0 < Integer.parseInt(check[4]))
{
out[4] = Integer.parseInt(check[4]);
}
else
{
throw new InvalidMessageException();
}
}
catch (InvalidMessageException ex)
{
System.err.println("Invalid instruction message");
return null;
}
return out;
}
I have considered doing something like:
inputText = inputText.replace(".", "");
inputText = inputText.replace(":", "");
inputText = inputText.replace(";", "");
inputText = inputText.replace("\"", "");
etc... but it does not seem a particularly great solution. If anyone has a better idea, please let me know. Thanks very much for any help!
I'd say something like this should replace your method, without having read your code, just your requirements:
String input = "7,23,62,8,1130";
if (input.matches("(?:\\d+(?:,|$))+")) {
int[] result = Arrays.stream(input.split(",")).mapToInt(Integer::parseInt).toArray();
} else {
throw new InvalidMessageException("");
}
You can use a regex expression to validate your input:
[0-9]+(,[0-9]+)*,?
Check it with the String matches(regex) method as:
if (yourString.matches("[0-9]+(,[0-9]+)*,?")) {
}
This is exactly what regular expressions are for:
return inputText.matches("\\d+(,\\d+)*");
I am working on a driving licence project on j2Me wich is including Tests like quizz , well and i am having a problem after parsing the questions and moving them into choiceGroups just like that :
if (questions.length > 0) {
for (int i = 0; i < questions.length; i++) {
ChoiceGroup reponses = new ChoiceGroup("Reponses" + i, Choice.EXCLUSIVE);
reponses.append(questions[i].getReponse1(), null);
reponses.append(questions[i].getReponse2(), null);
reponses.append(questions[i].getReponse3(), null);
pass.append(questions[i].getContenu());
pass.append(reponses);
}
}
} catch (Exception e) {
System.out.println("Exception:" + e.toString());
}
disp.setCurrent(pass);
and the next step is the command who's controlling the choiceGroups to test them if they are like the true answer or not .
so i am blocked here .
if (c == valider) {
int result = 0;
for (int i = 0; i < pass.size(); i++) {
String ch = pass.get(i).getLabel();
System.out.println(ch);
}
}
I don't know how to get the choice from the choicegroup
any help
Actually, I am not sure what totally you want for:
This code will help you get selected items from choicegroup that i did long time before:
//get a selected array in choicegroup
private String[] choiceGroupSelected(ChoiceGroup cg) {
String selectedArray[] = new String[cg.size()];
int k = 0;
for (int i = 0; i < cg.size(); i++) {
if (cg.isSelected(i)) {
selectedArray[k] = cg.getString(i);
k++;
}
}
return selectedArray;
}
That function will help me get all selected items for deleting action below:
private void deleteSpecificItem() {
try {
String temp = null;
int index;
//get ChoiceGroup size
int numbers = cgTrip.size();
String selectedItems[] = choiceGroupSelected(cgTrip);
//
rs = services.RecordStoreManager.openRecordStoreByName("TripRS");
re = rs.enumerateRecords(null, null, true);
String[] tripList = new String[2];
for (int i = 0; i < numbers; i++) {
temp = selectedItems[i];
if (temp != null) {
while (re.hasNextElement()) {
try {
index = re.nextRecordId();
System.out.println("RecordID: " + index);
byte[] byteBuff = rs.getRecord(index);
String source = new String(byteBuff);
tripList = services.StringManager.getItems(source, ";", 2);
String strProcess = tripList[0] + "-" + tripList[1];
//inspect all of items in choicegroup and if they are selecting then compare with record
//If comparison is true then delete this record
if (temp.equals(strProcess)) {
System.out.println("Delete RecordID: " + index);
rs.deleteRecord(index);
re.keepUpdated(true);
break;
}
} catch (RecordStoreException ex) {
ex.printStackTrace();
}
}
}
}
try {
rs.closeRecordStore();
} catch (RecordStoreException ex) {
ex.printStackTrace();
}
rs = null;
re.destroy();
this.LoadTripItem();
} catch (RecordStoreNotOpenException ex) {
ex.printStackTrace();
}
}
I have a big String (XML Style) and I provide a text-field for capturing the words to search. All words found should be highlighted.
The problem i have is, that the words can appear multiple times in that String but only the first/or last word is highlighted.
I found out that the problem is that the selectionStart and ending is always the same.
Can u help me ?
public static void searchTextToFind(String textToFind) {
highlighter.removeAllHighlights();
String CurrentText = textPane.getText();
StringReader readtext;
BufferedReader readBuffer;
int i = 0;
int matches = 0;
readtext = new StringReader(CurrentText);
readBuffer = new BufferedReader(readtext);
String line;
try {
i = CurrentText.indexOf(textToFind);
int start = 0;
int end = 0;
Pattern p = Pattern.compile(textToFind);
while ((line = readBuffer.readLine()) != null) {
Matcher m = p.matcher(line);
// indicate all matches on the line
while (m.find()) {
matches++;
while (i >= 0) {
textPane.setSelectionStart(i);
textPane.setSelectionEnd(i + textToFind.length());
i = CurrentText.indexOf(textToFind, i + 1);
start = textPane.getSelectionStart();
end = textPane.getSelectionEnd();
try {
highlighter.addHighlight(start, end,
myHighlightPainter);
} catch (BadLocationException e) {
e.printStackTrace();
}
}
}
}
} catch (IOException e1) {
e1.printStackTrace();
}
JOptionPane.showMessageDialog(paneXML,
matches+" matches have been found", "Matched",
JOptionPane.INFORMATION_MESSAGE);
}
You have a LOT of redundant code. Here's a short and sweet solution using String.indexOf
public static void searchTextToFind(String textToFind) {
highlighter.removeAllHighlights();
textToFind = textToFind.toLowerCase(); //STRINGS ARE IMMUTABLE OBJECTS
String currentText = textPane.getText(); //UPPERCASE LOCALS ARE EVIL
currentText = currentText.toLowerCase(); //STRINGS ARE IMMUTABLE OBJECTS
int offset = 0;
for(int index = currentText.indexOf(textToFind, offset); index >= 0; index = currentText.indexOf(textToFind, offset)){
int startIndex = currentText.indexOf(textToFind, offset);
int endIndex = startIndex + textToFind.length() - 1; //this gets you the inclusive endIndex.
textPane.setSelectionStart(startIndex);
textPane.setSelectionEnd(endIndex);
offset = startIndex + 1; //begin the NEXT search at startIndex + 1 so we don't match the same string over and over again
System.out.println(startIndex);
System.out.println(endIndex);
try {
highlighter
.addHighlight(startIndex, endIndex, myHighlightPainter);
} catch (BadLocationException e) {
e.printStackTrace();
}
}
}