Passing data to an object - java

I'll list my code at the bottom, but here's the deal.
I have a parser class with a process method. This method scrapes data from a web page. I want to take each line of the scrape, split the string into an array and add the values to an object, then add the object to an ArrayList. As the loop iterates, new values from each line of the scrape are added to an ArrayList via the object. The relevent method in this code is public ArrayList process()
I'm getting the following compile errors:
The constructor Flight(String) is undefined
Syntax error on token "[", Expression expected after this token
The method add(String) in the type ArrayList is not applicable for the arguments (Flight)
What am I doing wrong here, and how do if fix it?
public class HtmlParser {
public String url;
public String airline;
public static String lastFlight;
static ArrayList<String> capture = new ArrayList<String>();
public HtmlParser(Properties config) throws IOException{
url = config.getProperty("url");
airline = config.getProperty("airline");
print("Fetching.........%s" , url);
}
public ArrayList<String> process() throws IOException{
Document doc = Jsoup.connect(url).get();
Elements tableRow = doc.getElementsByTag("tr");
for(Element tr : tableRow){
if(tr.text().contains(airline)){
String delims = "[ ]+";
String singleRowArray[] = tr.text().split(delims);
Flight f = new Flight(singleRowArray[]);
capture.add(f);
}
}
return capture;
}
Here's my flight Class.
public class Flight {
public Flight(String singleRowArray[]) {
String origin = singleRowArray[0];
String airline1 = singleRowArray[1];
String airline2 = singleRowArray[2];
String flightNo = singleRowArray[3];
String date = singleRowArray[4];
String ArrTime = singleRowArray[5];
String status = singleRowArray[6];
}
}

"The constructor Flight(String) is undefined Syntax error on token "[", Expression expected after this token"
Try switching the brackets to the type, not the variable: String[] singleRowArray
"The method add(String) in the type ArrayList is not applicable for the arguments (Flight)"
You have a List<String> where you want to input an object of type Flight, so you should change the list type to List<Flight>.

static ArrayList<String> capture = new ArrayList<String>();
You can't add the Flight class object in capture list which can only contain element in String type.
Flight f = new Flight(singleRowArray[]);
capture.add(f); // Issue
-----------------^

Related

ElasticSearch Multiget issue in Java

I am new to Java programming and need some help here.
I am running below code and getting appropriate response i.e.
{"name1":"Name2","date1":"2016-05-13","message1":"Message2"}
{"name1":"Name0","date1":"2016-05-13","message1":"Message0"}
MultiGetResponse multiGetItemResponses = client.prepareMultiGet()
.add("loc", "message", "AVSoemK55hnvwxeDfgCc", "AVSoemK55hnvwxeDfgCa").get();
for(MultiGetItemResponse itemResponse: multiGetItemResponses){
GetResponse response2 = itemResponse.getResponse();
if(response2.isExists()){
String json2 = response2.getSourceAsString();
System.out.println(json2);
}
}
however, when i am trying to parameterise the search text, its not returning any value. Can anyone please guide what might be going wrong here? I have checked that variable abc is returning correct value i.e. "AVSoemK55hnvwxeDfgCc", "AVSoemK55hnvwxeDfgCa"
public static boolean getData(String ids){
String idAry[] = ids.split(",");
ArrayList<String> idStr = new ArrayList<String>();
for (String id:idAry){
idStr.add('"'+id+'"');
}
String abc = idStr.toString().replace("[", "").replace("]", "");
System.out.println(abc);
MultiGetResponse multiGetItemResponses = client.prepareMultiGet()
.add("loc", "message", abc).get();
// MultiGetResponse multiGetItemResponses = client.prepareMultiGet()
// .add("loc", "message", "AVSoemK55hnvwxeDfgCc", "AVSoemK55hnvwxeDfgCa").get();
//
for(MultiGetItemResponse itemResponse: multiGetItemResponses){
GetResponse response2 = itemResponse.getResponse();
if(response2.isExists()){
String json2 = response2.getSourceAsString();
System.out.println(json2);
}
}
return true;
}
You don't need the abc variable, i.e. you don't need to transform your list to string. You simply need to construct your query like this, by passing idList to your add() call as this call will take the index, the type and an Iterable<String>, so the idList already fits the job.
public static boolean getData(String ids){
String idAry[] = ids.split(",");
List<String> idList = Arrays.asList(idAry);
MultiGetResponse multiGetItemResponses = client.prepareMultiGet()
.add("loc", "message", idList).get();
...

How to populate array list with objects of different types using while loop

public void importStudent(String fileName) throws FileNotFoundException{
File input = new File("students.txt");
Scanner readFile = new Scanner(input);
ArrayList<Object> tokensList = new ArrayList<Object>();
while (readFile.hasNextLine()){
tokensList.add(readFile.nextLine().split(","));
String FirstName = (String) tokensList.get(0);
String LastName = (String) tokensList.get(1);
String phoneNum = (String) tokensList.get(2);
String address = (String) tokensList.get(3);
double gpa = (double) tokensList.get(4);
String major = (String) tokensList.get(5);
double creditsTaking = (double) tokensList.get(6);
//all of the stuff in one line of the text file
Student s = new Student( FirstName, LastName, phoneNum, address, gpa,
major, creditsTaking);
peopleBag.add(s);
}
readFile.close();
}
So i have a text file in which each line has all of the information for one object of Student class that I am trying to create. What I want to do is read one line of the text file, add of the info to an array list, then use that list to fulfill all of the fields of my Student constructor. This method has no red lines, but I get the following error when I run this method:
Exception in thread "main" java.lang.ClassCastException:
[Ljava.lang.String; cannot be cast to java.lang.String at
step1.PeopleBag.importStudent(PeopleBag.java:35) at
step1.Demo.main(Demo.java:10)
String.split returns an array, not a List. You could fix it like,
List<String> tokensList = new ArrayList<>();
tokensList.add(Arrays.asList(readFile.nextLine().split(",")));
or change tokensList to an array, and access it like an array.
String[] tokens = readFile.nextLine().split(",");
String FirstName = tokens[0];
// ...
or do that because split return an array, you should specify the index of array
tokensList.add(Arrays.asList(readFile.nextLine().split(",")[0]));

Return records in java

I need to return multiple records in to a variable, in below mention code with in while loop I am getting all the records but while return result I am getting only one record I don't know how to do
public String feed()
{
String projectname=null;
String claintid=null;
String projectstatus=null;
String prjstartdate=null;
String prjenddate=null;
String lastmodified=null;
String prjpinurl=null;
String patientDetails=null;
try
{
Connection conn = getMySqlConnection();
String simpleProc = "{ call Sp_RetPrjvals () }";
CallableStatement cs = conn.prepareCall(simpleProc);
ResultSet rs=(ResultSet) cs.executeQuery();
while(rs.next()){
projectid=rs.getString(1);
projectname=rs.getString(2);
claintid=rs.getString(3);
projectstatus=rs.getString(4);
prjstartdate=rs.getString(5);
prjenddate=rs.getString(6);
lastmodified=rs.getString(7);
prjpinurl=rs.getString(8);
patientDetails=projectid+"|"+projectname+"|"+claintid+"|"+projectstatus+"|"+prjstartdate+"|"+prjenddate+"|"+lastmodified+"|"+prjpinurl;
//here i am getting two values before:::2|Sample project 2|1|WIP|2015-08-01 00:00:00.0|2016-08-01 00:00:00.0|2015-08-24 16:40:10.0|http://hcup-us.ahrq.gov/toolssoftware/ccs/ccs.jsp
before:::1|Sample project 1|1|WIP|null|null|2015-08-24 16:38:39.0|http://hcup-us.ahrq.gov/toolssoftware/ccs/ccs.jsp
}
conn.close();
} catch (Exception e)
{
}
return patientDetails;
// here i am getting only After:::1|Sample project 1|1|WIP|null|null|2015-08-24 16:38:39.0|http://hcup-us.ahrq.gov/toolssoftware/ccs/ccs.jsp
}
The problem is that you override your String. You have to add it to a list or an array.
For example: List<String> al = new ArrayList<String>()
and then you have to add the String you build on every while step into this array and retrun this array:
al.add(patientDetails);
your return statement follows this: return al;
your function header is then:
public List<String> feed(){
patientDetails is a `String` Object.
If you expet to be able to retun a list of striong, then you should use an array of String objects in that case.
Something like:
String[] patientDetails
Then in your code you should add each returned record to your array
Something like:
patientDetails[i] = projectid+"|"+projectname+"|"+claintid+"|"+projectstatus+"|"+prjstartdate+"|"+prjenddate+"|"+lastmodified+"|"+prjpinurl;
i ++; //Initialize this *i* variable outside the while
Also change the signature of your method as:
public String[] feed()
Because you don't know your result size, you need a dynamic structure, like a list:
List<String> pacients = new ArrayList<>();
while(results.next()){
...
String patientDetails = ....;
pacients.add(patientDetails);
}
After this code you will have alist of pacient details. But I would advise you to keep their data in an object, not a String;
class PatientDetails {
String projectname; // you don't have to initialize with null, it's done by default
String claintid;
String projectstatus;
String prjstartdate;
String prjenddate;
String lastmodified;
String prjpinurl;
String patientDetails;
// getters & setters
#Override
public String toString(){
return projectid+"|"+projectname+"|"+claintid+"|"+ ...;
}
}
Now when you will want to print a PatientDetails you will get same result as your string representation.
And you would return a List<PatientDetails> holding your query results.

pass the argument of array from command line instead of scanner in java

I write the code in Java to get the arguments by scanner. I have several classes : ChartToHtml.java, ExecutionProperties.java, ExecutionV2.java, TestCase.java, TestCaseList.java, Section.java and all of them will be called from ImplTest.java.
They are working fine when I execute either from eclipse or command line by scanner. The problem is when I want to execute them via program arguments and pass the arguments in one single line. It considers the input as single String but I have to use a String[] as input for Section class.
Here are my Section class and ImplTest classes
public class Section {
Ini.Section root;
ArrayList<String> StringList = new ArrayList<String>();
ArrayList<TestCase> TCList = new ArrayList<TestCase>();
String sectionSearched;
String section;
String filenameSearched;
public Section (){
}
public Section (String filenameSearched, String sectionSearched) {
this.sectionSearched = sectionSearched;
this.filenameSearched = filenameSearched;
}
public ArrayList<String> findSection(String filename, String... wanted) throws IOException, IOException {
Ini myIni = new Ini(new File (filename));
for (String d : wanted) {
root = myIni.get(d);
for (String name : root.keySet()){
StringList.add(root.get(name));
}
}
return StringList;
}
public ArrayList<TestCase> convertStringToTestCase(ArrayList<String>StringList){
for ( int i = 0; i < StringList.size(); i++) {
String name = StringList.get(i) ;
TestCase tc = new TestCase (name);
TCList.add(tc);
}
return TCList;
}
public String[] getSection(int NumOfSec){
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.println("Input section name:");
section = scanner.nextLine();
for (int i =0; i<NumOfSec; i++){
String token[]= section.split(" ");
System.out.println(Arrays.toString(token));
return token;
}
}
}
}
My Main class
public class ImplTest {
public static void main(String[] args) throws IOException, ConfigurationException, TemplateException {
ExecutionV2 ex = new ExecutionV2();
TestCaseList tc = new TestCaseList();
Section s = new Section();
ChartToHtml chr= new ChartToHtml();
ExecutionProperties ep = new ExecutionProperties();
ImplTest imp = new ImplTest();
String filename = ex.getcfg();
String []sec = ex.getSection();
int it = ex.getIterationMax();
String runTCpath =ex.getRunTCdir();
String dir = chr.getChartDir();
ArrayList<TestCase> TClist = s.convertStringToTestCase(s.findSection(filename, sec));
ex.executeTestCaseList(TClist, it , runTCpath);
ex.getTCAttribute(TClist);
ep.setConfigProperties(tc.getTCPassed(), tc.getTCFailed());
chr.generateHistoryTable();
chr.generateChartAndTableTemplate(tc.getTCPassed(), tc.getTCFailed(),ex.getNameList(), ex.getPassedList().toString(), ex.getItList().toString(),dir);
}
}
Then I modified the main class to pass the arguments via run configuration and pass this single line:
ArrayList<TestCase> TClist = s.convertStringToTestCase(s.findSection(**args[0]**, **args[1]**));
ex.executeTestCaseList(TClist, Integer.parseInt(**args[2]**) , **args[3]**);
ex.getTCAttribute(TClist);
ep.setConfigProperties(tc.getTCPassed(), tc.getTCFailed());
chr.generateHistoryTable();
chr.generateChartAndTableTemplate(tc.getTCPassed(), tc.getTCFailed(),ex.getNameList(), ex.getPassedList().toString(), ex.getItList().toString(), **args[4]**);
and pass this singe line into program arguments
C:\\Users\\syuniyar\\.EasyTest\\4\\ccl\\config\\test2.cfg 12346 5 C:\\EasyTest\\4\\bin\\runTC.exe C:\\Users\\syuniyar\\EclipseWS\Test3\\chart.html
it is working fine. However, when I modify the input from ...12346... to ...12346 12345..., I get such error:
Exception in thread "main" java.io.IOException: Cannot run program "5": CreateProcess error=2, The system cannot find the file specified
I also try with VM arguments but the option of System.getProperty() is only for single string.
I know why I get this error because it reads 12345 as 'it' which is not correct. What I wanna ask :
Is it possible to have an array as single argument in main method?
To directly answer your question, "Is it possible to have an array as [a] single argument in [a] main method?", no. The main method accepts arguments in the form of one array of String objects (usually called "args"). Each of these strings is considered an argument.
When executing the main method from the command line, these arguments come after the program name and are delimited by spaces. They are loaded into an array and passed into the main method.
As mentioned in the comments (esp. #Ismail Kuruca), if it is important to you to pass in several strings as one argument, you can concatenate the strings to make your arguments technically one String, and thereby treated as one argument.

identifier error when declaring object array for file

public static Vehicle[] fillArray(inputString) throws exception {
while(readRecords.ready()) {
Vehicle newVehicle;
checkType = readRecords.readLine();
if(checkType.equals("vehicle")) {
String ownersName = readRecords.readLine();
String address = readRecords.readLine();
String phone = readRecords.readLine();
String email = readRecords.readline();
newVehicle = new Vehicle(ownersName,address,phone,email);
list.add(newVehicle);
}
I am getting an <identifier> expected error. Signals at the inputString within the parenthesis.
any suggestions?
You need to tell what type the parameter is:
public static Vehicle[] fillArray(String inputString) throws Exception
Otherwise the compiler doesn't know if inputString is a string, an int, or some other object. It won't guess by the name.
You should specify a type for your parameter. Try this :
public static Vehicle[] fillArray(String inputString) throws exception

Categories