I am trying to read a CSV file with 20 columns which may or may not contain value but the problem is that I have to create 20 try catch in order to maintain the code flow in control manner. Like
String a = ""; loop
try{
a = list.get(0); // converted the csv to list of list and iterated in
}catch(NoSuchElementException e){}
and same for every other variable.The reason I have seperate try catch because In the below code
String a = "";
String b = "";
try{
a = list.get(0);
b = list.get(1);
}catch(NoSuchElementException e){}
If first line of try gave exception the second line will not execute.
So is there any alternate to these n number of try catch situation?
Thanks
You could create a helper method:
private String getField(List<String> list, int n) {
try {
return list.get(n);
} catch (NoSuchElementException e) {
return "";
}
}
String a = getField(list, 0);
String b = getField(list, 1);
EDIT:
Typically you wouldn't rely on exceptions if you do not have sufficient fields, the following achieves the same thing but subjectively feels cleaner:
private String getField(List<String> list, int n) {
if (n < list.size()) {
return list.get(n);
}
return "";
}
Related
I'm attempting to pull the 'Total Cash Flow From Operating Activities' figure from Yahoo Finance. The variable "s" can be any symbol in the SP500. For the most part, the desired output occurs. However, in some cases, like for AAPL, I can't figure out what it's printing or where it came from.
If "s" is A, the output is 711000000. Correct.
If "s" is AA, the output is 1674000000. Correct.
However, if "s" is AAPL, the output is -416542144. No clue where that comes from.
public class CashFlowStatement {
String cashFromOperatingActivities = "Total Cash Flow From Operating Activities";
public CashFlowStatement(String s) {
String cashFlowStatementURL = ("https://finance.yahoo.com/q/cf?s="+s+"+Cash+Flow&annual");
String cashFlowStatementTableName = "table.yfnc_tabledata1";
boolean foundLine = false;
String line;
int line2;
try {
Document doc = Jsoup.connect(cashFlowStatementURL).get();
for (Element table : doc.select(cashFlowStatementTableName)) {
for (Element row : table.select("tr")) {
if(foundLine == false) {
Elements tds = row.select("td");
for( int j = 0; j < tds.size() - 1; j++) {
if(tds.get(j).text().equals(cashFromOperatingActivities)) {
line = tds.get(j+1).text().replaceAll(",","");
line = line.substring(0,(line.length())-2);
line2 = Integer.parseInt(line)*1000;
System.out.println(line2);
foundLine = true;
}
}
}
}
}
}
catch (IOException ex) {
ex.printStackTrace();
}
catch (NumberFormatException ex) {
ex.printStackTrace();
}
}
}
You have an OVERFLOW! The value from the table is 59,713,000. When you multiply it by 1000 - line2 = Integer.parseInt(line)*1000; you get a number which is greater than MAXINT, thus the negative value. Try use long instead int for line2.
I had some success with this site, and I hope I find more excellent programmers to assist me.
So I am at my wit's end with this code. I am very new to programming, especially exceptions. I have looked very hard through my course material and sought help, but I have been quite unsuccessful. I am trying to create an improved parser that will override another parser. It reads a .txt file with student information of it including an ID, a name, a grade, and an optional email address and optional comment as tokens in a String separated by commas. The override checks for errors in each token and throws an exception called ParserException. The exception will check the code and then return an error message if the error is unfixable.
For example, if a student puts in an AB for the grade, the exception will flag and check if the input is a valid grade (which it is) and then return, if it is not, then it will throw a ParserException, in this case
throw new ParserException(ParserException.GRADE_INVALID_GRADE,lineIndex);
This shows that the does not work and sends out a message GRADE_INVALID on the line indexLine
I have a list of what I need to have as an output:
Any violation of the file format specified in the Input File Format Description section above should result in an ParcerException with an appropriate message
Duplicate IDs are not allowed
Grade values must be a float (92.0) or a letter grade and not an integer
I have all the code to correct and check for errors, but I cannot figure out how to get the try-catch to work. Here's is the override code:
#Override
public ParserResult parseLine(int lineIndex) {
String[] tokens = lines.get(lineIndex).split(",");
ArrayList<Integer> idList = new ArrayList<Integer>();
Integer studentId;
String name;
String grade;
String email;
String comments;
boolean isFloat;
float gradeFinal;
String editName;
studentId = new Integer(tokens[0]);
ParserResult result;
try{
return super.parseLine(lineIndex);
}
catch(ParserException e){
// Check reasonable number of tokens
if(tokens.length >= 3 && tokens.length <= 5){
name = tokens[1];
grade = tokens[2];
// Check the student ID
if(idList.contains(studentId)){
throw new ParserException(ParserException.DUPLICATE_ID, lineIndex);
}else{
idList.add(studentId);
}
// Check the grade
if(grade.trim().equalsIgnoreCase("A")){
gradeFinal = gradeA;
}else if(grade.trim().equalsIgnoreCase("AB")){
gradeFinal = gradeAB;
}else if(grade.trim().equalsIgnoreCase("B")){
gradeFinal = gradeB;
}else if(grade.trim().equalsIgnoreCase("BC")){
gradeFinal = gradeBC;
}else if(grade.trim().equalsIgnoreCase("C")){
gradeFinal = gradeC;
}else if(grade.trim().equalsIgnoreCase("CD")){
gradeFinal = gradeCD;
}else if(grade.trim().equalsIgnoreCase("D")){
gradeFinal = gradeD;
}else if(grade.trim().equalsIgnoreCase("F")){
gradeFinal = gradeF;
}else{
try{
Integer.parseInt(grade);
isFloat = false;
}
catch(Exception fl) {
isFloat = true;
}
if(isFloat){
if((Float.parseFloat(grade) < 100f) && (Float.parseFloat(grade) >= 0f)){
gradeFinal = Float.parseFloat(grade);
}else{
throw new ParserException(ParserException.GRADE_INVALID_GRADE,lineIndex);
}
}else{
throw new ParserException(ParserException.GRADE_INTEGER_VALUE,lineIndex);
}
}
// Check the name
if(name.split(" ").length > 3){
throw new ParserException(ParserException.UNKNOWN, lineIndex);
}else{
editName = name.trim().split(" ")[0];
}
result = new ParserResult(studentId, editName, gradeFinal);
// Checks the email
if(tokens.length >= 4){
email = tokens[3];
// Check for at sign
if(!email.contains("#")){
throw new ParserException(ParserException.UNKNOWN, lineIndex);
}
int count = 0;
// Counts number of # symbols
for(int i=0; i<email.length(); i++){
if(email.indexOf(i) == '#'){
count++;
}
}
if(count > 1){
throw new ParserException(ParserException.EMAIL_MULTIPLE_AT,lineIndex);
}
if(email.split(".").length == 2){
if(!(email.trim().split(".")[1].contains(".edu")) && !(email.trim().split(".")[1].contains(".com"))){
throw new ParserException(ParserException.EMAIL_NOT_EDU_OR_COM,lineIndex);
}else{
result.setEmail(email);
}
}
// Checks if email contains .com or .edu
// Checks the comments
if(tokens.length == 5){
comments = tokens[4];
result.setComment(comments);
}
}
return result;
}
}
// TODO Call Parser's parseLine() here to attempt to parse, catch any exceptions
return null;
}
The original parseLine that is overridden, but still used is:
public ParserResult parseLine(int lineIndex) {
String[] tokens = lines.get(lineIndex).split(",");
ParserResult result = new ParserResult(Integer.parseInt(tokens[0]),
tokens[1], Float.parseFloat(tokens[2]));
result.setEmail(tokens[3]);
return result;
}
Here is the main() file:
public static void main(String[] args){
// TODO Change the line below to use ImprovedParser
Parser parser = null;
try {
parser = new ImprovedParser(args[0]);
} catch (FileNotFoundException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
System.exit(-1);
}
List<ParserResult> results = parser.parse();
int count = results.size();
double sum = 0.0;
for (ParserResult result : results) {
sum += result.getGrade();
}
System.out.println("Number of valid input lines: " + results.size());
System.out.println("Number of invalid input lines: "
+ (parser.getLineCount() - results.size()));
System.out.println("Average grade: " + sum / count);
for (ParserResult result : results) {
System.out.println(result);
}
}
Lastly, here is the .txt file that is being read:
# student_id,name,grade,email
1234,Bob,92.0,bob#test.edu
4321,Alice,95.0,alice#test.edu
1111,Eve,80.0,eve#test.edu
1121,Barry,85.0,barrytest.edu
1131,Harry,86.0,h#rry#test.edu
1121,Larry,87.0,larry#test.edu
1141,Jim Song,88.0,jim#song.edu
1151,Jerry,77.0,jerry#test.net
1161,James,65.0,james#test.com
The last six inputs should cause exceptions, but I can't figure out how to organize it to work. The code ignores the line with # symbol.
Here is a sample successful output:
Number of valid input lines: 3
Number of invalid input lines: 0
Average grade: 89.0
1234, 92.0, Bob, bob#test.edu,
4321, 95.0, Alice, alice#test.edu,
1111, 80.0, Eve, eve#test.edu,
The major changes should be in the orverride method
Please help if you can, I sit at my desk still pondering possibilities, and your help will be most-appreciated.
Assuming ParseException has an error field being an int and someMethod() that throws ParseException:
try {
someMethod();
} catch (final ParseExeption ex) {
if (ex.getError() == ParseException.SOME_ERROR) {
// do something
} else if (ex.getError() == ParseException.OTHER_ERROR) {
// do something else
}
}
Note that it's usually better to use specific exceptions for specific error, something like SomeErrorParseException, OtherErrorParseException, ... (those can extends ParseException if you want) and try-catch like this:
try {
someMethod();
} catch (final SomeErrorParseException ex) {
// do something
} catch (final OtherErrorParseException ex) {
// do something else
}
Some reading: http://docs.oracle.com/javase/tutorial/essential/exceptions/index.html
It seems that there is no code to actually cause the catch clause in the first place. Try adding a throw new ParserException(STUFF_HERE); when an error has been detected while reading the file.
I'm having an issue with changing the values of a class variable within nested loops - I can't figure out why. I'm guessing it's because the variable is static. But it's a static method and because it's used for listing a User in a system from a file, it has to be static (I'm calling it from main method to read file to TreeMaps). Is it not possible to rewrite a static class variable from within a method? If it's possible - what the heck am I doing wrong?
public class Loan{
protected int noOfLoans;
protected int noOfReturns;
protected User user=new User();
protected static Book book= new Book();
protected Map <Integer, Book> currentLoans=new TreeMap <Integer, Book>();
protected Map <Integer, Book> returned=new TreeMap <Integer, Book>();
protected static Map<Integer, Loan> loanList=new TreeMap<Integer, Loan>();
public static void main(String[] args){
readLoans();
}
public static void readLoans(){
loanList.clear();
BufferedReader reader = null;
try {
reader=new BufferedReader(new FileReader("loans.txt"));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
String line = null;
try {
line = reader.readLine();
} catch (IOException e) {
e.printStackTrace();
}
while (line!=null) {
String[] splitOut=line.split("-");
String[] loan_User=splitOut[0].split(",");
String[] loan_CurrentLoans=splitOut[2].split(",");
String[] loan_Returned=splitOut[4].split(",");
Loan loan = new Loan();
loan.user.setFirstName(loan_User[0]);
loan.user.setSurname(loan_User[1]);
loan.user.setPersonalID(loan_User[2]);
for (int i = 1; i <= Integer.parseInt(splitOut[1]); i++) {
book.setName(loan_CurrentLoans[((Integer.parseInt
(splitOut[1])-1)*4)]);
book.setAuthorFirstname(loan_CurrentLoans[((Integer.parseInt
(splitOut[1])-1)*4)+1]);
book.setAuthorSurname(loan_CurrentLoans[((Integer.parseInt
(splitOut[1])-1)*4)+2]);
book.setISBN(loan_CurrentLoans[((Integer.parseInt
(splitOut[1])-1)*4)+3]);
loan.currentLoans.put(i, book);
}
for (int i = 1; i <= Integer.parseInt(splitOut[3]); i++) {
book.setName(loan_Returned[((Integer.parseInt
(splitOut[3])-1)*4)]);
book.setAuthorFirstname(loan_Returned[((Integer.parseInt
(splitOut[3])-1)*4)+1]);
book.setAuthorSurname(loan_Returned[((Integer.parseInt
(splitOut[3])-1)*4)+2]);
book.setISBN(loan_Returned[((Integer.parseInt
(splitOut[3])-1)*4)+3]);
loan.returned.put(i, book);
}
loan.setNoOfLoans(Integer.parseInt(splitOut[1]));
loan.setNoOfReturns(Integer.parseInt(splitOut[3]));
loanList.put(loanList.size()+1, loan);
try {
line=reader.readLine();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Here's an input line for reference:
John,Doe,8012311213-2-a book,Author,Authorson,1234567890123,another book,Author,Authorson,2345678901234-1-a returned book,Author,Authorson,3456789012345
What I'm hoping to get when printing above line:
Current Loans:
1. a book by Author Authorson (1234567890123)
2. another book by Author Authorson (2345678901234)
Returned Loans:
1. a returned book by Author Authorson (3456789012345)
What I'm currently getting:
Current Loans:
1. a book by Author Authorson (1234567890123)
2. a book by Author Authorson (1234567890123)
Returned Loans:
1. a book by Author Authorson (1234567890123)
And
readLoans();
System.out.println(loanList.get(2).currentLoans.get(1).toString());
System.out.println(loanList.get(2).currentLoans.get(2).toString());
returns
a returned book by Author Authorson (3456789012345)
a returned book by Author Authorson (3456789012345)
Which leads me to believe I actually cannot make instances of my static Book object, but have to make it non-static and try to create instances of the object within the method. If so - how do I do that?
From here, it's hard to understand how you can understand as much as you do, and yet be so confused, at the same time. I don't mean that to be insulting - just to say that I'm not at all sure I understand where you are.
Create instances by using new. So in your two loops, where you keep overwriting the one static book, instead you need a local variable that you assign a new book to and then set the fields on.
The problem isn't that your Book is static, the problem is more simply that it's the same object every time you change it during the loop. This does happen because you've declared it as a static field but you are on the wrong track thinking the way you are about it.
Let's simplify the problem and instead of a Book, use this to illustrate:
class AnObject {
int aValue;
}
And instead of IO, just loop some times and add it to a list:
class PersistenceOfChangesDemo {
static List<AnObject> theList = new ArrayList<AnObject>();
public static void main(String[] args) {
AnObject theObject = new AnObject();
for(int i = 1; i <= 3; i++) {
/* reassign the object's value */
theObject.aValue = i;
/* adds the same object each time */
theList.add(theObject);
}
/* theList is now of size 3
* but all its elements refer to the same object (theObject) */
for(AnObject anObject : theList) {
/* prints '3' every time
* because that was the last value assigned */
System.out.println(anObject.aValue);
/* prints 'true' every time */
System.out.println(anObject == theObject);
}
}
}
The solution is that you need to create a new object each time you want a new one:
class PersistenceOfChangesDemo {
static List<AnObject> theList = new ArrayList<AnObject>();
public static void main(String[] args) {
for(int i = 1; i <= 3; i++) {
/* make a new object each time */
AnObject anObject = new AnObject();
anObject.aValue = i;
theList.add(anObject);
}
/* theList now has references to 3 different objects */
for(AnObject anObject : theList) {
/* prints 1, 2, 3 */
System.out.println(anObject.aValue);
}
}
}
Per your comment, make sure you are creating the new instance for each time you put it in to the map:
for (int i = 1; i <= Integer.parseInt(splitOut[1]); i++) {
Book newBook = new Book();
newBook.setName(loan_CurrentLoans[((Integer.parseInt
(splitOut[1])-1)*4)]);
newBook.setAuthorFirstname(loan_CurrentLoans[((Integer.parseInt
(splitOut[1])-1)*4)+1]);
newBook.setAuthorSurname(loan_CurrentLoans[((Integer.parseInt
(splitOut[1])-1)*4)+2]);
newBook.setISBN(loan_CurrentLoans[((Integer.parseInt
(splitOut[1])-1)*4)+3]);
loan.currentLoans.put(i, newBook);
}
it's just Reference problem. All three are referring to same object static book so represent the same details which are inserted last.
The change is only create new object of Book() instead of using same object for different detail.
try below code
Loan loan = new Loan();
loan.user.setFirstName(loan_User[0]);
loan.user.setSurname(loan_User[1]);
loan.user.setPersonalID(loan_User[2]);
for (int i = 1; i <= Integer.parseInt(splitOut[1]); i++) {
book = new Book(); // added this line
book.setName(loan_CurrentLoans[((Integer.parseInt
(splitOut[1])-1)*4)]);
book.setAuthorFirstname(loan_CurrentLoans[((Integer.parseInt
(splitOut[1])-1)*4)+1]);
book.setAuthorSurname(loan_CurrentLoans[((Integer.parseInt
(splitOut[1])-1)*4)+2]);
book.setISBN(loan_CurrentLoans[((Integer.parseInt
(splitOut[1])-1)*4)+3]);
loan.currentLoans.put(i, book);
}
for (int i = 1; i <= Integer.parseInt(splitOut[3]); i++) {
book = new Book(); // added this line
book.setName(loan_Returned[((Integer.parseInt
(splitOut[3])-1)*4)]);
book.setAuthorFirstname(loan_Returned[((Integer.parseInt
(splitOut[3])-1)*4)+1]);
How I solved it;
public static void readLoans(){
// Reads the bookList and userList.
readBooks();
readUsers();
// Creates a new BufferedReader and tries to read "loans.txt"
BufferedReader reader = null;
try {
reader=new BufferedReader(new FileReader("loans.txt"));
}
// Catches exception if "books.txt" does not exist.
catch (FileNotFoundException e) {
e.printStackTrace();
}
String line = null;
// tries to read the first line and interpret it as a String.
try {
line = reader.readLine();
}
// Catches IOexception if any is thrown when trying to read line.
catch (IOException e) {
e.printStackTrace();
}
// Loop as long as "line" is not empty, i.e. as long as a Loan is read.
while (line!=null) {
// split the String "line" at every RegEx "-"
String[] splitOut=line.split("-");
// Create a String from the first index of the first split.
String user = splitOut[0];
/* Split the second and third index of the first split and create
* new Stringarrays from them.*/
String[] loans = splitOut[1].split(",");
String[] returns = splitOut[2].split(",");
User aUser = new User();
/* Find the user in the userList whose personal ID matches the
* String "user" that we created. This is the user that we want to
* create (a) loan/s and/or (a) returned loan/s for.*/
for (int i = 1; i < userList.size()+1; i++) {
if (userList.get(i).getPersonalID().equals(user)) {
/*Set the variables for the User.*/
aUser.setFirstname(userList.get(i).getFirstname());
aUser.setSurname(userList.get(i).getSurname());
aUser.setPersonalID(userList.get(i).getPersonalID());
aUser.setTelephone(userList.get(i).getTelephone());
aUser.setLoans(userList.get(i).getLoans());
aUser.setReturns(userList.get(i).getReturns());
// Create an ArrayList for Loans and Returns for every user
ArrayList<Loan> listOfloans = new ArrayList<Loan>();
ArrayList<Loan> listOfreturns = new ArrayList<Loan>();
// if the new user has any loans...
for (int j = 0; j < aUser.getLoans(); j++) {
for (int k = 1; k < bookList.size()+1; k++) {
/* ... find the "Book" object with the
* corresponding ISBN...*/
if (bookList.get(k).getIsbn().equals(loans[j*3])) {
// ...then create a new loan object for each...
Loan loan = new Loan();
// ...and set the variables of each loan...
loan.setTitle(bookList.get(k).getTitle());
loan.setAuthor_firstname(bookList.get(k).
getAuthor_firstname());
loan.setAuthor_surname(bookList.get(k).
getAuthor_surname());
try {
loan.setIsbn(bookList.get(k).getIsbn());
} catch (Exception e) {
e.printStackTrace();
}
loan.setMaxLoan(bookList.get(k).getMaxLoan());
loan.setOnLoan(bookList.get(k).getOnLoan());
loan.setAvailable(bookList.get(k).
getAvailable());
loan.setSignature(loans[j*3+1]);
loan.setTimestamp(loans[j*3+2]);
/* ...then add each one to the "listOfloans"
* ArrayList.*/
listOfloans.add(loan);
}
}
}
/* if the "listOfloans" ArrayList is not empty,
* add the loan to loanList with User as Key.*/
if (!listOfloans.isEmpty()) {
loanList.put(aUser, listOfloans);
}
// if the new user has any returned loans...
for (int j = 0; j < aUser.getReturns(); j++) {
for (int k = 1; k < bookList.size()+1; k++) {
/* ... find the "Book" object with the
* corresponding ISBN...*/
if(bookList.get(k).getIsbn().equals(returns[j*4])){
// ...then create a new loan object for each...
Loan loan = new Loan();
// ...and set the variables of each loan...
loan.setTitle(bookList.get(k).getTitle());
loan.setAuthor_firstname(bookList.get(k).
getAuthor_firstname());
loan.setAuthor_surname(bookList.get(k).
getAuthor_surname());
try {
loan.setIsbn(bookList.get(k).getIsbn());
} catch (Exception e) {
e.printStackTrace();
}
loan.setMaxLoan(bookList.get(k).getMaxLoan());
loan.setOnLoan(bookList.get(k).getOnLoan());
loan.setAvailable(bookList.get(k)
.getAvailable());
loan.setSignature(returns[j*4+1]);
loan.setTimestamp(returns[j*4+2]);
loan.setReturndate(returns[j*4+3]);
/* ...then add each one to the "listOfreturns"
* ArrayList.*/
listOfreturns.add(loan);
}
}
}
/* if the "listOfreturns" ArrayList is not empty,
* add the returned loan to returnList with User as Key.*/
if (!listOfreturns.isEmpty()) {
returnList.put(aUser, listOfreturns);
}
}
}
// tries to read the next line and interpret it as a String.
try {
line=reader.readLine();
}
// Catches IOexception if any is thrown when trying to read line.
catch (IOException e) {
e.printStackTrace();
}
}
// try to close the BufferedReader.
try {
reader.close();
}
// Catches IOexception if any is thrown when trying to close.
catch (IOException e) {
e.printStackTrace();
}
}
It was a problem with the instancing of the Book object and with objects and methods being static. I had to rewrite a few of the methods behind the scenes that were major problems. Thanks for all the help! =)
I wish to:
Reading in two files
Split the files into individual strings
Compare the two string lists and retrieve strings that are unique to a file.
At the moment I am running in to the problem of finding a way to call the two methods used to call in the files (one for each file) to the same method in order to be compared.
Both methods use a try-catch-while statement and if I try to read all of the entries after the while statement only a single is shown and not the entire list.
Is there a way to send parts of both methods as parameter to a single new method?
Here is the code for the program. I know that there are problems with the way that I am doing the program, but I am only doing it the way that I was taught.
File mainEmails = new File("Testrun.txt");
Scanner inputScanner = null;
int counter = 1;
String fullName = null;
String position = null;
String companyName = null;
String telNumber = null;
String emailAddress = null;
try
{
inputScanner = new Scanner(mainEmails);
}
catch(FileNotFoundException e)
{
System.out.println("File has not been found.");
}
while (inputScanner.hasNextLine())
{
String nextLine = inputScanner.nextLine();
String [] splitFile = nextLine.split(",");
for (int i = 0; i <splitFile.length;i++)
{
if(i==0)
{
fullName = splitFile[0];
}
else if(i==1)
{
position = splitFile[1];
}
else if(i==2)
{
companyName = splitFile[2];
}
else if(i==3)
{
telNumber = splitFile[3];
}
else if(i==4)
{
emailAddress = splitFile[4];
}
else if(splitFile[i] == null)
{
System.out.println("You have failed!");
}
}
}
public static void deletionList()
{
File deletionEmails = new File("Testrun1.txt");
Scanner inputScanner1 = null;
String deletionfullName = null;
String deletionposition = null;
String deletioncompanyName= null;
String deletiontelNumber = null;
String deletionemailAddress = null;
try
{
inputScanner1 = new Scanner(deletionEmails);
}
catch(FileNotFoundException e)
{
System.out.println("File has not been found.");
}
while (inputScanner1.hasNextLine())
{
String deletionnextLine = inputScanner1.nextLine();
String [] deletionsplitFile = deletionnextLine.split(",");
for (int i = 0; i <deletionsplitFile.length;i++)
{
if(i==0)
{
deletionfullName = deletionsplitFile[0];
}
else if(i==1)
{
deletionposition = deletionsplitFile[1];
}
else if(i==2)
{
deletioncompanyName = deletionsplitFile[2];
}
else if(i==3)
{
deletiontelNumber = deletionsplitFile[3];
}
else if(i==4)
{
deletionemailAddress = deletionsplitFile[4];
}
else if(deletionsplitFile[i] == null)
{
System.out.println("You have failed!");
}
}
}
}
What I am trying to do is to take the fullName, emailAddress from the first split and deletionfullName and deletionemailAddress from the second split and compare the first and second of each, respectively. Each file will have a number of fields in it, and I am only interested in the fullName and emailAddress fields.
It is quite confusing to understand how you are trying to implement your solution, so may I suggest you look at a different way of doing the whole read-and-compare process. For example, I would suggest doing something like this... (in psuedocode)
public void compareFiles(String file1, String file2){
// Read the lines of each file into String[] arrays
String[] file1Lines = readAndSplitIntoLines(file1);
String[] file2Lines = readAndSplitIntoLines(file2);
// compare the lines
for (int x=0;x<file1Lines.length;x++){
for (int y=0;y<file2Lines.length;y++){
if (file1Lines[x].equals(file2Lines[y])){
// match. set it to null
file1Lines[x] = null;
file2Lines[y] = null;
// break out of the inner loop and start comparing the next line
break;
}
}
// remove the duplicates (which are now null values), creating a smaller array of uniques.
String[] newFile1 = shrinkArrayByRemovingNulls(file1Lines);
String[] newFile2 = shrinkArrayByRemovingNulls(file2Lines);
}
Besides the fact that your question is not very clear, you have at least one glaring problem:
DO NOT use exception handling for logic! Exception handling should be only for exceptions.
Secondly, think about what you are really looking to do. In pseudocode it would look something like this:
list1 = split(file(name1).read())
list2 = split(file(name2).read())
list3 = unique(list1, list2)
What does your code look like?
I am trying to convert a Java function into equivalent Groovy code, but I am not able to find anything which does && operation in loop. Can anyone guide me through..
So far this is what I got
public List getAlert(def searchParameters, def numOfResult) throws UnsupportedEncodingException
{
List respList=null
respList = new ArrayList()
String[] searchStrings = searchParameters.split(",")
try
{
for(strIndex in searchStrings)
{
IQueryResult result = search(searchStrings[strIndex])
if(result!=null)
{
def count = 0
/*The below line gives me error*/
for(it in result.document && count < numOfResult)
{
}
}
}
}
catch(Exception e)
{
e.printStackTrace()
}
}
My Java code
public List getAlert(String searchParameters, int numOfResult) throws UnsupportedEncodingException
{
List respList = null
respList = new ArrayList()
String[] searchStrings = searchParameters.split(",")
try {
for (int strIndex = 0; strIndex < searchStrings.length; strIndex++) {
IQueryResult result = search(searchStrings[strIndex])
if (result != null) {
ListIterator it = result.documents()
int count = 0
while ((it.hasNext()) && (count < numOfResult)) {
IDocumentSummary summary = (IDocumentSummary)it.next()
if (summary != null) {
String docid = summary.getSummaryField("infadocid").getStringValue()
int index = docid.indexOf("#")
docid = docid.substring(index + 1)
String url = summary.getSummaryField("url").getStringValue()
int i = url.indexOf("/", 8)
String endURL = url.substring(i + 1, url.length())
String body = summary.getSummaryField("infadocumenttitle").getStringValue()
String frontURL = produrl + endURL
String strURL
strURL = frontURL
strURL = body
String strDocId
strDocId = frontURL
strDocId = docid
count++
}
}
}
result = null
}
} catch (Exception e) {
e.printStackTrace()
return respList
}
return respList
}
It seems to me like
def summary = result.documents.first()
if (summary) {
String docid = summary.getSummaryField("infadocid").getStringValue()
...
strDocId = docid
}
is all you really need, because the for loop actually doesn't make much sense when all you want is to process the first record.
If there is a possibility that result.documents contains nulls, then replace first() with find()
Edit: To process more than one result:
def summaries = result.documents.take(numOfResult)
// above code assumes result.documents contains no nulls; otherwise:
// def count=0
// def summaries = result.documents.findAll { it && count++<numOfResult }
summaries.each { summary ->
String docid = summary.getSummaryField("infadocid").getStringValue()
...
strDocId = docid
}
In idiomatic Groovy code, many loops are replace by iterating methods like each()
You know the while statement also exists in Groovy ?
As a consequence, there is no reason to transform it into a for loop.
/*The below line gives me error*/
for(it in result.document && count < 1)
{
}
This line is giving you an error, because result.document will try to call result.getDocument() which doesn't exist.
Also, you should avoid using it as a variable name in Groovy, because within the scope of a closure it is the default name of the first closure parameter.
I haven't looked at the code thoroughly (or as the kids say, "tl;dr"), but I suspect if you just rename the file from .java to .groovy, it will probably work.