My code for deleting a player of a doubly linked list works right, but the System.out.print statements don't.
I placed System.outs.print statements before the removeFirst and removeLast because I don't know of a way to output the data that was removed in the nodes so I print it out before I remove.
I know my current method is bad design but I'm unsure of what function to use.
What conditions do I check for in an if-statement to see if the node has removed successfully?
else if (mChoice.startsWith("4")) {
System.out.println("What do you want to delete?");
mChoice = in.nextLine();
if (mChoice.contains("first")) {
System.out.println("Removed first player " + rBook.mHead.getData());
rBook.removeFirst();
}
else if (mChoice.contains("last")) {
System.out.println("Removed last player " + rBook.mHead.mPrev.getData());
rBook.removeLast();
}
else {
rBook.remove(rBook.searchByName(mChoice));
// System.out.println(rBook.get() + " removed."); this line
}
If you dont want to change your Player class and its functions try this:
else if (mChoice.startsWith("4")) {
System.out.println("What do you want to delete?");
mChoice = in.nextLine();
Player deleted;
if (mChoice.contains("first")) {
deleted = rBook.mHead.getData();
rBook.removeFirst();
System.out.println("Removed first player " + deleted);
}
else if (mChoice.contains("last")) {
deleted = rBook.mHead.mPrev.getData();
rBook.removeLast();
System.out.println("Removed last player " + deleted );
}
else {
deleted = rBook.searchByName(mChoice);
rBook.remove(searchByName(mChoice));
System.out.println(deleted + " removed.");
}
I would suggest that you modify your remove() function to return the element you just removed. So the code you're looking at would look like:
Player deleted = rBook.remove(rBook.searchByName(mChoice));
System.out.println(deleted.get() + " removed.");
If you want to store which elements of the list have been removed (to print or undelete them later, for example), then a better design would be either
only flagging these elements as removed, or
moving them into another, "history" list.
Which of these solutions is better depends on the problems you want to solve.
Related
User input from scanner method to array of 5 indexes also gives user ability to delete any index matching with string from one of the index.
ALL I want to achieve in this is in this while loop I would like to settle city (option 1), which means creating one as you can probably see from my code. This is where user will type any name they like no restrictions. once they settle the city loops starts again. However it does remember that user created a city earlier. I can have upto 5 cities. There is cost associate with settling new city. I know how to do those conditionals. I am just not sure about this string array.
ArrayList or Array class is not allowed.
where as, option 2 I can demolish any of the city i have created by giving user lists of city they have made earlier. I have to keep minimum of at least one city.
IF you are wondering then this is based on Civilization game.
Please ask for clarification as this may not be
straight forward. thanks
while (playing) {
System.out.println("\nPlease make your selection!");
System.out.println("\n1. Settle a City"
+ "\n2. Demolish a City"
+ "\n3. Build Militia"
+ "\n4. Research Technology"
+ "\n5. Attack Enemy City"
+ "\n6. End Turn\n");
String gameChoice = userinput.nextLine();
if (gameChoice.equals("1")) {
System.out.println("\nWhat would you like to"
+ " name your city?");
String cityname = userinput.nextLine();
cityname = cityNames[0];
} else if (gameChoice.equals("2")) {
System.out.println("What city would you like to demolish?");
for (int i = 0; i < 5 ; i++) {
System.out.print(cityNames[i]);
System.out.print("");
}
} else if (gameChoice.equals("3")) {
System.out.println("You have military points");
} else if (gameChoice.equals("4")) {
System.out.println("You have Research Technology points");
} else if (gameChoice.equals("5")) {
System.out.println("You have zero points");
} else {
System.out.println(" Thanks for playing ");
}
playing = false;
}
First, here:
String cityname = userinput.nextLine();
cityname = cityNames[0];
You are assigning cityname to user input and then you are assigning it to something in cityNames array, that doesn't make sense, maybe you pasted wrong or something, but just in case, this should be the other way around, like this:
cityNames[0] = cityname;
You have playing = false at the end so the loop is gonna just end when user types the city name, you need to either remove this playing = false or use continue; after cityNames[0] = cityName;, that's gonna go to the next iteration of a loop, without going all the way down to playing = false.
Following code written in Java
public static void main (String [] args) throws Exception
{
ordListe ol = new ordListe();
ol.lesBok("navn.text");
ol.leggTilOrd("hello");
ol.leggTilOrd("Hello");
Is my main method. This is about reading from file and adding to a arraylist(dictionary). ''Hello'' and "hello" is supposed to be the same word, and in the code under, it should increase the count of that word.
for (int i = 0; i < ordListe.size(); i++)
{
if (ordListe.toString().contains(s))
{
if (ordListe.get(i).toString().equalsIgnoreCase(s))
{
ord.oekAntall();
System.out.println("'" + s + "' That word is found and there are " + ord.hentAntall() + " of that word now in dictionary.");
break;
}
}
else
{
Ord ny = new Ord(s);
ordListe.add(ny);
System.out.println("'" + s + "' This word is added. " + ny.hentAntall() + " of this word in dictionary.");
break;
}
}
So this is a part of my code. From the main method I add words like ol.leggTilOrd("hello"); leggTilOrd is my method where the code right above is taken from. This is the part of the code that adds words to the dictionary/arrayList and checks if inputwords already exists. I have no problem with anything else than the specific if (ordListe.get(i).toString().equalsIgnoreCase(s)) part. If a word exist in the arrayList, I'm supposed to increase the count of that word. If not, I add the word in the arraylist (ordListe). The problem is that even if I add ol.leggTilOrd("hello") or ol.leggTilOrd("Hello"); with capital 'H', I can't get to recognize it as the same word even if I use the statements above. How do I do this, any other possibilites? This is my last possible effort, after many attempts earlier.
If there are anything questionable above, just tell me.
Change both strings to lower case before comparing and then comapare..it will help you and is easier!!! Use toLower function and then compare
The problem is this line:
if (ordListe.toString().contains(s))
Because 1) you do not compare the lowercase or uppercase versions of the two strings and 2) you probably not overrided toString so it returns the items in the list as you probably expect. Put this function in your ordListe class assuming that your ordliste extends arraylist:
public boolean containsIgnoreCase(String item) {
for(int i = 0; i < size(); i++) {
if (get(i).toString().equalsIgnoreCase(item)) {
return true;
}
}
return false;
}
Now you can call containsIgnoreCase to determinate if there is a specific item in the list ignoring the case
Hello Everyone i am creating a game mode for Bukkit and am encountering a problem that at the moment seems to baffling me. Perhaps i am simply over looking something so i would very much appreciate it if i could have another pair of eyes look at this segment of code. Here is my situation i have a command that creates a Game. This is a class Type. Every time the /newgame command is used it adds it to a ArrayList. Now it is supposed to check to see if a game with its name already exists. It only works for the first game name. so if i make a game called "game1" and then try to make "game1" again it returns "Can not create game with the name of game1" but when i make another one for example if i add the game"game2" and then i make "game2" again it allows it to be created. It only appears to working on the first game made. If someone could help it would be of much help so thanks in advance.
Note: The Main.games.size() always goes up so the games are being created but only the first game can not be created more then once any game after that can have the same name for some reason.
Here is the code Snippet in my CommandExecuter
if (cmd.equalsIgnoreCase("newgame")){
Player player = sender.getServer().getPlayer(sender.getName());
if (Main.games.size() == 0){
Main.games.add(new Game(args[0]));
player.sendMessage(ChatColor.GREEN + "Game Created. To join Type " + ChatColor.ITALIC + "/join " + args[0]);
return true;
}else{
//Loop and Check
Game game;
for (int i = 0; i < Main.games.size(); i++){
game = Main.games.get(i);
if (game.getName().equalsIgnoreCase(args[0]) == false){
Main.games.add(new Game(args[0]));
player.sendMessage(ChatColor.GREEN + "Game Created. To join Type " + ChatColor.ITALIC + "/join " + args[0]);
//debug
player.sendMessage(Main.games.size() + ""); // + "" id
return true;
}else{
//Tells that a game already exists with that name.
player.sendMessage(ChatColor.RED + "Can not create game with the name of " + args[0]);
return true;
}
}
}
Your code only checks the name of the first game in the list. If the first game matches, the code is correct in returning because it already knows the name is duplicate. However, if the name of the first game does not match, the code should not return. We only know that the new game is not a duplicate of the first game but we do not know if it is a duplicate of the other games in the list. The code should go on to check the rest of the games in the list. Only after none of the game names match should this code return.
Change your else clause to the following.
Game game;
for (int i = 0; i < Main.games.size(); i++){
game = Main.games.get(i);
if (game.getName().equalsIgnoreCase(args[0]) == false){
// Do not return here. Instead, continue to check the rest of the list
continue;
}else{
//Tells that a game already exists with that name.
player.sendMessage(ChatColor.RED + "Can not create game with the name of " + args[0]);
return true;
}
}
// We have reached the end of the loop so we now know that none of the
// games in the list match. Now we can return.
Main.games.add(new Game(args[0]));
player.sendMessage(ChatColor.GREEN + "Game Created. To join Type " + ChatColor.ITALIC + "/join " + args[0]);
//debug
player.sendMessage(Main.games.size() + "");
return true;
Seems like you still learn Java, so I don't want to give you a full code solution, just an explanation.
When iterating over a loop to see if something is in an array, you cannot return a false result until you checked all the items.
You error here - you compare new name with first item. If it is not the same name - you create a new game.
What you should do - you should add a boolean variable isFound and set it to false. Iterate over all games and check if the name exists. If so - change isFound to true and break the loop.
After the loop ends you should check isFound state.
I'm trying to Display individual elements of an Object I have created.
It is a simple Java program that allows users to add and keep track of Player Details.
I'm just stumped when it comes to displaying the details after they have been added already. here is what my code looks like
I can create the object and input it into the arraylist no problem using the case 2, but when I try to print it out I want to do something like
System.out.println("Player Name" + myPlayersArrayList.PlayerName + "Player Position" + myPlayerArrayList.PlayerPosition + "Player Age" + "Player Age");
I know that is not correct, but I dont really know what to do, if anyone can be of any help it would be greatly appreciated. Thanks
System.out.println("Welcome to the Football Player database");
System.out.print(System.getProperty("line.separator"));
UserInput myFirstUserInput = new UserInput();
int selection;
ArrayList<Player> myPlayersArrayList = new ArrayList<Player>();
while (true) {
System.out.println("1. View The Players");
System.out.println("2. Add A Player");
System.out.println("3. Edit A Player");
System.out.println("4. Delete A Player");
System.out.println("5. Exit ") ;
System.out.print(System.getProperty("line.separator"));
selection = myFirstUserInput.getInt("Please select an option");
System.out.print(System.getProperty("line.separator"));
switch(selection){
case 1:
if (myPlayersArrayList.isEmpty())
{
System.out.println("No Players Have Been Entered Yet");
System.out.print(System.getProperty("line.separator"));
break;}
else
{for(int i = 0; i < myPlayersArrayList.size(); i++){
System.out.println(myPlayersArrayList);
}
break;
case 2: {
String playerName,playerPos;
int playerAge;
playerName = (myFirstUserInput.getString("Enter Player name"));
playerPos = (myFirstUserInput.getString("Enter Player Position"));
playerAge = (myFirstUserInput.getInt("Enter Player Age"));
myPlayersArrayList.add(new Player(playerName, playerPos, playerAge)); ;
break;
}
You need to use index to access individual element: -
for(int i = 0; i < myPlayersArrayList.size(); i++){
System.out.println(myPlayersArrayList.get(i));
}
Then you can override toString() method in your Player class
public String toString() {
return playerName + " : " + playerAge + " : " + playerPosition;
}
I can create the object and input it into the arraylist no problem using the case 2, but when I try to print it out I want to do something like
System.out.println("Player Name" + myPlayersArrayList.PlayerName + "Player Position" + myPlayerArrayList.PlayerPosition + "Player Age" + "Player Age");
I know that is not correct, but I dont really know what to do, if anyone can be of any help it would be greatly appreciated. Thanks
Just override toString() method to get desired output
A List is a collection of elements. The List provides a number of useful methods which allows you to manage it, add, remove, set, indexOf, contains and most importantly, in this case, get.
In order to manipulate a element within the list, you first need to "get" or retrieve it from the list.
List are Iterable, this means you don't need to use an indexed for loop to gain access to the various members (unless the index is of importance).
So you can do...
for(int i = 0; i < myPlayersArrayList.size(); i++){
Player player = myPlayersArrayList.get(i);
// display results
}
or
for (Player player : myPlayersArrayList) {
// display results
}
To display the contents of the Player object you can do a number of different things...
You could simply display the various properties of the Player (I don't have access to your Player class, so I'm guessing at its properties)
System.out.println("Player Name: " + player.PlayerName + "; Player Position: " + player.PlayerPosition + "Player Age: " + player.PlayerAge);
Or you could write a "formatter" method. This could be static to the Player class or it could be part of utility class, depending on your needs
System.out.println(PlayerUtils.format(player)); // Format the player properties as you see fit
Or you can, as has already being suggest, override the toString method of the Player
System.out.println(player);
There are advantages and disadvantages to all these approaches.
I tend to like putting diagnostic information into my toString methods which isn't normally useful for displaying to the user. Formatters aren't always obvious to other developers (unless they are well documented ;)).
You will need to choose those which are most useful to you and your needs.
You can also use forEach in Java 8:
List<String> myPlayersArrayList = new ArrayList<>();
myPlayersArrayList.stream().forEach((player) -> {
System.out.println("Player: " + player); //Override toString() in Player class
});
You could also use 'for-each' loop. Here's the syntax:
for(Class object : collectionOfObjects){
//this will loop through the list for you and
//now you can access each object in the list
//using object.property or object.method()
}
//using your example
for(Player player: myPlayersArrayList){
System.out.println(player); //requires override of toString() method
//or you could use
System.out.println(player.getName());
}
If you just want to show the data right after it is added, you can declare a Player reference and make it point to the object you add to the list, like so:
Player p = new Player(playerName, playerPos, playerAge);
myPlayersArrayList.add(p);
System.out.println("Player Name" + p.PlayerName + "Player Position" + p.PlayerPosition + "Player Age" + p.playerAge);
Direct access to an object's attributes is, however, very frowned upon in an OOP environment, so you should retrieve them via get methods. For example, to get the players name, this would suffice:
public String getPlayerName(){
return playerName;
}
If you want to print the data later, maybe you should take a look at the iterator pattern.
I made a simple address book program using an Arraylist (program does not save entries after termination) and when I search the entries for an entry that was not the first one my error messages comes up with the entry information. I understand that this is happening because of the if condition used and the the error being an else. But I do not know how to make the program work another way. I want to be able search the entries for a specific name (String) and then display that persons contact info and if that name was not entered display "That person is not listed try another". I am very new to programming and have a very limited knowledge and I know my code looks bad right now but I would like to make it work correctly before making it look good.
while(!search){
if(listSize == 0){
break;//does not allow search if no names have been entered.
}
System.out.print("Please enter the first name to search for or q to quit: ");
String searchName = in.next().trim().toUpperCase();
for(AddressBook a: myBook){
if(searchName.compareTo("Q") == 0){
search = true;//allows user to exit search
}
else if(a.getName().compareTo(searchName) == 0){
System.out.println("that contact info is: ");
System.out.println("name: " + a.getFullName());
System.out.println("phone number: " + a.getPhoneNumber());
System.out.println("email: " + a.getEmail());
System.out.println("address: " + a.getAddress());
search = true;
break;
}
else
System.out.println("That name is not listed please try another");
}
}
This is the search portion of my code, the problem I am having is with the last else if / else. I know that when I search for a name and it doesn't come up in the first element the program goes to the else because the else if condition is false and that is what I need to fix.
You made a logic error in your for statement.
First, you should check for "Q" letter entered only once (not in for statement).
Then you should check for existence of one of the names every iteration of the for, and then (if all items of myBook collection doesn't appears your search condition(equals to searchName), you should show the error message. So, improved code version looks like this:
while(!search){
if(listSize == 0){
break;//does not allow search if no names have been entered.
}
System.out.print("Please enter the first name to search for or q to quit: ");
String searchName = in.next().trim().toUpperCase();
if(searchName.compareTo("Q") == 0){
search = true;//allows user to exit search
break; //exit "while" iteration
}
boolean found = false;
for(AddressBook a: myBook){
if(a.getName().compareTo(searchName) == 0){
System.out.println("that contact info is: ");
System.out.println("name: " + a.getFullName());
System.out.println("phone number: " + a.getPhoneNumber());
System.out.println("email: " + a.getEmail());
System.out.println("address: " + a.getAddress());
search = true;
found = true;
}
}
if(found == false)
System.out.println("That name is not listed please try another");
}
Did you try something like this:
System.out.print("Please enter the first name to search for or q to quit: ");
String searchName = in.next().trim().toUpperCase();
if (searchName.equals("Q") == false)
{
boolean found = false;
for(AddressBook a: myBook){
if(a.getName().toUpperCase().equals(searchName)){
System.out.println("that contact info is: ");
System.out.println("name: " + a.getFullName());
System.out.println("phone number: " + a.getPhoneNumber());
System.out.println("email: " + a.getEmail());
System.out.println("address: " + a.getAddress());
found = true;
break;
}
if(found == false)
{
System.out.println("Item Not Found!");
}
}
P.S. I think you should be using a HashMap since it is far more efficient if you just want to store and retrieve specific strings.
For a short tutorial, please follow this link.
Here is the flow you have now:
1. Read in the requested name to search for
2. Get the first element in the list. Put it in a.
a. Did the user enter Q? Then eventually exit the loop.
b. Does the first element match? If so, print info.
c. Otherwise, print The name is not listed. Try again...
What you want is
1. Read request
2. If request is Q, quit.
3. If request is not Q then loop through the list
a. If an element matches, set flag saying we found a match.
4. After the loop, check the flag to see if a match was found. If it was, print the info
5. If a match wasn't found, print Try again.
The long and short is, you will need to move some of your code out of the loop. I could write the code for you, but I'm sure you can get it. I will monitor this if you have more questions so I can help!
First of all, I would not use ArrayList - if you're going to search by name all the time, I would make it a Map with fullName as the key.
On the second case, why are you checking if searchNAme is "Q" in the Addressbook loop? You should do that instead of the loop.