Coding a Ask for Char menu
Trying to construct a menu in which allows a user to add or view parts from a linkedlist. Ive been following a tutors video, however when he enters In.nextChar his program works fine, however my program wont accept that as an option/method of obtaining the users input.
The code is exactly the same as the tutors but as you can see I get the error where return In.nextChar(); is
I suggest using something like an ArrayList as storage for your Parts.
public class Catalogue {
private ArrayList<Part> parts;
public Catalogue() {
parts = new ArrayList<Part>();
}
}
if you want to be able to add certain Parts to the Catalogue you can just add the the Part-Instances to the ArrayList by
Part myExamplePart = new Part(...);
parts.add(myExamplePart);
Related
I'm trying to make the bot I'm coding react on a user's message when it has specific keywords in it. I have about 50 keywords that the bot can react to, but only if they are at the start of the message.
The bot will react with an emote when it's at the start of the user's message but not when it's after the first word.
I've already tried asking the discord for some help but it's pretty apparent that they don't really care to be friendly to newcomers. I've tried changing the argument from "0" to "Message.MAX_CONTENT_LENGTH" which didn't work. I also originally had an ArrayList that I converted into a String that didn't work, and later tried using just a normal List; with the same result. Right now I'm stuck with an extremely unoptimized if/else statement, but I can live with it. I just need it to work.
import net.dv8tion.jda.core.events.message.guild.GuildMessageReceivedEvent;
import net.dv8tion.jda.core.hooks.ListenerAdapter;
public class GuildMessageReceived extends ListenerAdapter {
public void onGuildMessageReceived(GuildMessageReceivedEvent event) {
String[] args = event.getMessage().getContentRaw().split("\\s+");
if (args[0].equalsIgnoreCase("zachary")) {
event.getMessage().addReaction("🕵").queue();
} // if
} // onGuildMessageReceived()
} // GuildMessageReceived
I expect the result to be a reaction on the message with the keyword located inside of it at any point, not just at the beginning. Assume that "money" is a keyword.
What I need:
[6:52 PM] Anon: I have money
|| Reactions: :spy:
What I get:
[6:52 PM] Anon: I have money
|| Reactions: None
Your code only reacts if the first message is a keyword because you're splitting by space and then only checking the first element of the array. Convert the array to an List and use contains(). For example:
List<String> words = Arrays.asList(event.getMessage().getContentRaw().split("\\s+"));
if (words.contains("zachary")) {
event.getMessage().addReaction("🕵").queue();
}
If you want to easily check for multiple keywords you can instead use Collections.disjoint(). For example:
Set<String> keywords = Set.of("foo", "bar", "baz");
List<String> words = Arrays.asList(event.getMessage().getContentRaw().split("\\s+"));
if (!Collections.disjoint(keywords, words)) {
event.getMessage().addReaction("🕵").queue();
}
I have two objects that are being stored in arrays:
Game(String creator, String title, int releaseYear, int NumberSold)
Creator(String name, String gamesWorkedOn)
Game(creator) has multiple creators, so is stored as a string like this: "creator1, creator2, creator3" using commas to separate their values.
Not all games have multiple creators and there are not many different creators in total.
What I am trying to do is loop through an array of Game(games) and extract a creator variable from it and assign it to the Creator(name) and then match any games that creator is mentioned in and assign those title variables to Creator(gamesWorkedOn).
So far I have this:
public static void PopulateCreators(ArrayList<Game> games) {
//populating an array of Creators with games they have worked on
boolean match = false;
String thisCreator;
String gamesWorkedOn;
ArrayList<Creator> creatorArray = new ArrayList<Creator>();
for (int i = 0; i < games.size(); i++) {
thisCreator = games.get(i).getGameCreator();
thisCreator = thisCreator.replaceAll(", ", "\n");
Which gives me this output using a sysout:
Shigeru Miyamoto
Satoshi Tajiri
Yoshiaki Koizumi
Koichi Hayashida
Shigeru Miyamoto
My desired output would be to have something like this:
name = "Shigeru Miyamoto"
gamesWorkedOn = "game1, game2, game3"
I am looking at using a for loop but am unsure on how to implement it here.
Edit:
I forgot to mention a couple of details that I didn't think were important but I will be a bit clearer now. This is a Swing based project I am working on that takes user inputs and stores these arrays which are then saved into a JSON file that is read upon loading of the application and when a user clicks a 'save' button.
What you seem to want to do is map the creators to all the games that they have created or helped create. I'm going to start by creating a simplified version of the problem.
You have a list of:
class Game {
Set<Creator> creators;
}
which you want to convert to:
Map<Creator, Set<Game>> createdGames; // Map of creator name to games created
The first thing to do here is to find all of the unique creators to start adding to the map. This can be done with the stream API.
createdGames = gameList.stream().flatMap(game -> game.creators.stream()).distinct().collect(Collectors.toMap(Function.identity(), v -> new HashSet<>()));
Now you can just loop through all the games again and add the game to a creator's set if they took part in the creation of that game.
for(Game game : gameList) {
for(Creator creator : createdGames.keySet()) {
if(game.creators.contains(creator)) {
createdGames.get(creator).add(game);
}
}
}
I have a 3 dimensional ArrayList and I want to determine if it is empty or not. There is an exception called EmptyCollectionException which is not part of java standard library and hence I'm not allowed to use it.
Is there a way to accomplish that using a native java exception or function?
The 3D List is constructed as follow:
public void makeRandomCardListForLearning (Course courseToBeMadeRandom) {
List<List<List<Card>>> course = new ArrayList<List<List<Card>>>();
for(Chapter chptr: courseToBeMadeRandom.getChapterList()) {
List<List<Card>> chapter = new ArrayList<List<Card>>();
course.add(chapter);
for(Deck dck: chptr.getDeckList()) {
List<Card> deck = new LinkedList<Card>();
chapter.add(deck);
for(Card crd: dck.getCardList()) {
if(dck.isTheCardDueToday(crd.getLastDate())) {
deck.add(crd);
}
}
Collections.shuffle(deck);
}
}
}
As I go through course, chapter and deck I create a List for each one. There is only one course, many chapters, many decks and of course many cards which are saved under deck doublyLinkedList if they pass the pre-condition. If no card passes the condition, I have a 3D list which exists but has no cards. And I want to determine that If no card exists in the list, then the user receives an error message.
In fact I only need the cards. But I also need to know in which deck each card resides at the moment. If I just make a list and go through all chapters and decks and put cards in that list based on the condition then I have no clue in which chapter and deck each card resides. That can be solved by maybe adding two attributes to the card class. But that was a mistake as we designed the system and adding them now costs a lot of change in other parts of the program. Each index in course List represents the chapter number and each index in chapter list represents the deck number. I solved the problem that way.
This should do it:
public static boolean isEmpty(List<List<List<Card>>> list3d) {
return list3d.stream().flatMap(llc -> llc.stream()).flatMap(lc -> lc.stream()).count() == 0;
}
It takes into account that the outer lists may contain empty inner lists. It deems the entire 3D list empty if there are no cards in it.
you can do something like this
List<List<List<Card>>> course = new ArrayList<List<List<Card>>>();
// some possible codes
boolean check = course.isEmpty()
// other possible codes
if (check) {
// do something
}
or any arraylist you want to check or any way you want to reach your goal
I'm not looking for a complete answers just help on how to start it or maybe some references I could look at that may help me with this. Ok so I have to populate the JComboBox (accountnumber) from a text file. The txt files reads as:
1231<>Jack Williams<>2015/1/21<>463.02
1232<>Jane Brown<>2015/1/21<>13510.54
1233<>Paul Gonzales<>2015/1/22<>680.17
1234<>Jian Chen<>2015/1/22<>1117.54
1235<>Lily Makki<>2015/1/22<>1124.89
1236<>Michael Lopez<>2015/1/23<>800.0
1237<>Jose Alvarez<>2015/1/23<>607.21
1238<>Tina Lin<>2015/1/24<>11077.0
It reads as acctNumber<>CustomerName<>openDate<>balance
How would I go about starting this? Which would be easiest to split the 4 variables. array/arraylist/hashmap etc.?
I'm not familiar with file I/O. and trouble with collections so this is the only part I'm stuck on.
import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class AccountUtility {
List<String> accountsInfo = new ArrayList<>();
BufferedReader in;
File file = new File("accounts.txt");
public AccountUtility(){
ReadFile();
}
public void ReadFile(){
String nxtLine = " ";
try{
in = new BufferedReader(new FileReader(file));
while(nxtLine != null){
nxtLine = in.readLine();
accountsInfo.add(nxtLine);
}
for(String items : accountsInfo)
System.out.println(items);
in.close();
}catch(IOException ex){
}
}
public static void main(String[] args) {
AccountUtility ut = new AccountUtility();
}
}
so i decided to use a list , this is just my accountutility class I just added a mainmethod so i can test just this class and the result when i Run it comes to
1231<>Jack Williams<>2015/1/21<>463.02
1232<>Jane Brown<>2015/1/21<>13510.54
1233<>Paul Gonzales<>2015/1/22<>680.17
1234<>Jian Chen<>2015/1/22<>1117.54
1235<>Lily Makki<>2015/1/22<>1124.89
1236<>Michael Lopez<>2015/1/23<>800.0
1237<>Jose Alvarez<>2015/1/23<>607.21
1238<>Tina Lin<>2015/1/24<>11077.0
null
How do i split an list using a delimiter?
You're primary identifier is the account number, from this you need to be able to ascertain the account details.
This would lead me to use some kind of Map.
I would then create an Account class which held all the information in a simple, easy to use class, which provided appropriate setters and getters.
This would then lean me to the fact that I wouldn't actually need the Map, because all the information I need was in the Account class, so instead, I would simply create a ListCellRenderer for the combo box that would be capable of taking the account number from an instance of the Account class and display it appropriately...
This would mean I'd only need a List or a ComboBoxModel to hold the account details
Take a closer look at How to Use Combo Boxes for more details
To display an Object, Swing components will use the toString() method the Object placed in it.
One approach is to create a Data class that holds the name, ID, etc., implement toString() to display what you want (in your case, the Account Number), and then put a list of these objects in your JComboBox.
Then on change of selection in the combo, get the selected item, cast it to the data class, and then call getDate(), getName(), etc. to populate the textfields.
If you want to actually show the extra details of the Customer in the combo (after all, who really knows the person by account number?), then take a look at one approach here:
DetailedComboBox
Justin, I'm in the same boat and created a similar program that reads from text file. There was an excellent given for cells (e.g. Excel or Sql), but need to have it read from a text file. I'm thinking:
String tmp [] = line.split ("<>");
this will output data from each break.
Okay I'll try to be direct.
I am working on a file sharing application that is based on a common Client/Serer architecture. I also have HandleClient class but that is not particularly important here.
What I wanna do is to allow users to search for a particular file that can be stored in shared folders of other users. For example, 3 users are connected with server and they all have their respective shared folders. One of them wants to do a search for a file named "Madonna" and the application should list all files containing that name and next to that file name there should be an information about user(s) that have/has a wanted file. That information can be either username or IPAddress. Here is the User class, the way it needs to be written (that's how my superiors wanted it):
import java.io.File;
import java.util.ArrayList;
import java.util.Scanner;
public class User {
public static String username;
public static String ipAddress;
public User(String username, String ipAddress) {
username = username.toLowerCase();
System.out.println(username + " " + ipAddress);
}
public static void fileList() {
Scanner userTyping = new Scanner(System.in);
String fileLocation = userTyping.nextLine();
File folder = new File(fileLocation);
File[] files = folder.listFiles();
ArrayList<String> list = new ArrayList<String>();
for (int i = 0; i < files.length; i++) {
list.add(i, files[i].toString().substring(fileLocation.length()));
System.out.println(list.get(i));
}
}
public static void main(String args[]) {
System.out.println("Insert the URL of your shared folder");
User.fileList();
}
}
This class stores attributes of a particular user (username, IPAddress) and also creates the list of files from the shared folder of that particular user. the list type is ArrayList, that's how it has to be, again, my superiors told me to.
On the other hand I need another class that is called RequestForFile(String fileName) whose purpose is to look for a certain file within ArrayLists of files from all users that are logged in at the moment of search.
This is how it should look, and this is where I especially need your help cause I get an error and I can't complete the class.
import java.util.ArrayList;
public class RequestForFile {
public RequestForFile(String fileName) {
User user = new User("Slavisha", "84.82.0.1");
ArrayList<User> listOfUsers = new ArrayList();
listOfUsers.add(user);
for (User someUser : listOfUsers) {
for (String request : User.fileList()) {
if (request.equals(fileName))
System.out.println(someUser + "has that file");
}
}
}
}
The idea is for user to look among the lists of other users and return the user(s) with a location of a wanted file.
GUI aside for now, I will get to it when I fix this problem.
Any help appreciated.
Thanks
I'm here to answer anything regarding this matter.
There are lots of problems here such as:
I don't think that this code can compile:
for (String request : User.fileList())
Because fileList() does not return anything. Then there's the question of why fileList() is static. That means that all User objects are sharing the same list. I guess that you have this becuase you are trying to test your user object from main().
I think instead you should have coded:
myUser = new User(...);
myUser.fileList()
and so fileList could not be static.
You have now explained your overall problem more clearly, but that reveals some deeper problems.
Let's start at the very top. Your request object: I think it represents one request for one user with one file definition. But it needs to go looking in the folders of many users. You add the the requesting user to a list, but what about the others. I think that this means that you need another class responsible for holding all the users.
Anyway lets have a class called UserManager.
UserMananger{
ArrayList<User> allTheUsers;
public UserManager() {
}
// methods here for adding and removing users from the list
// plus a method for doing the search
public ArrayList<FileDefinitions> findFile(request) [
// build the result
}
}
in the "line 14: for (String request : User.fileList()) {" I get this error: "void type not allowed here" and also "foreach not applicable to expression type"
You need to let User.fileList() return a List<String> and not void.
Thus, replace
public static void fileList() {
// ...
}
by
public static List<String> fileList() {
// ...
return list;
}
To learn more about basic Java programming, I can strongly recommend the Sun tutorials available in Trials Covering the Basics chapter here.
It looks like you're getting that error because the fileList() method needs to returns something that can be iterated through - which does not include void, which is what that method returns. As written, fileList is returning information to the console, which is great for your own debugging purposes, but it means that other methods can't get any of the information fileList sends to the console.
On a broader note, why is RequestForFile a separate class? If it just contains one method, you can just write it as a static method, or as a method in the class that's going to call it. Also, how will it get lists of other users? It looks like there's no way to do so as is, as you've hard-coded one user.
And looking at the answers, I'd strongly second djna's suggestion of having some class that acts as the controller/observer of all the Users.