java.lang.ArrayIndexOutOfBoundsException how to handle-7 - java

java.lang.ArrayIndexOutOfBoundsException
how to remove this exception
public static void main(String[] args) throws ClassNotFoundException, SQLException {
FileUpdate obj = new FileUpdate();
obj.run();
}
public void run() throws SQLException, ClassNotFoundException {
String csvFile = "/home/IMRAN/file.csv";
BufferedReader br = null;
String line = "";
String cvsSplitBy = ",";
try {
DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
Date dateobj = new Date();
String dt = df.format(dateobj);
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/Rforms", "root", "root12");
Statement st = con.createStatement();
br = new BufferedReader(new FileReader(csvFile));
while ((line = br.readLine()) != null) {
String[] emp = line.split(cvsSplitBy);
// if (emp[0] != null && emp[1] != null ) {
// for(int x = 0; x < emp.length; x++) {
String t = (String) emp[0].trim();
String t2 = (String) emp[1].trim();
}
}

Problem is not clear... java.lang.ArrayIndexOutOfBoundsException occours when you try to access to an object (array element) that does not exist. For example, your array is 7 elements long and you try to access element[8]
Are you sure emp[0] is not null?

You should check length of the emp array before accessing its elements.
if(emp!=null && emp.length==2){
String t = (String) emp[0].trim();
String t2 = (String) emp[1].trim();
}

This code below tells that emp should always have 2 or more elements.
else you got java.lang.ArrayIndexOutOfBoundsException.
...
String t = (String) emp[0].trim();
String t2 = (String) emp[1].trim();
...

Hi Let's assume that you have place CSV file and content correctly in that case you can place conditions check per below
String[] emp = line.split(cvsSplitBy);
if (emp.length > N) {
String t = (String) emp[0] !=null ?emp[0].trim():"";
String t2 = (String)emp[1] !=null ?emp[1].trim():"";
}
Note that you are aware of number values fetch from the line .
or you can utilize List. this will completely take you out from this issue.
List lst= Arrays.asList(emp);
Refer java docs for how to utilize List and fetch list from it.

Related

How to Iterate Twice over Map values in Java

I know there are other solutions out there but nothing is working for me.
Question: In my main method, I group together IDs by rating and make the rating the key and the rest of the info the value as a List. When I create the hashmap and put in the lists I can accurately print the contents of the hashmap. However, once I pass the map the evaluate method, the values are lost and I cannot iterate in the same way that I did in the main method, even though the logic is the same. I am not experienced with the Map class in java. Can somebody please help me figure out why when I pass the Map to my evaluate method that I can no longer iterate the Map?
import java.io.*;
import java.util.*;
public class Evaluate {
public static double grandTotal;
public static void main(String[] args) throws Exception {
FileInputStream fs = new FileInputStream("testInput.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(fs));
FileInputStream fs2 = new FileInputStream("testTest.txt");
BufferedReader br2 = new BufferedReader(new InputStreamReader(fs2));
String line;
String line2;
String[] bloop;
String bleep;
String flooper;
String splitter;
String[] splitInput;
List<String> oneStarList= new ArrayList<String>();
List<String> twoStarList= new ArrayList<String>();
List<String> threeStarList= new ArrayList<String>();
List<String> fourStarList= new ArrayList<String>();
List<String> fiveStarList= new ArrayList<String>();
List<String> values2 = new ArrayList<String>();
try {
while ((line=br.readLine()) != null) {
bloop = new String[10];
bloop = line.split("\\s+");
bleep = bloop[1].toString();
flooper = (bloop[0]+" "+bloop[2]+" "+bloop[3]+" "+bloop[4]);
if (bleep.equals("1")){
oneStarList.add(flooper);
}
else if (bleep.equals("2")){
twoStarList.add(flooper);
}
else if (bleep.equals("3")){
threeStarList.add(flooper);
}
else if (bleep.equals("4")){
fourStarList.add(flooper);
}
else if (bleep.equals("5")){
fiveStarList.add(flooper);
}
grandTotal+=(Double.parseDouble(bloop[2]));
}
}
catch (Exception e){
}
Map<String,List<String>> hmap = new HashMap<String,List<String>>();
hmap.put("1",oneStarList);
hmap.put("2", twoStarList);
hmap.put("3", threeStarList);
hmap.put("4", fourStarList);
hmap.put("5", fiveStarList);
while ((line2=br2.readLine()) != null) {
splitInput = new String[5];
splitInput = line2.split("\\s+");
evaluate(splitInput[0],splitInput[1],hmap);
}
br.close();
br2.close();
}
public static void evaluate(String movID, String usrID, Map<String,List<String>> hash) throws Exception{
FileWriter fw = new FileWriter("outputTest.txt");
BufferedWriter bwr = new BufferedWriter(fw);
List<String> values = new ArrayList<String>();
List<String> outputList = new ArrayList<String>();
String[] floop;
String fleep;
int movIDtotal=0;
int usrIDtotal=0;
int totalValues=0;
double pmovIDStar=0;
double pusrIDStar=0;
double pmovID=0;
double pusrID=0;
double numID=0;
double keyTotalProb=0;
String keyOutputStr;
String keyHold;
final Set<Map.Entry<String,List<String>>> entries = hash.entrySet();
for (String key : hash.keySet()){
values = hash.get(key);
System.out.println(key + ":");
for (int i=0;i<values.size();i++){
System.out.println(values.get(i));
floop = new String[5];
fleep = values.get(i);
floop = fleep.split("\\s+");
if (movID.equals(floop[0])){
movIDtotal++;
totalValues++;
}
if (usrID.equals(floop[0])){
usrIDtotal++;
totalValues++;
}
}
values.clear();
}
for (Map.Entry<String, List<String>> entry: entries){
values= entry.getValue();
keyHold = entry.getKey();
for (int j=0;j<values.size();j++){
floop = new String[5];
fleep = values.get(j);
floop = fleep.split("\\s+");
if (movID.equals(floop[0])){
pmovIDStar = Double.parseDouble(floop[3]);
numID = Double.parseDouble(floop[1]);
pmovID = (numID/movIDtotal);
}
if (usrID.equals(floop[0])){
pusrIDStar = Double.parseDouble(floop[3]);
numID = Double.parseDouble(floop[1]);
pusrID = (numID/usrIDtotal);
}
}
keyTotalProb = ((totalValues/grandTotal)*(pmovIDStar)*(pusrIDStar))/(pusrID*pmovID);
keyOutputStr = Double.toString(keyTotalProb);
outputList.add(keyHold);
outputList.add(keyOutputStr);
values.clear();
}
double max = Double.MIN_VALUE;
for (int m=0;m<outputList.size();m+=2){
double coolguy = Double.parseDouble(outputList.get(m+1));
int index = 0;
if(coolguy>max){
max = coolguy;
index = m;
}
try {
bwr.write(String.format("%-1s %-1s %-1s%n", movID,usrID,outputList.get(index)));
bwr.close();
fw.close();
}
catch(Exception e) {
}
}
}
}
Backup info: I'm trying to build a java program that essentially performs the final stage of the Naive Bayes algorithm to predict user ratings (1-5) for movies. I have used MapReduce to train data and now I have an input file where each line contains a string containing information in this order without the commas (movie or user id,rating , number of times rating and ID occur together in total, number of times ID occurs in total, probability that ID and rating occur together out of all ratings for ID). Essentially this is the classification stage.
never suppress excetions. especially when you do coding/debugging.
catch (Exception e){ } is very bad practice
When you do:
final Set<Map.Entry<String,List<String>>> entries = hash.entrySet();
it does not copy hash.entrySet to entries. It creates another reference to it.
same is for values= entry.getValue();
then what do you expect after your first loop (and others too)?
when you do:
values.clear();
your values gone from the lists which are in hash and since entries is just a reference to hash.entrySet() you have what you've done - empty lists.

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;
}
}

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.

split variables from texte

this method runs an exception and i didn't find why.
private void loadTrace () {
BufferedReader reader = new BufferedReader(
new StringReader(logTextArea.getText()));
String str;
try {
while(reader != null)
{
str =reader.readLine();
String [] splitted = str.split("\\|");
String b = splitted[1].trim();
String c = splitted[2].trim();
String d = splitted[3].trim();
String Chemin;
String Type = "action" ;
String Description;
if (d!=null) {
Description=d;
}
else Description ="Afficher onglet";
if (c!= null) {
Chemin= b+"."+c;
}
else Chemin =b;
String trace =Type+" "+Description +" "+Chemin ;
ArrayList<String> p = new ArrayList<String>();
p.add(trace);
System.out.println(p);
}
}
catch(IOException e) {
e.printStackTrace();
}
}
Without knowing the exception I can guess one of the potential issue is in these lines:-
String [] splitted = str.split("\\|");
String b = splitted[1].trim();
String c = splitted[2].trim();
String d = splitted[3].trim();
You are accessing splitted without checking if it is null or size so you may run into ArrayIndexOutOfBound exception if splitted length is less than 3. So modify the code this way-
String [] splitted = str.split("\\|");
if(splitted!=null && splitted.length==3){
String b = splitted[0].trim();
String c = splitted[1].trim();
String d = splitted[2].trim();
}
The NullPointerException you get now that you've fixed the ArrayIndexOutOfBound is because of the test you use in your while loop:
while(reader != null)
{
...
}
reader will always be non-null so this loop will never end. You need to test if
reader.readLine()
returns null (indicating EOF).
I guess you get an ArrayIndexOutOfBoundException, right?
(You need to tell us, what Exception you receive)
The problem could be in the following lines. You should check the size of the array and not just "hope" that it has three parts.
String b = splitted[1].trim();
String c = splitted[2].trim();
String d = splitted[3].trim();

sql and database

I have this method in my database class.and I want to get a part of data from a column which is "dateOfBirth" in MySQL table ,but I don't know why the list.size() is "0" but when i use System.out.println() in my code it will show just the first line of sql table ,although I have two rows!!!
my method:
public static int getBirthPercent(String i) throws SQLException {
Statement stmt = conn.createStatement();
List<String> list = null;
if (i.equals("O")) {
ResultSet rst = stmt.executeQuery("SELECT dateOfBirth from birthtable");
while (rst.next()) {
String s1 = rst.getString(1);
if (rst.wasNull()) {
s1 = null;
}
String s2 = s1.substring(s1.length() - 4);
int s3 = Integer.parseInt(s2);
if (list == null && s3 < 1970) {
list = new ArrayList<String>();
list.add(s2);
} else {
list = new ArrayList<String>(0);
}
}
}
if (i.equals("N")) {
ResultSet rst = stmt.executeQuery("SELECT dateOfBirth from birthtable");
while (rst.next()) {
String s1 = rst.getString(1);
if (rst.wasNull()) {
s1 = null;
}
String s2 = s1.substring(s1.length() - 4);
int s3 = Integer.parseInt(s2);
if (list == null && s3 > 2000) {
list = new ArrayList<String>();
list.add(s2);
System.out.println(list);
} else {
list = new ArrayList<String>(0);
}
}
}
it will return "0" for all "if" situation but the System.out.println() ,shows [2006] which is one of my row's column's year,although I have two rows it must show [2006,2009].but it doesn't!!!
Now try this code, and let us know. Cheers.
public static int getBirthPercent(String i) throws SQLException {
Statement stmt = conn.createStatement();
ResultSet rst = null;
List<String> list = new ArrayList<String>();
if (i.equals("O")) {
rst = stmt.executeQuery("SELECT dateOfBirth from birthtable");
while (rst.next()) {
String s1 = rst.getString(1);
if (s1 != null && !s1.isEmpty()) {
String s2 = s1.substring(s1.length() - 4);
int n = Integer.parseInt(s2);
if (n < 1970) {
list.add(s2);
}
}
}
}
if (i.equals("N")) {
rst = stmt.executeQuery("SELECT dateOfBirth from birthtable");
while (rst.next()) {
String s1 = rst.getString(1);
if (s1 != null && !s1.isEmpty()) {
String s2 = s1.substring(s1.length() - 4);
int n = Integer.parseInt(s2);
if (n > 2000) {
list.add(s2);
}
}
}
}
System.out.println(list);
}
Enough refactoring for now. Try to do more for yourself. For example,
look into commons-lang StringUtils to replace null checking,
use Date object to store dates and use rs.getDate() instead,
you can use Calendar object to get the year out. Or even SimpleDateFormat object would work too
etc...

Categories