So I've been struggling all day today trying to create an instance of a class called 'Sport'.
I've got my code set up so I run the User Interface, which then runs a constructor, which then runs another constructor which loads the Sport values from a text file.
The problem is, the way I'm apparently creating the objects is wrong. Could really use some help.
public static void seperateValues(String sportDetail)
{
String[] sportDetails = sportDetail.split(",");
System.out.println("Adding new sport to the Sport collection");
System.out.println(sportDetail);
/*
for(int i=0; i<sportDetails.length; i++) //just used for testing whether it was splitting correctly
{
System.out.println(sportDetails[i]);
} */
// name,usagefee,insurance,affiliationfees, then court numbers
//Tennis,44,10,93,10,11,12,13,14,15,16
int vlength;
vlength = sportDetail.length();
String[] sportDetailz;
sportDetailz = new String[vlength];
sportDetailz[0] = sportDetails[0]; //name
sportDetailz[1] = sportDetails[1]; //usage fees
sportDetailz[2] = sportDetails[2]; //insurance
sportDetailz[3] = sportDetails[3]; //afflcationfees
String vSportObjectName;
vSportObjectName = sportDetails[0];
String sportinstance;
sportinstance = sportDetails[0]; //this is the name of the sport which I'm hoping each loop around
//it will give a new name to
Sport sportinstance = new Sport(sportDetails);
//System.out.println(Sport.this.name);
}
Error message: variable sportinstance is already defined in method seperateValues(java.lang.String)
http://puu.sh/2zil9
I'm guessing your issue is that you first declare sportinstance as a String. You then try to define it again as a Sport.
Just remove the following lines and try again (as it doesn't look like they actually are used anywhere else):
String sportinstance;
sportinstance = sportDetails[0];
The other option would be to simply rename either one of your instances of sportinstance.
You are trying to define sportinstance as two different datatypes and Java will not allow this. Either change the name of the Sport definition of sportinstance to another variable name or remove the definition.
Related
I'm trying to get my ArrayList's index via indexOf. So far, I've got
My ArrayList: public static ArrayList<Shop> allShops = new ArrayList();
That what is supposed to get the index
Scanner editShop = new Scanner(System.in);
String shopToEdit = editShop.nextLine();
int i = allShops.indexOf(shopToEdit);
System.out.println(i); //see what our index is (returns -1 because the var doesn't seem to get the right input)
EditFunc.edit(i);
and this, that is supposed to change my arraylist
public static void edit(int index){
//change array with given input in edit
//TODO: Make it so they can choose what to edit
//with booleans if editTrueName = false and then later on make it true again
System.out.println("Enter the new shop name:");
Scanner editedShopAttribute = new Scanner(System.in);
String editedShopName = editedShopAttribute.nextLine();
System.out.println("Enter the new shop location:");
String editedShopLocation = editedShopAttribute.nextLine();
Shop EditedVar = new Shop();
EditedVar.createShop(editedShopName,editedShopLocation);
allShops.set(index, EditedVar);
}
I've copied the values that debugger showed me and replaced them with that, but it still doesn't seem to work. Am I taking in the wrong kind of data? What can I try?
If there's something that looks wrong with my code, I'm always up to try and make it better.
Can't you do it with a Map<String, Shop>? That way you could use the shopName as a key.
By the way, as I see your new with java and OOP, I strongly recommend you read Clean Code, by Robert C. Martin, its a game-changing book.
I don't believe you can make what you want work with an Array. The reason as pointed out in one of the comments is that you are looking for a String, but the Array contains Shop(s). Since a Shop contains more than just the ShopName, you will never be able to find it this way. You should use a "Map" for such purposes:
public static Map<String, Shop> allShopsMap = new HashMap<>();
If you add all the shops to this map, then when you get a ShopName as an input, you merely need to do:
Shop shopToEdit = allShopsMap.get(inputShopName);
then call the set methods on this object to alter name and location.
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 am trying to create a public instance method that takes no arguments and returns no values. It is required to get an input from a user to select a file, this part I have no issues with. The method needs to make use of the BufferReader and Scanner Objects. So that it can read the file selected. For each line that is read, a new object should be created and its instance variables set using the values found in the file.
That object that is created should then be added to a list. This is where I am having issues, it won't let me add the new object to the list. Below is my code:
public void readInEntrants()
{
String pathname = OUFileChooser.getFilename();
File aFile = new File(pathname);
Scanner bufferedScanner = null;
Set<Entrant> entrantSet = new HashSet<>();
try
{
String currentEntrantLine;
Scanner lineScanner;
bufferedScanner = new Scanner(new BufferedReader(new FileReader(aFile)));
while (bufferedScanner.hasNextLine())
{
currentEntrantLine = bufferedScanner.nextLine();
lineScanner = new Scanner(currentEntrantLine);
lineScanner.useDelimiter(" ");
currentEntrantLine = lineScanner.next();
entrantSet.add(new Entrant(currentEntrantLine)); // <----- Here is where I am having trouble. It won't let me add the new object to the class Entrant
}
}
catch (Exception anException)
{
System.out.println("Error: " + anException);
}
finally
{
try
{
bufferedScanner.close();
}
catch (Exception anException)
{
System.out.println("Error: " + anException);
}
}
return entrantSet;
}
I'm not sure what to do. Could anyone see what I am doing wrong?
Sorry for got to add that it is a compilation issue, it will not compile properly.
Use an IDE ,I bet you dont (otherwise it would mark compilation error immediatly with red -> you use return in void method ) and in this case you would see other errors.
(off: this would go to comment section however under 50reputation I am not allowed to do that. Stackoverflow should change this imo. )
First of all:
You marked function readInEntrants as public void so you can't use return inside.
You could either remove return entrantSet; instruction or change function definition to public Set<Entrant> readInEntrants.
Concerning problem you have:
Basing on comment you left on beatrice answer I think you have only parameterless constructor for 'Entrant' class, while you try to create it passing string as parameter.
new Entrant(currentEntrantLine)
What you need to do is define Entrant class constructor that accept String as it's argument. For example:
public Entrant(String dataToParse)
{
// here you parse data from string to entrant fields
}
On the side:
You use bufferedReader to read entire file line at once and that's ok, but then you define Scanner lineScanner to iterate through line elements and then use it only once.
This way for file... let's say:
One Two Three
Four Five Six
Your while loop would work like this:
Store "One Two Three" inside currentEntrantLine.
Create scanner that'll work on "One Two Three", and set it to use space as delimiter.
Use .next to "Finds and returns the next complete token" (see documentation) and then store value inside currentEntrantLine. This way contents of currentEntrantLine is "One". Not entire line.
In next iteration you would have scanner working on "Four Five Six" and "Four" as currentEntranceLine content.
It seems the constructor of entrant class does not have any argument. Pass String as an argument type in the constructor to set the String field inside the Entrant class .
So this is my first time posting here. I am trying to read data from a file, create multiple objects from that data, and then place the created objects into an ArrayList. But every time I have tried, I just get multiple copies of the same object, instead of different objects. I am at my wits end.
Anyways, here is the code for the method to read the data in from the file. Thanks in advance for any help!
public void openShop() throws IOException{
System.out.println("What is the name of the shop?");
shopName = keyboard.nextLine();
setShopFile();
File openShop = new File(shopFile);
if (openShop.isFile()){
Scanner shopData = new Scanner(openShop);
shopName = shopData.nextLine();
shopOwner = shopData.nextLine();
while (shopData.hasNextLine()){
shopItem.setName(shopData.nextLine());
shopItem.setPrice(Double.parseDouble(shopData.nextLine()));
shopItem.setVintage(Boolean.parseBoolean(shopData.nextLine()));
shopItem.setNumberAvailable(Integer.parseInt(shopData.nextLine()));
shopItem.setSellerName(shopData.nextLine());
shopInventory.add(shopItem);
}
setNumberOfItems();
}
else
System.out.println("That shop does not exist. Please try to open" +
"the shop again.");
isSaved = true;
}
inside your while loop you should create a new instance of an object. Else it would only end up making modifications to the exisiting instance.
Correct way :
while (shopData.hasNextLine()){
shopItem = new ShopItem(); //This will create a new Object of type ShopItem
shopItem.setName(shopData.nextLine());
shopItem.setPrice(Double.parseDouble(shopData.nextLine()));
shopItem.setVintage(Boolean.parseBoolean(shopData.nextLine()));
shopItem.setNumberAvailable(Integer.parseInt(shopData.nextLine()));
shopItem.setSellerName(shopData.nextLine());
shopInventory.add(shopItem);
}
I cant see where you're creating the shopItem instance.
But if you're not creating a new ShopItem each time then every time you go around the loop you're just updating the one instance, and then adding it to the shopInventory.
You fill your ArrayList using the very same object. You should create a new instance of ShopItem:
while (shopData.hasNextLine()){
ShopItem shopItem = new ShopItem();
shopItem.setName(shopData.nextLine());
...
}
basically am trying to make java command prompt. Suppose user enters as input from the user:
new x java.util.ArrayList
here x is the object name and java.util.ArrayList is the class. So this script inputed by the user means create an object of class java.util.ArrayList.
Now suppose that user enter:
new x java.util.ArrayList int:5
means create an object x of the java.util.ArrayList and make its size 5. Like this i want that everytime i input something related to object creation as input i should be able to create class its object and its method based on the input that the user does. Am new to java and reflection so kindly help! here is the code i thought so far using my mind:
public static void token_classification() throws ClassNotFoundException
{
my_hash = new HashMap();
Keep_Obj_Info = new HashMap();
if(expression_keeper[0].equalsIgnoreCase("new"))
{
my_hash.put("Object", expression_keeper[1]);
Class Obj= Class.forName(expression_keeper[2]);
Keep_Obj_Info.put("Modifier", Obj.getModifiers());
Keep_Obj_Info.put("Package",Obj.getPackage());
////????
Constructor[] constructors = Obj.getConstructors();
}
else
if(expression_keeper[0].equalsIgnoreCase("call"))
{
}
else
if(expression_keeper[0].equalsIgnoreCase("print"))
{
}
else
{
System.out.println("Invalid Script!");
}
}
ExpressionKeeper is basically a String array that keeps the user input in tokenized form. Meaning anything next to a white space to a new location.
Well for Object creation in java; the constructor and it's arguments are required.
you can have a generic framework which will accept input from command prompt and interpret them means find out the data type of the input ex : number/string/char/boolean etc..
Also your framework should know the argument index for example say a constructor has 2 parameter and one is string and another is int. and say first parameter is int and 2nd parameter is String and while passing the parameter from the command line the user first pass string and then int in that scenario your program should be smart enough to properly arrange them in order. So many such things you need to take care of....Now coming to the example which you have mentioned for ArrayList you can write a program as follows : (I have just given you a pseudocode you can implement your own way)
{
int howManyParametersFromCommandLine = getnoParameterCount; //it will maintain no.of parameters passed from command line
String[] parametersFromCommandLine = getParametersFromcommandLine(); // Ex : {1,"ABC",new Double(80.0d)};
List<Class> parameterTypesList = parseParameters(parametersFromCommandLine); //This will identify type of each of the parameter
Class clazz = Class.forName("youClassName");
Constructor[] cons = clazz.getConstructors();
for(Constructor c : cons)
{
Class[] parameterTypes = c.getParameterTypes();
if(parameterTypes.length == howManyParametersFromCommandLine)
{
//try to match the parameter type in parameterTypesList with parameterTypes if this matches then
boolean typeMatchingAndSequecneSucess = matchParameters(parameterTypes,parameterTypesList);
if(typeMatchingAndSequecneSucess)
{
if(c.isAccessible())
{
Object[] initargs = parseAndRetActualParamValue(parametersFromCommandLine);
return c.newInstance(initargs);
}
}
}
}
}
Hope this will help you !!
You may want to use the Interpreter design pattern. It is used just for that.
The Interpreter is a bit complex, but will ensure you code interpretation works right. Also, it gives you a easy inclusion of new commands.
Take a look at here: http://en.wikipedia.org/wiki/Interpreter_pattern
Hope I could help.