user13339898
user13339898

Reputation:

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.

Upvotes: 2

Views: 108

Answers (3)

Amir MB
Amir MB

Reputation: 3418

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
}

Upvotes: 1

Arvind Kumar Avinash
Arvind Kumar Avinash

Reputation: 79095

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

Upvotes: 1

Dheeraj Joshi
Dheeraj Joshi

Reputation: 1582

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

Upvotes: 0

Related Questions