Java : how to get the expression through the jcombo list - java

How do i create the one line expression using Java swing, link image picture. the every minute, every day,every month, every weekday and every hour need to convert it to "*" and also all the combo box contain the list of number list number link and weekday contain the click the picture
what i want is, if the user select "Every Minute" , "Every day","month = 2", "Weekday = monday", "hour= 3"
note of weekday JCombo : sunday = 0 , monday = 1, tuesday = 2 .....
the output will print as : * * 2 1 3
thanks alot.
i already tried this , my beginning code but cant do much :
String sjcb_EM = jcb_EM.getSelectedItem().toString();
String sjcb_EH = jcb_EH.getSelectedItem().toString();
String sjcb_ED = jcb_ED.getSelectedItem().toString();
String sjcb_EEM = jcb_EEM.getSelectedItem().toString();
String sjcb_EW = jcb_EW.getSelectedItem().toString();
String vb_1 = sjcb_EM + " " + sjcb_EH + " " + sjcb_ED + " " + sjcb_EEM + " " + sjcb_EW;
System.out.println(vb_1);
now i stuck, how to make the expression that i wanted.

Start by building a class which can hold both the display value and the query value...
public class WorkoutUnit {
private String displayValue;
private String queryValue;
public WorkoutUnit(String displayValue, String queryValue) {
this.displayValue = displayValue;
this.queryValue = queryValue;
}
public String getDisplayValue() {
return displayValue;
}
public String getQueryValue() {
return queryValue;
}
#Override
public String toString() {
return displayValue;
}
}
Build a ComboBoxModel using these values...
DefaultComboBoxModel<WorkoutUnit> model = new DefaultComboBoxModel<>();
model.addElement(new WorkoutUnit("Every Minute", "*"));
for (int index = 10; index < 61; index += 10) {
model.addElement(new WorkoutUnit(Integer.toString(index), Integer.toString(index)));
}
JComboBox<WorkoutUnit> cb = new JComboBox(model);
When needed, get the selected item from the combo box and get its query value...
WorkoutUnit unit = (WorkoutUnit)cb.getSelectedItem();
System.out.println("Query = " + unit.getQueryValue());
In this example, I've used toString to provide the display value to the JComboBox, this is not my preferred solution, I'd prefer to use a ListCellRenderer as demonstrated here
Oh, and because it looks like you're heading down a database query route, you should also have a look at Using Prepared Statements

Related

How to search a CSV file based on an input field?

I am able to access only few number of lines (41 lines to be proper).after that I am unable to read.
import java.io.File;
import java.util.Scanner;
public class FileReader {
public static void main(String[] args) {
String filePath = "qwe.csv";
System.out.println("Enter the City name to be Searched\n");
Scanner in = new Scanner(System.in);
String searchTerm = in.nextLine();
readRecord(filePath, searchTerm);
}
public static void readRecord( String filePath, String searchTerm ) {
boolean found = false;
String City = ""; String City_Asciis = ""; String Lattitude = "";
String longitude = ""; String Country = "";
String iso_2 = ""; String iso_3 = ""; String Admin_Name = "";
String Capital = ""; String Population = ""; String Id = "";
try {
File file = new File(filePath);
Scanner x = new Scanner (file);
x.useDelimiter("[,\n]"); //to separate the data items
//hasNext - Returns true if the scanner has another token/value in its input
while(x.hasNext() && !found) {
City = x.next();
City_Asciis = x.next();
Lattitude = x.next();
longitude = x.next();
Country = x.next();
iso_2 = x.next();
iso_3 = x.next();
Admin_Name = x.next();
Capital = x.next();
Population = x.next();
Id = x.next();
if (City.equals(searchTerm)) {
found = true;
}
}
if (found) {
System.out.println(" The following details are of city : " + City +"\n The Ascii string would be : "
+ City_Asciis +"\n Its having the lattitude around : "
+ Lattitude + "\n and Longitude of : "+ longitude +"\n It is situated in : "
+ Country +"\n These have iso code like : "+ iso_2 +" and : "+ iso_3 +"\n It comes under : "
+ Admin_Name +" State \n Capital of this city is : "+ Capital +"\n The population is around : "
+ Population +"\n ZIP code is : "+Id+"");
}
else {
System.out.print("Enter the Correct City Name");
}
}
catch(Exception e1){
System.out.print("file not found \n");
e1.printStackTrace();
}
}
}
This code will load the searched city from the file path given, so that given a particular city name print the details of the city.
Who knows?
Without getting a headache, the code itself looks as though it should work and I personally can't off hand see why your read will only do 41 lines without doing a series of experiments with actual data and not many people really want to do that which is why you've been asked to provide some sample fictitious data.
It could be as simple as the fact that you are satisfying the boolean found variable criteria within the while loop condition and the loop breaks out stopping the read. I would suspect this since you do indicate that the "code will load the searched city from the file path given". I should think that this is not really what you would want for the mere reason that some countries contain the same City names. As a matter of fact, some States, Provinces, or Regions within the same Country can contain same City names. As an example did you know that in the United States alone, there are 88 Cities and Towns named Washington? I know, weird right, especially when you consider that there are only 50 States and 2 Territories. Benjamin Franklin was also one of the Founding Fathers of the United States and there are 35 cities and towns/villages that honorably carry the name of Franklin within that country.
If your data file or database is big enough then I'm sure you would want to display all cities that match your specific search criteria. With that being said perhaps what you need to do is get rid of that && !found condition for the while loop. I personally wouldn't use the Scanner#hasNext() method in the while loop condition either. It's an invitation for disaster since it's more focused towards checking the availability of tokens when used in combination with Scanner#next() rather than actual file lines. Use the Scanner#hasNextLine() in combination with the Scanner#nextLine() method then use the String#split() method to parse the CSV comma (,) delimited data lines one line at a time.
Below I provide a runnable Java code example which demonstrates the above mentioned methods. Your readRecord() method is used but considerably modified to accommodate the following options:
Return a List Interface (List<String>) of City information found
pertaining to the supplied search criteria.
Ignore (skip past) blank or comment lines within the CSV file. Comment lines can start with # or ;.
The option to ignore letter case during the search.
Allow for selection of the desired City Information field to which
the Search Criteria will be applied to. The City Information Fields
are:
City, CityAscii, Latitude, Longitude, Country, ISO2,
ISO3, AdminName, Capital, Population, and ID
Wildcard (? and *) characters can be used when supplying the desired search field so that the entire field name does not need to be provided, for example: lat* for Latitude. So, you can do a City Information search simply based on population if you like instead of a City Name.
Allow for wildcard (? and *) characters to be used within the
supplied search criteria for example: wash*. This tells the method
to search for any city which name starts with Wash like
Washington or Washougal or Washtucna.
Allow for the number of found city instances to be returned.
Below is the runnable code which demonstrates the above mentioned concepts. The code is well commented. There are Regular Expressions used within the code and if you want an explanation of those expressions then copy/paste them into regex101.com.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class CityInfoRecords {
public static void main(String[] args) {
/* The appplication is started this way so that there
is no need for static methods or variables.
*/
new CityInfoRecords().startApp(args);
}
// Application Start method.
private void startApp(String[] args) {
String ls = System.lineSeparator(); // Not all OS Consoles work well with "\n"
String filePath = "qwe.csv"; // Path and file name of the data file.
Scanner in = new Scanner(System.in);
// Provide the City Info Field to base search from...
System.out.println("Enter the Data Field you want to search by:" + ls
+ "[City, CityAscii, Lattitude, Longitude, Country" + ls
+ "ISO2, ISO3, AdminName, Capital, Population, ID]" + ls
+ "Wildcards (? and *) can be used:");
String searchField = in.nextLine();
// Provide the Search Criteria to find within the supplied City Info Field.
System.out.println(ls + "Enter the search criteria you are looking for" + ls
+ "in " + searchField + ". Wildcards (? and *) are permitted:");
String searchCriteria = in.nextLine();
// Declare a List Interface of String and fill it
// with the call to the readRecord method.
List<String> cityInfoList = readRecord(filePath, searchField, searchCriteria, 0, "N/A");
// Display the returned List to console window.
for (int i = 0; i < cityInfoList.size(); i++) {
System.out.println(cityInfoList.get(i));
}
}
/**
* Returns a List Interface of the City Information found based on the supplied
* search criteria.<br><br>
*
* #param filePath (String) The full path and file name of the data file to read
* containing City information.<br>
*
* #param searchField (String) The City Information Field to based the supplied
* Search Criteria from. Any City Information Field can be supplied here and
* letter case is optional. The wildcard characters (? and *) can also be used
* here so that the entire field name does not need to be supplied, for example:
* <pre>
* lat* for the Latitude field or
* *asc* for the CityAscii field or
* iso? for either the ISO2 or ISO3 fields or simply
* City for the City field.</pre><br>
*
* The <b>?</b> wildcard character specifies any single alphanumeric character,
* as in ?an, which locates "ran," "pan", "can", and "ban".<br><br>
*
* The <b>*</b> wildcard character specifies zero or more of any alphanumeric
* character, as in corp*, which locates "corp", "corporate", "corporation",
* "corporal", and "corpulent".<br>
*
* #param searchCriteria (String) The search criteria string. This can be any
* string you would like to search for within the supplied City Information
* Field. By default letter case is ignored during searches therefore the
* supplied search criteria string does not need to be letter case specific
* however if you want the search to be case specific then set this methods
* optional ignoreLetterCase parameter to false.<br><br>
*
* Wildcard characters (? and *) can also be used within the Search Criteria
* string so as to expand the search to other possibilities, for example if
* the "City" field is supplied and a criteria string like: "wash*" is supplied
* then any city which name starts with "Wash" will have their city information
* returned.<br><br>
*
* The <b>?</b> wildcard character specifies any single alphanumeric character,
* as in ?an, which locates "ran," "pan", "can", and "ban".<br><br>
*
* The <b>*</b> wildcard character specifies zero or more of any alphanumeric
* character, as in corp*, which locates "corp", "corporate", "corporation",
* "corporal", and "corpulent".<br>
*
* #param numberOfFoundToReturn (int) The number of cities who's information
* should be returned. If 0 is supplied then all cities found will be returned.<br>
*
* #param noDataReplacement (String) Sometimes there is no data supplied for a
* specific field within the data file or the file data line may not contain
* the same amount of delimited data. Rather than returning NULL or Null String
* ("") for empty data fields you can supply here what to actually return in
* such a case. "N/A" is a good choice or perhaps: "Nothing Supplied". Whatever
* you like to use can be supplied here.<br>
*
* #param ignoreLetterCase (Optional - Boolean - Default is true) By default
* searches ignore letter case but if you want your search to be letter case
* specific then you can supply boolean false to this optional parameter.<br>
*
* #return (String List Collection) Information for every City found within the
* supplied data file which matches the supplied field and search criteria.
*/
public List<String> readRecord(String filePath, String searchField,
String searchCriteria, int numberOfFoundToReturn,
String noDataReplacement, boolean... ignoreLetterCase) {
String ls = System.lineSeparator(); // Not all OS Consoles work well with "\n" (property)
boolean ignoreCase = true; // Ignore letter case when searching (Default - property)
if (ignoreLetterCase.length > 0) {
ignoreCase = ignoreLetterCase[0];
}
boolean found = false; // Flag to indicate data was found (toggles)
int foundCounter = 0; // Indicates number of same data found (increments)
List<String> returnableList = // The List of found city information that will be returned (collection)
new ArrayList<>();
// City Information Variables (data fields)
String city;
String cityAscii;
String latitude;
String longitude;
String country;
String iso2;
String iso3;
String adminName;
String capital;
String population;
String id;
// Open Scanner to read data file...
// Try With Resources is used here to auto close the reader.
try (Scanner fileReader = new Scanner(new File(filePath))) {
// Iterate through data file...
while (fileReader.hasNextLine()) {
// Read file line by line and remove leading or
// trailing whitespaces, tabs, line breaks, etc.
String cityData = fileReader.nextLine().trim();
// Skip blank or comment lines (comment lines can be lines that start with # or ;)
if (cityData.equals("") || cityData.startsWith("#") || cityData.startsWith(";")) {
continue; // Get next file line
}
// Split the read line based on any comma delimited anomaly.
String[] cityInfo = cityData.split(",|,\\s+|\\s+,|\\s+,\\s+");
// The number of data pieces split from data line.
// Not all lines may contain the same amount of data.
int i = cityInfo.length;
/* Ternary is used to fill city information variables
so that data not provided will not be null or null string.
As an Example for the city variabel this is the same as:
if (i >= 1 && !cityInfo[0].equals("")) {
city = cityInfo[0].trim();
}
else {
city = noDataReplacement;
}
*/
city = (i >= 1 && !cityInfo[0].equals("")) ? cityInfo[0].trim() : noDataReplacement;
cityAscii = (i >= 2 && !cityInfo[1].equals("")) ? cityInfo[1].trim() : noDataReplacement;
latitude = (i >= 3 && !cityInfo[2].equals("")) ? cityInfo[2].trim() : noDataReplacement;
longitude = (i >= 4 && !cityInfo[3].equals("")) ? cityInfo[3].trim() : noDataReplacement;
country = (i >= 5 && !cityInfo[4].equals("")) ? cityInfo[4].trim() : noDataReplacement;
iso2 = (i >= 6 && !cityInfo[5].equals("")) ? cityInfo[5].trim() : noDataReplacement;
iso3 = (i >= 7 && !cityInfo[6].equals("")) ? cityInfo[6].trim() : noDataReplacement;
adminName = (i >= 8 && !cityInfo[7].equals("")) ? cityInfo[7].trim() : noDataReplacement;
capital = (i >= 9 && !cityInfo[8].equals("")) ? cityInfo[8].trim() : noDataReplacement;
population = (i >= 10 && !cityInfo[9].equals("")) ? cityInfo[9].trim() : noDataReplacement;
id = (i >= 11 && !cityInfo[10].equals("")) ? cityInfo[10].trim() : noDataReplacement;
// Determine the city data field we want to search in
String regex;
// Were wildcards used in the supplied Search Field string?
if (searchField.contains("?") || searchField.contains("*")) {
// Yes... Prep regex to get proper search field
regex = searchField.replace("?", ".?").replace("*", ".*?").toLowerCase();
}
else {
regex = "(?i)(" + searchField + ")";
}
// Get proper search field data
String field = "";
if ("city".toLowerCase().matches(regex)) {
field = city;
}
else if ("cityAsciis".toLowerCase().matches(regex)) {
field = cityAscii;
}
else if ("lattitude".toLowerCase().matches(regex)) {
field = latitude;
}
else if ("longitude".toLowerCase().matches(regex)) {
field = longitude;
}
else if ("country".toLowerCase().matches(regex)) {
field = country;
}
else if ("iso2".toLowerCase().matches(regex)) {
field = iso2;
}
else if ("iso3".toLowerCase().matches(regex)) {
field = iso3;
}
else if ("adminName".toLowerCase().matches(regex)) {
field = adminName;
}
else if ("capital".toLowerCase().matches(regex)) {
field = capital;
}
else if ("population".toLowerCase().matches(regex)) {
field = population;
}
else if ("id".toLowerCase().matches(regex)) {
field = id;
}
if (field.equals("")) {
System.err.println("Invalid Search Field Name Provided! (" + searchField + ")");
return returnableList;
}
// See if the search criteria contains wildcard characters
// A search can be carried out using wildcards in this method.
if (searchCriteria.contains("?") || searchCriteria.contains("*")) {
// There is...build the required Regular Expression (RegEx) to use.
regex = searchCriteria.replace("?", ".?").replace("*", ".*?");
// See if the data item matches the search criteria ignoring letter case if desired.
// The String.matches() method is used for this and ternary for ignoring letter case.
if (ignoreCase ? field.toLowerCase().matches(regex.toLowerCase()) : field.matches(regex)) {
found = true; // toogle flag to true if there is a match.
}
}
// No wildcard characters in search criteria...
// Ternary is used in condition to handle ignore letter case if desired.
else if (ignoreCase ? field.equalsIgnoreCase(searchCriteria) : field.equals(searchCriteria)) {
found = true; // toogle flag to true if there is a match.
}
// If the 'found' flag has been set to true...
if (found) {
// Add City information to returnable ArrayList
String info = ls + "The following details are of city: " + city + ls
+ "The Ascii string would be: " + cityAscii + ls
+ "It has the approximate Lattitude of: " + latitude + ls
+ "And the approximate Longitude of: " + longitude + ls
+ "It is situated in the country of: " + country + ls
+ "The city has iso codes like: " + iso2 + " and: " + iso3 + ls
+ "The State/Province/Region is: " + adminName + ls
+ "Capital of this city is: " + capital + ls
+ // Didn't know cities had capitals
"The population is approximately: " + population + ls
+ "City general ZIP code is: " + id;
returnableList.add(info); // Add to list
found = false; // Toggle found flag back to false in prep to locate more city data.
foundCounter++; // increment the found counter.
// If the First Instance Only flag is true then...
if (numberOfFoundToReturn > 0 && foundCounter == numberOfFoundToReturn) {
// Break out of the 'while' loop. We don't need anymore cities.
break;
}
}
}
// If the Found Counter was not incremented then
// we didn't find any data in file... Inform User.
if (foundCounter == 0) {
System.err.print(ls + "Can not find City Name (" + searchCriteria
+ ") in data file!" + ls);
}
}
catch (FileNotFoundException ex) {
System.err.print("City Data file not found! (" + filePath + ")" + ls);
}
// Return the List of found data.
return returnableList;
}
}
Create a new Java Application Project and name it CityInfoRecords. Copy and paste the above code over top of the Main Startup class. Run the application, read the console prompts carefully and enter the proper data.
The first prompt asks for a City Information Field name...enter: city.
The second prompt will ask for the search criteria for city...enter a city name in Upper or lower case (it doesn't matter). The city information will be displayed in console but only if that city name is contained within the City field within the data file.
Now run the code again and enter the same data except this time, for the city name just provide the first three letters of a city name and an asterisk (*) and then hit the enter key. Now any city information within your specific City Data File which starts with those supplied three letters will be displayed within the Console Window.
Play with it, try different fields to search from and play with the wildcard characters as well with your supplied field or search criteria data.
Now make readRecord a Class instead of a method which would be better.

Parsing String in Java, then storing in variables

I need help to parse a string in Java... I'm very new to Java and am not sure how to go about it.
Suppose the string I want to parse is...
String str = "NC43-EB2;49.21716;-122.667252;49.216757;-122.666235;"
What I would want to do is:
String name = C43
String direction = EB2;
Then what I'd like to do is store 2 coordinates as a pair...
Coordinate c1 = 49.21716;-122.667252;
Coordinate c2 = 49.216757;-122.666235;
And then make a List to store c1 and c2.
So far I have this:
parseOnePattern(String str) {
String toParse = str;
name = toParse.substring(1, toParse.indexOf("-"));
direction = toParse.substring(toParse.indexOf("-", toParse.indexOf(";")));
I'm not sure how to move forward. Any help will be appreciated.
A simple substring function may solve your problem.
String str = "NC43-EB2;49.21716;-122.667252;49.216757;-122.666235;";
String[]s = str.split(";");
String[]n = s[0].split("-");
String name = n[0].substring(1);
String direction = n[1];
String c1 = s[1] +";"+s[2];
String c2 = s[3] +";"+s[4];
System.out.println(name + " " + direction);
System.out.println(c1 + " " + c2);
I hope this helps you.
Welcome to Java and the whole set of operations it allows to perform on Strings. You have a whole set of operations to perform, I will give you the code to perform some of them and get you started :-
public void breakString() {
String str = "NC43-EB2;49.21716;-122.667252;49.216757;-122.666235";
// Will break str to "NC43-EB2" and "49.21716" "-122.667252" "49.216757" "-122.666235"
String [] allValues = str.split(";", -1);
String [] nameValuePair = allValues[0].split("-");
// substring selects only the specified portion of string
String name = nameValuePair[0].substring(1, 4);
// Since "49.21716" is of type String, we may need it to parse it to data type double if we want to do operations like numeric operations
double c1 = 0d;
try {
c1 = Double.parseDouble(allValues[1]);
} catch (NumberFormatException e) {
// TODO: Take corrective measures or simply log the error
}
What I would suggest you is to go through the documentation of String class, learn more about operations like String splitting and converting one data type to another and use an IDE like Eclipse which has very helpful features. Also I haven't tested the code above, so use it as a reference and not as a template.
Ok i made this:
public static void main(String[] args) {
String str = "NC43-EB2;49.21716;-122.667252;49.216757;-122.666235;";
String[] strSplit = str.split(";");
String[] nameSplit=strSplit[0].split("-");
String name=nameSplit[0].replace("N", "");
String direction= nameSplit[1];
String cordanateOne = strSplit[1]+";"+strSplit[2]+";";
String cordanateTwo = strSplit[3]+";"+strSplit[4]+";";
System.out.println("Name: "+name);
System.out.println("Direction: "+direction);
System.out.println("Cordenate One: "+cordanateOne);
System.out.println("Cordenate Two: "+cordanateTwo);
}
Name: C43
Direction: EB2
Cordenate One: 49.21716;-122.667252;
Cordenate Two: 49.216757;-122.666235;
String str3 = "NC43-EB2;49.21716;-122.667252;49.216757;-122.666235;";
String sub = str3.substring(0,4); // sub = NC43
String sub4 = str3.substring(5,9); // sub = EB2;
HashMap<String, String> hm = new HashMap<>();
hm.put(str3.substring(9 ,30), str3.substring(30));
hm.forEach((lat, lot) -> {
System.out.println(lat + " - " + lot); // 49.21716;-122.667252; - 49.216757;-122.666235;
});
//edit if using an array non pairs (I assumed it was lat + lon)
List<String> coordList = new ArrayList<>();
coordList.add(str3.substring(9 ,30));
coordList.add(str3.substring(30));
coordList.forEach( coord -> {
System.out.println(coord);
});
//output : 49.21716;-122.667252;
49.216757;-122.666235;

Split out array list into separate strings

I have created an array of values from my SQLite database - this comprises of just two values from two different columns from an inner joined table.
in my SQLDatabaseHelper.java:
public List<List<String>> getAllAnswersByQuestion1() {
List<String> array1 = new ArrayList<String>();
List<String> array2 = new ArrayList<String>();
SQLiteDatabase db = this.getReadableDatabase();
String selectQuery = "SELECT * FROM " + TABLE_ANSWERS + " ta, "
+ TABLE_QUESTION + " tq, " + TABLE_QUESTANS + " tqa WHERE ta." + ASID
+ " = " + "tqa." + ASID + " AND tq." + QID + " = "
+ "tqa." + QID;
Cursor c = db.rawQuery(selectQuery, null);
if (c.moveToFirst()) {
do {
String questdescr = c.getString(c.getColumnIndex(QDESCR));
String questid = c.getString(c.getColumnIndex(QID));
array1.add(questdescr);
array2.add(questid);
} while (c.moveToNext());
}
List< List<String> > listArray = new ArrayList< List<String> >();
listArray.add(array1);
listArray.add(array2);
return listArray;
}
I want to pass these to my main activity. Specifically I would like to split out the array into separate strings so I can assign those values to separate edittext fields.
This is my current attempt in my main activity:
public void showNextRandomQuestion()
{
SQLDatabaseHelper db = new SQLDatabaseHelper(this);
StringTokenizer tokens = new StringTokenizer(db.getAllAnswersByQuestion1(), ",");
String first = tokens.nextToken();
String second = tokens.nextToken();
questionView.setText(first);
answerText1.setText(second);
}
However the code will not compile as it wants to either 'change the return type of 'getAllAnswersByQuestion1() to string' - or 'Remove argument to match StingTokenizer(String)'
Can't seem to get around this.
for(List l : db.getAllAnswersByQuestion1()){
for(String s : l){
StringTokenizer tokens = new StringTokenizer(s, ",");
String first = tokens.nextToken();
String second = tokens.nextToken();
questionView.setText(first);
answerText1.setText(second);
}
}
this update will make your code work at least
It looks like you have both the question and answer stored in the QDESCR field, comma delimited.
If that is the case, then something like the code below would work.
I assume that you want to select a random question from the list, given the method name.
You can use Random in order to generate a random index of the list.
You might want to add logic to prevent previously selected questions from coming up again.
Here is the basic code that gets the question/answer, and question ID:
public void showNextRandomQuestion() {
//get the data from the database
List<List<String>> listList = db.getAllAnswersByQuestion1();
//Get the question/answer Strings and the question IDs
List<String> questionStrings = listList.get(0); //question and answer Strings
List<String> questionIDs = listList.get(1); //question IDs
//Generate random index
Random r = new Random();
int rand = Math.abs((r.nextInt() % questionStrings.size()));
//get question ID for randomly selected question
String questionID = questionIDs.get(rand);
//Separate out the question/answer of randomly selected question
StringTokenizer tokens = new StringTokenizer(questionStrings.get(rand), ",");
String first = tokens.nextToken();
String second = tokens.nextToken();
questionView.setText(first);
answerText1.setText(second);
}
Also, note that it would be better to use String.split(), as is stated in the documentation.

Auto Increment ID break the Sequence

My program has an auto incremented ID with the format of ITM001, ITM002.... But after ITM009, ITM0010 the sequence is broken and goes back to ITM001. Because of that I'm getting ITM0010 as next item ID instead of ITM0011. Please help me to understand how should I write the query to continue the sequence.
ITM001
**ITM0010**
ITM002
ITM003
ITM004
ITM005
ITM006
ITM007
ITM008
ITM009
Connection conn = DBConnection.conn();
String sql = "select itemId from ItemMain";
ResultSet res = DBHandller.getData(sql, conn);
if (res.last()) {
String lastid = res.getString("itemId");
return lastid;
}
return null;
/////////////////////////////////////////////////////////////////////////////
String itemID = ItemController.getItemID();
String[] split = itemID.split("ITM",0);
int num = Integer.parseInt(split[1]);
itemID = "ITM00"+ (num+1);
txtitemID.setText(itemID);
The problem is that you're using split on 0, and there are several 0's in your String after you increment, for instance:
String[] split = itemID.split("ITM",0);
int num = Integer.parseInt(split[1]);
String second = "ITM00" + (num + 1);
System.out.println(second);
System.out.println(Arrays.toString(second.split("0")));
This will output:
[ITM, , 1]
Since the last 0 will also be split.
Something like:
String itemID = "ITM009";
int num = Integer.parseInt(itemID.substring(itemID.indexOf("0")));
String second = "ITM0" + String.format("%02d", num + 1);
System.out.println(second);
Will give you what you want probably, but you need to figure out how many digits you want your key to have and adapt accordingly.
You are implicitly sorting on a VARCHAR field.
SELECT a.a FROM (
SELECT 'a001' [a]
UNION ALL
SELECT 'a009' [a]
UNION ALL
SELECT 'a0010' [a]
) a ORDER BY a
a001
a0010
a009
The last id you pick up will always be 009 so the next one you create will always be 0010.
If you front padded the "10" with 1 "0" instead of two the implicit ascending sorting would be correct. "001 ... 009, 010"

After extracting data from html using a for loop, how do I insert one by one into a database?

I have extracted multiple data from an HTML using Jsoup and now I am trying to insert one by one into a derby db using JDBC on netbeans.
Here is my code:
public String nameOf() {
String nameStr = null;
String nameResults = "";
for(int j=100;j<=110;j++) {
refNum = j;
//System.out.println("Reference Number: " + refNum);
try {
//crawl and parse HTML from definition and causes page
Document docDandC = Jsoup.connect("http://www.abcd.edu/encylopedia/article/000" + refNum + ".htm").get();
// scrape name data
Elements name = docDandC.select("title");
nameStr = name.get(0).text();
//System.out.println(nameStr);
nameResults += nameStr + " ";
} catch (Exception e) {
//System.out.println("Reference number " + refNum + " does not exist.");
}
}
return nameResults;
So this method takes the names of diseases from 10 different HTMLs. What I am trying to do is to insert one name at a time to a derby db that I have created using JDBC. I have everything set up and all I have left to do is to insert each name in the corresponding name field of a table named DISEASE (which has fields: id, name, etc).
nameResults += nameStr + " ";
This part worries me as well since some diseases can have multiple words. Maybe I should use a list of some sort?
Please help! Thanks in advance.
Something like:
public List<String> nameOf() {
...
List<String> nameResults = new ArrayList<String>();
...
nameResults.add(nameStr);
...
return nameResults;

Categories