Comparing information in nested loops and marking when they match - java

data is an array carrying:
observation1, observation2, observation3, observation4, observation5
stringarray2 an array which may contain any of the above, eg:
observation1, observation4
I am trying to add items into countryList, setting them true if they appear in both arrays, otherwise setting false.
I need help setting up the nested loops.
I currently have the below setup which is really close, but this only adds the last item in array 2 as true (eg, observation4)
Can you see where I am going wrong please?
while (data.moveToNext()){
if (data.moveToFirst()){
do{
observation = data.getString(1);
if (editing.equals("yes")) {
stringarray2
Boolean test = false;
for (String name:stringarray2)
{
if (observation.equals(name)){
test = true;
}else{
test = false;
}
}
Country country = new Country(null,observation,test);
countryList.add(country);
}else{
Country country = new Country(null,observation,false);
countryList.add(country);
}
}while(data.moveToNext());
}
}

Try this
if (data.moveToFirst())
{
do
{
observation = data.getString(1);
if (editing.equals("yes"))
{
stringarray2 //random word here?
Boolean test = false;
for (String name:stringarray2)
{
if (observation.equals(name))
{
test = true;
break;
}
}
Country country = new Country(null,observation,test);
countryList.add(country);
}
else
{
Country country = new Country(null,observation,false);
countryList.add(country);
}
}
while (data.moveToNext())
}

I think you problem is in your while and if condition.
With your first loop you have
while (data.moveToNext())
moveToNext() already checks if there is a next and moves to it, you shouldn't be moving to first again, just start using the value
You need something like
try {
while (data.moveToNext()) {
observation = data.getString(1);
if (editing.equals("yes")) {
stringarray2
Boolean test = false;
for (String name:stringarray2)
{
if (observation.equals(name)){
test = true;
}else{
test = false;
}
}
Country country = new Country(null,observation,test);
countryList.add(country);
}else{
Country country = new Country(null,observation,false);
countryList.add(country);
}
}
} finally {
data.close();
}
Assuming your inner logic is working fine.
P.S I added a try finally, because you need to close your cursor after your're done with the query result.

Related

Breaking without else statement

Each item has a unique code.
Item also have name it doesn't have to be unique.
Everything I add a code, if the code doesn't exist it will ask the name.
If the code does exists, it it will only print out the below statement and 'break';
System.out.println("Already exists");
But when I type the same item code again.
Not only it print out the statement, it also still ask me the name.
Here is my code
String code = //scannerobject;
for(Item item: items)
if(item..getCode().equals(code))) {
System.out.println("Already exists");
break;
}
String itemName = //scannerobject
item.add(new Item(code,itemName));
.getCode() is just return method from Item class
private String code;
public String getCode(){
return code;
}
Can someone explain to me?
Thanks.
If I understood correctly, before adding a new item you want to check if the code is fresh. So, you need to make sure the loop has been finished without break and all items code has been checked. For performance improvement, you may want to consider binary tree to check for used code in O(log n).
String code = //scannerobject;
boolean isFresh = true;
for(Item item: items) {
if(item.getCode().equals(code))) {
System.out.println("Already exists");
isFresh = false;
break;
}
}
if(isFresh){
String itemName = //scannerobject
items.add(new Item(code,itemName));
} else {
//maybe exit or continue to outer while
}
You need to check if the object has not been found with some condition once the loop terminates.
String code = //scannerobject;
int i;
for(i = 0; i < items.size(); i++) {
if(items.get(i).getCode().equals(code))) {
System.out.println("Already exists");
break;
}
}
if(i == items.size()) {
String itemName = //scannerobject
items.add(new Item(code, itemName));
}
We need to check the flag and ask for the itemName outside the for loop so that every item is checked.
String code = //scannerobject;
Boolean flag=true;
for(Item item: items) {
if(item..getCode().equals(code))) {
System.out.println("Already exists");
flag = false;
break;
}
}
if(flag){
String itemName = //scannerobject
item.setName(itemName);
}

Unable to write values into excel using multiple workbook.write methods

The below code is working without any runtime error if I call the owb.write(fileOut) and fileOut.close() method only once at at the ending (commented as write and close positioning) but the problem here is that the first value to be set when k=1, is not being printed in the workbook. It works fine when the iteration is in other columns and k=1.Only the first iteration is not being printed. Rest of the values are being set correctly.
I tried using multiple workbook.write() method. If you look at the below code, commented as [1], I had to invoke owb.write(fileOut) separately in the if condition(commented as if condition[1]) and else condition(commented as else condition [2]) because as I said, first value was not getting set in the workbook. I am getting the following runtime error while trying to execute the code in this scenario: Fail to save: an error occurs while saving the package : The part /docProps/app.xml fail to be saved in the stream with marshaller org.apache.poi.openxml4j.opc.internal.marshallers.DefaultMarshaller#3740f768
for(int i=0;i<noOfCols1;i++)
{
for(int j=1;j<=noOfRows1;j++)
{
value1 = formatter.formatCellValue(sheet1.getRow(j).getCell(i));
for(int m=1;m<=noOfRows2;m++)
{
value2 = formatter.formatCellValue(sheet2.getRow(m).getCell(i));
value1= value1.trim();
value2=value2.trim();
int value2Position = sheet2.getRow(m).getCell(i).getRowIndex();
if(!positions.contains(value2Position))
{
if(value1.contentEquals(value2))
{
positions.add(value2Position);
matched = true;
}
else{
matched = false;
}
}
if(matched==true)
{
break;
}
}
if(matched == false)
{
int k=1;
if(cFilledPositions.isEmpty()) //If condition[i]
{
rowHead = sheet.createRow((short)k);
rowHead.createCell(i).setCellValue(value1);
owb.write(fileOut); //[1]
}
else //else condition [1]
{
int l = cFilledPositions.size()-1;
k = cFilledPositions.get(l)+1;
rowHead = sheet.createRow((short)k);
rowHead.createCell(i).setCellValue(value1);
owb.write(fileOut);
}
cFilledPositions.add(k);
}
matched = false;
}
cFilledPositions.clear();
positions.clear();
}
//write and close positioning
fileOut.close();
I tried debugging and found that the createRow() method deletes the values previously created if called again on the same row.
To elaborate this, suppose the sheet.createRow() sets the value of a cell in the first iteration, and when it finishes its iteration in the j for loop, the cFilledPositions list is cleared and while it comes back after going to the main loop, 'cFilledPositionswill be empty and the integerkwill again be initialized to1. This is whencreateRow(k)` which is 1 is called again. This would flush out the previously existing values in the 1st row. I am trying to figure out a work around for this and will edit my answer with the solution if I my code works.
Below was the work around. I checked if the row is empty. The createRow function is called only when the row is empty. I have added the comments for the new code.
for(int i=0;i<noOfCols1;i++)
{
for(int j=1;j<=noOfRows1;j++)
{
value1 = formatter.formatCellValue(sheet1.getRow(j).getCell(i));
for(int m=1;m<=noOfRows2;m++)
{
value2 = formatter.formatCellValue(sheet2.getRow(m).getCell(i));
value1= value1.trim();
value2=value2.trim();
int value2Position = sheet2.getRow(m).getCell(i).getRowIndex();
if(!positions.contains(value2Position))
{
if(value1.contentEquals(value2))
{
positions.add(value2Position);
matched = true;
}
else{
matched = false;
}
}
if(matched==true)
{
break;
}
}
if(matched == false)
{
int k=1;
if(cFilledPositions.isEmpty())
{
try{
isEmpty = checkIfRowIsEmpty(sheet,k,formatter);
if(isEmpty)
{
rowHead = sheet.createRow(k);
}
rowHead.createCell(i).setCellValue(value1);
}
catch (Exception e){
try{
rowHead = sheet.createRow(k);
rowHead.createCell(i).setCellValue(value1);
}
catch (Exception e1){
}
}
}
else
{
int l = cFilledPositions.size()-1;
k = cFilledPositions.get(l)+1;
try{
isEmpty = checkIfRowIsEmpty(sheet,k,formatter);
if(isEmpty)
{
rowHead = sheet.createRow(k);
}
rowHead.createCell(i).setCellValue(value1);
}
catch (Exception e)
{
try{
rowHead = sheet.createRow(k);
rowHead.createCell(i).setCellValue(value1);
}
catch (Exception e1){
}
}
}
cFilledPositions.add(k);
}
matched = false;
}
cFilledPositions.clear();
positions.clear();
}

Using a for-each loop to return largest value in arraylist

I'm having trouble writing a for-each loop that searches the arraylist and returns the county's name within the continent that has the highest gdp. Here's my code for it right now. (ElementsList is the original ArrayList)
public Country highestGdp(String continent) {
boolean flag;
for (Country cont : ElementsList) {
if (cont.getContinent().equals(continent)) {
ArrayList<Country> TMP1 = new ArrayList<Country>();
TMP1.add(cont);
for (Country gdp : TMP1) {
double max = 0;
if (max < gdp.getGDP()) {
max = gdp.getGDP();
}
if (gdp.getGDP() == max) {
ArrayList<Country> TMP2 = new ArrayList<Country>();
TMP2.add(gdp);
}
return gdp;
}
}
}
return null;
}
Each time you find a country in the right continent, you can check to see if it is greater than the max so far. Don't need to loop through all of them each time.
public Country highestGdp(String continent) {
boolean flag;
Country maxCountry = null;
for (Country cont : ElementsList) {
if (cont.getContinent().equals(continent)) {
if (maxCountry == null) maxCountry = cont;
if (maxCountry.getGDP() < gdp.getGDP()) {
maxCountry = cont;
}
}
}
return maxCountry;
}
Sorry for saying it but Your code is a little messy ;)
To shortly solve Your problem, try to move max declaration before the loop like this:
[...]
double max = 0;
for(Country gdp : TMP1){
[...]
We can see that TMP2 is completely useless, remove it:
// ArrayList<Country> TMP2 = new ArrayList<Country>();
// TMP2.add(gdp);
You create TMP1 list always with only 1 element and then iterate over it. This is also useless, You can do the code directly on the element You are adding to the list.
First iteration over ElementList is a list of Country elements, but the element You iterate is called cont (=continent) which is a Continent and not the Country. Is it intended to use Country class to cover both: Countries and Continents? Do You plan to have a tree structure like "Continents contains many Countries"?
Final code to solve problem from Your original question should be like this:
public Country highestGdp(String continent){
Country countryWithMaxGdp = null;
for(Country cont: ElementsList ){
if(cont.getContinent().equals(continent)){
if(countryWithMaxGdp == null || countryWithMaxGdp.getGDP() < cont.getGDP()){
countryWithMaxGdp = cont;
}
}
}
return countryWithMaxGdp;
}

Checking if the entity is on the list

I'm programming a friend system for my "forcefield" in a game called Minecraft. My idea is that if the player is not on the friend list, the player will it attack. The follow is all the code for my friend system and forcefield.
public static boolean friends = true;
public static List friend = new ArrayList();
public static void friendsList(){
if(friends){
try{
File file = new File("friends.txt");
BufferedWriter bufferedwriter = new BufferedWriter(new FileWriter(file));
for(int i = 0; i < friend.size(); i++){
bufferedwriter.write((new StringBuilder()).append((String) friend.get(i)).append("\r\n").toString());
}
bufferedwriter.close();
}
catch(Exception exception){
System.err.print(exception.toString());
}
}
Forcefield:
if(Camb.nocheat){
if (Camb.killaura)
{
hitDelay++;
for(Object o: mc.theWorld.loadedEntityList){
Entity e = (Entity)o;
if(e != this && *******CHECK IF PLAYER IS NOT ON LIST******* && e instanceof EntityPlayer &&getDistanceToEntity(e) < 3.95D){
if(e.isEntityAlive()){
if(hitDelay >= 4){
if(Camb.criticals){
if(mc.thePlayer.isSprinting()==false){
if(mc.thePlayer.isJumping==false){
if(mc.thePlayer.onGround){
mc.thePlayer.jump();
}
}
}
}
swingItem();
mc.playerController.attackEntity(this, e);
hitDelay = 0;
break;
}
}
}
}
}
}
Adding/removing/clearing the friend list:
if(par1Str.startsWith("&friendadd")){
Camb.friends = true;
String as0[] = par1Str.split("");
Camb.friend.add(as0[1]);
mc.thePlayer.addChatMessage((new StringBuilder()).append("\2479[CAMB]\247e Added Friend.").append("").toString());
Camb.friendsList();
Camb.friends = false;
return;
}
if(par1Str.startsWith("&friendremove")){
Camb.friends = true;
String as0[] = par1Str.split("");
Camb.friend.remove(as0[1]);
mc.thePlayer.addChatMessage((new StringBuilder()).append("\2479[CAMB]\247e Removed Friend.").append("").toString());
Camb.friendsList();
Camb.friends = false;
return;
}
if(par1Str.startsWith("&friendclear")){
Camb.friends = true;
Camb.friend.clear();
Camb.friendsList();
mc.thePlayer.addChatMessage("\2479[CAMB]\247e Friends list cleared.");
return;
}
par1Str is the string entered in chat. Basically commands. Additionally, the &friendremove system is broken as well. I'm unsure why.
Thanks,
Brad
Use friend.contains(e). It checks for equality albeit by iteration.
Returns true if this list contains the specified element. More formally, returns true if and only if this list contains at least one element e such that (o==null ? e==null : o.equals(e)).
I'm not too familiar with the SDK you're using to make this, but you can use this oneliner to check if an element is in an ArrayList.
myList.contains("friendname");
http://docs.oracle.com/javase/6/docs/api/java/util/ArrayList.html#contains(java.lang.Object)

Calling Two Different Methods into One Method in Java

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?

Categories

Resources