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);
}
Related
I've been following Tim Buchalka's course Java Programming Masterclass for Software Developers and I've been modifying his program from lesson 118.
I want to update my list at the runtime while using the list iterator (navigate method). The program runs fine, but if I update my list, Java throws an error: ConcurrentModificationException
I have come up with the following solution:
Whenever a user performs a modification of the list, other methods run, and update the list and pass it to the navigate() method. By doing this, my program enters multi-level nested methods, and the problem comes up when a user wants to exit from the program (case 0: in navigate() method). User has to press 0 as many times as many nested methods were ran.
My initial idea was to count how many times navigate() was nested, then using for loop return as many times as it was nested. But later I understood it does not make sense
What can I do to exit from the program by using case 0: just once?
package com.practice;
import java.util.LinkedList;
import java.util.ListIterator;
import java.util.Scanner;
public class List extends Traveler {
private LinkedList<String> linkedList;
private String tripName;
public List(String travelerName, int travelerAge, String tripName) {//it has to have same amount of parameters or more with super constructor!
super(travelerName, travelerAge);
this.tripName = tripName;
this.linkedList = new LinkedList<>();
}
public List(){} //it has to have same amount of parameters or more with super constructor!
public LinkedList<String> getLinkedList() {
return linkedList;
}
public String getTripName() {
return tripName;
}
private void removeCity(LinkedList<String> cityList, String deletedCity) {
if(cityList.remove(deletedCity)) {
System.out.println(deletedCity + " has been removed");
} else System.out.println("Could not find the city you want to remove");
List.navigate(cityList);
}
//adds a new city and update the list without an error
private void noExceptionError(LinkedList<String> listOfCities, String cityName) {
ListIterator<String> listIterator = listOfCities.listIterator();
while((listIterator.hasNext())) {
int comparison = listIterator.next().compareTo(cityName);
if(comparison == 0) {
System.out.println(cityName + " has been already added to the list");
return;
} else if(comparison > 0) {
listIterator.previous();
break;
}
}
listIterator.add(cityName);
List.navigate(listOfCities);
}
private void loadToList(LinkedList<String> listOfCities) {
alphabeticallyAdd(listOfCities, "Poznan");
alphabeticallyAdd(listOfCities, "Gdansk");
alphabeticallyAdd(listOfCities, "Szczeczin");
alphabeticallyAdd(listOfCities, "Warszawa");
alphabeticallyAdd(listOfCities, "Lodz");
alphabeticallyAdd(listOfCities, "Wroclaw");
List.navigate(listOfCities);
}
private void alphabeticallyAdd(LinkedList<String> listOfCities, String cityName) {
ListIterator<String> listIterator = listOfCities.listIterator(); //just a setup; doesn't point to the 1st element
while((listIterator.hasNext())) {
//if value is greater, the word that is in the list is alphabetically bigger, thus, put it before the list element
//if equal, it is duplicate! return false
// else it is less, thus, we have to move further in the list
int comparison = listIterator.next().compareTo(cityName); //retrieves the 1st value and goes to the next
if(comparison == 0) {
System.out.println(cityName + " has been already added to the list");
return;
} else if(comparison > 0) {
listIterator.previous(); //because we've used .next() in the int comparison initialization
listIterator.add(cityName); //don't use linkedList.add because it doesn't know the int comparison, so cannot properly add!!!
return;
}
}
listIterator.add(cityName); //adding at the end of the list
}
public static void navigate(LinkedList<String> listOfCities) {
Scanner userChoice = new Scanner(System.in);
List travelListObject = new List();
ListIterator<String> listIterator = listOfCities.listIterator();
boolean goingForward = true;
while(true) {
Main.menu();
int choice = userChoice.nextInt();
userChoice.nextLine(); //takes care of enter key problem
switch(choice) {
case 0:
System.out.println("Goodbye");
//possible improvement
/* for(int i = 0; i <= List.amountNestedMethods; i++) {
return;
}*/
return;
case 1: //moving forward
if(!goingForward) {
if(listIterator.hasNext()) {
listIterator.next();
}
}
if(listIterator.hasNext()) {
System.out.println(listIterator.next());
Traveler.setNumberVisitedCities(Traveler.getNumberVisitedCities() + 1);
goingForward = true;
} else {
System.out.println("No more cities in the list");
goingForward = false;
}
break;
case 2: //moving back
if(goingForward) {
if(listIterator.hasPrevious()) {
listIterator.previous();
}
goingForward = false;
}
if(listIterator.hasPrevious()) {
Traveler.setNumberVisitedCities(Traveler.getNumberVisitedCities() + 1);
System.out.println(listIterator.previous());
} else {
System.out.println("You're at the beginning of the list");
goingForward = true;
}
break;
case 3:
Main.printCities(listOfCities);
break;
case 4:
break;
case 5:
System.out.println("Write new city");
String addedCity = userChoice.next();
travelListObject.noExceptionError(listOfCities, addedCity);
break;
case 6:
System.out.println("Write the city you want to delete");
String deletedCity = userChoice.next();
travelListObject.removeCity(listOfCities, deletedCity);
break;
case 7:
System.out.println("You have been in " + Traveler.getNumberVisitedCities() + " cities in total");
break;
case 9:
travelListObject.loadToList(listOfCities);
break;
default:
System.out.println("Something weird happened. Try to choose an option again");
}
}
}
}
If you want to exit the program you can simply call System.exit(n), where the n is an integer return code (the convention being that code 0 means normal execution and other values indicate some sort of error).
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.
public void searchWatch(long srch){
long s = srch;
boolean found = false;
for(int i = 0; i<watchStore.size();i++){
Watch fd = watchStore.get(i);
if(fd.equals(s)){
System.out.print("item found");
found = true;
}
if(!found){
System.out.println("no such record");
}
}
}
this is a code fragment from one of my class. my question here is I want to test a particular input of type long against an arraylist of type Watch. whether the serial number exist in the arraylist.
but it fails due to an error " .equal() on incompatible types" whats the problem with the above code
the following is the revised code
public Watch findWatchBySerialNumber(long srch){
long s = srch;
Watch watch = null;
for(int i = 0; i<watchStore.size();i++){
watch = watchStore.get(i);
if(watchStore.contains(s)){ // this pop an error called suspicious call to java.utit.Collection.contains
System.out.print("item found");
return watch;
}
}
System.out.print("item not found");
return null; // watch is not found.
}
please how can I fix that.
When u do if(fd.equals(s)){ you are trying to match A String with another object of type Watch and that is why you are getting the error.
You need to get the String representation of fd and then match it with s.
'fd' is an object of Watch and 's' is an object of String. Since these are two different classes, running a fd.equals(s) will throw the error.
To get it working, try overriding the toString() method in the Watch class and then do
fd.toString().equals(s)
If you try to find by serial number then:
public void searchWatch (long srch){
boolean isFound = false;
Watch fd = null; // declaring variable out of the loop is better.
for(int i = 0; i<watchStore.size();i++){
fd = watchStore.get(i);
if(fd.getSerialNumber.equals(srch)){
System.out.print("item found");
isFound = true;
}
if(!found){
System.out.println("no such record");
}
}
}
My suggestion: if you write your method name as search or find you should return an object. If you only need to know "is it exist", you can give a name to your method: isWatchExist() and add a boolean return type.
public boolean isWatchExist (long serialNumber) {
Watch watch = null; // declaring variable out of the loop is better.
for(int i = 0; i < watchStore.size(); i++){
watch = watchStore.get(i);
if(watch.getSerialNumber.equals(serialNumber)){
System.out.print("item found");
return true;
}
}
System.out.println("no such record");
return false;
}
If you need to find object, you should add a return type of your object. Give a name that describes your method goal clearly.
public Watch findWatchBySerialNumber (long serialNumber){
boolean isFound = false;
Watch watch = null; // declaring variable out of the loop is better. and name of you variable should describe your object, same name is better.
for(int i = 0; i < watchList.size(); i++){ // your list name should be "watchList".
watch = watchList.get(i);
if(fd.getSerialNumber.equals(serialNumber)){
System.out.print("item found");
return watch;
}
}
System.out.print("item not found");
return null; // watch is not found.
}
Replace:
Watch fd = watchStore.get(i);
With:
Watch fd = watchStore.get(i);`
// use getter method
String fdString = fd.getSerial();
if(fdString.equals(s)){
System.out.print("item found");
found = true;
}
See if that helps.
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)
I am calling a method that passes in a variable. I want to be able to compare this variable to all the items in an ArrayList to see if there is a match.
This is my code...
private boolean input;
private ArrayList chcekItem = new ArrayList();
public void setAction(String action) {
input=true;
if (getChcekItem().isEmpty()) {
getChcekItem().add(action);
}
else {
Iterator iterators = getChcekItem().iterator();
while (iterators.hasNext()) {
if (iterators.next()==action) {
System.out.println(iterators.next()+"="+action);
input=false;
}
}
if (input) {
getChcekItem().add(action);
System.out.println("The item " + action + " is Successfully Added to array");
}
else{
System.out.println("The item " + action + " is Exist");
}
}
}
My code isn't working as I had expected. Could someone please help me fix the problem.
I take it that the checkItem variable is a List of Strings, thus it should be defined like this:
private List<String> checkItem = new ArrayList<String>();
When comparing an String you don't use string1==string2 but string1.equals(string2);
So
(iterators.next()==action)
should be:
(iterators.next().equals(action))
Remember to check the string for null values.
So the whole code could look like this:
private boolean input;
private List<String> chcekItem= new ArrayList<String>();
public void setAction(String action) {
input=true;
if (getChcekItem().isEmpty()) {
getChcekItem().add(action);
} else {
//Foreach loop instead of an iterator ;)
for(String item : chcekItem) {
if(item.equals(action)) {
System.out.println(item+"="+action);
input=false;
//We can jump out of the loop here since we already found a matching value
break;
}
}
if (input) {
getChcekItem().add(action);
System.out.println("The item " + action + " is Successfully Added to array");
}else{
System.out.println("The item " + action + " is Exist");
}
}
}
}