Iam trying to compare each string or int in array with another array then print the results according to whether the string exists or not in the other array: Below is the whole code: I get error in the for loops when trying to comparing two values using .equals(not sure if its right method,,... I am new to this) Please help!
public class comparer {
public void compare (){
ArrayList NameofFileinDir = new ArrayList ();
ArrayList Stocks = new ArrayList();
// populate array with files names in dir
try {
Scanner reads = new Scanner (new File("G:/Programming/StockDataDownload/NameOfFileinDir.txt"));
String FileCode;
while (reads.hasNext()){
FileCode = reads.nextLine(); //read next line
NameofFileinDir.add(FileCode);
}
reads.close();
}
catch (IOException e) {
}
// populate array with original stocks
try {
Scanner reads = new Scanner (new File("G:/Programming/StockDataDownload/AllSecurities.txt"));
String StockCode;
while (reads.hasNext()){
StockCode = reads.nextLine(); //read next line
Stocks.add(StockCode);
}
reads.close();
for(int i = 0; i < Stocks.size(); i++) {
for (int j = 0; j < NameofFileinDir.size(); j++) {
if (Stocks[i].equals(NameofFileinDir[j])) > 0) {
System.out.println("Stock:" + Stocks[i]);}
else{
System.out.println("Stock not in files:" + Stocks[i]);
}
}
}
}
catch (IOException e) {
}
}}
An ArrayList
is not an array
. The syntax to get the element at index i
is different: list.get(i)
vs arr[i]
. Read up on ArrayList
, especially the get(int)
method.
Research what String.equals(Object)
returns and what that means. Glancing at Object.equals(Object)
also wouldn't hurt, since every object in java gets this one by default.
Consider using a foreach loop instead of the old for loop. The old for loop can be crazy useful, but there's no point here. Look how much cleaner this is:
for (String stock : Stocks) {
for (String filename : NameofFileinDir) {
if (stock.equals(filename)) {
System.out.println(" Stock: " + stocks);
} else {
System.out.println("Stock not in files: " + stocks);
}
}
}
ArrayList Stocks = new ArrayList();
. Cool. So you have an ArrayList
. Of what?! Now, this isn't technically illegal, but if your java compiler supports type parameters, you really need to use them. Write instead List<String> stocks = new ArrayList<String>()
. Now everyone reading your code immediately knows what the list holds. Also, the compiler will guarantee that your list will only contain strings. If you try and do something insane or stupid, like throwing some Integers and Maps into the list with your strings, the compiler will puke.
If what you print in the if..else is what you mean, your logic is fatally flawed. You print "stock not in list of files" if the current stock string and file string you happen to be comparing are not equal. But logically, does this mean none of the stock strings and file strings are equal?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With