I read most of the other things on SO and I couldn't seem to find an answer.
Don't know how to write an add method. I'm getting a StackOverflowError. It seems to run infinitely which I am not sure why.
Also, just wanted to confirm that it is possible to write a print function that prints out everything in arraylist myPolygon right?
class IrregularPolygon{
private ArrayList <Point2D.Double> myPolygon;
// constructors
public IrregularPolygon() { }
// public methods
public void add(Point2D.Double aPoint) {
//System.out.println("in");
this.add(aPoint);
System.out.println("finished");
// for (Point2D.Double number : myPolygon) {
// System.out.println("Number = " + aPoint);
// }
}
}
public class App{
public static void main(String[] args){
IrregularPolygon polygon = new IrregularPolygon();
Point2D.Double point = new Point2D.Double(1.2, 2.3);
System.out.println(point);
polygon.add(point);
} // main
} // class
Calling this.add(aPoint) in add is a recursive call. This method calls itself, and there is no base case, so this results in a StackOverflowError once it recurses deeply enough.
It looks like you want to add it to the ArrayList, so change
this.add(aPoint);
to
myPolygon.add(aPoint);
In addition, you never initialized myPolygon, so it's null. Initialize it:
private ArrayList <Point2D.Double> myPolygon = new ArrayList<>();
Related
I want to create a list, add blocks to it and then use it in a BlockBreakEvent to check if the block is in the list and cancel the event if it's not. But I can't seem to create and add things in it any other way than in the actual event itself (which looks to me like it would create issues). The only thing that is working for me is creating the list in the event and adding blocks to it one by one which looks really messy compared to: creating the list in a separate class and just checking the list with if(Listname.contains(block)) does anyone know how I can achieve this? Whether its dependency injection, or whatever else. I just can't figure out how to put it to use.
Here's what I've tried and is currently working for me, but I believe it's theoretically incorrect:
public class Event implements Listener {
#EventHandler
public void onBreak(BlockBreakEvent e) {
List<Material> allowedblocks = new ArrayList<Material>();
allowedblocks.add(Material.STONE);
//repeat this 10-50 times for whatever item
Player p = e.getPlayer();
Material block = e.getBlock().getType();
if(allowedblocks.contains(block)){
p.sendMessage("Invalid block. Break cancelled");
e.setCancelled(true);
}else{
p.sendMessage("Valid Block");
}
}
}
You can make allowedBlocks List a class field and fill it with elements inside of the constructor.
public class YourClass {
private List<Material> allowedBlocks = new ArrayList<>();
public YourClass() {
allowedBlocks.add(Material.STONE);
//repeat this 10-50 times for whatever item
}
#EventHandler
public void onBreak(BlockBreakEvent e) {
Player p = e.getPlayer();
Material block = e.getBlock().getType();
if(allowedBlocks.contains(block)){
p.sendMessage("Valid Block");
} else {
p.sendMessage("Invalid block. Break cancelled");
e.setCancelled(true);
}
}
}
Another approach would be to make the list static and fill it with values inside of a static block. I would not recommend making the list static if you are planning to change its values, but if your allowed blocks are going to remain the same, it may be a good idea to even go further and make it public, so you can access it from anywhere without an instance of YourClass
public class YourClass {
public static final List<Material> allowedBlocks;
static {
List<Materials> list = new ArrayList<>();
list.add(Material.STONE);
//repeat this 10-50 times for whatever item
//use an unmodifiable list,
//so you do not accidentally change its content later
allowedBlocks = Collections.unmodifiableList(list);
}
#EventHandler
public void onBreak(BlockBreakEvent e) {
Player p = e.getPlayer();
Material block = e.getBlock().getType();
if(allowedBlocks.contains(block)){
p.sendMessage("Valid Block");
} else {
p.sendMessage("Invalid block. Break cancelled");
e.setCancelled(true);
}
}
}
In the first case, there will be a list of allowedBlocks per instance of YourClass, which means, that every time you call new YourClass() a new List will be created and filled. In the second case, there will be only one list which will be created and populated on class loading (at the very beginning of the program) start up.
P.S. I would rather use a Set instead of a List here, considering you are using contains very often.
Since you are using an enum to store your Material types, you can simply call the static .values() method through Material.
Ex:
#EventHandler
public void onBreak(BlockBreakEvent e) {
Player p = e.getPlayer();
Material block = e.getBlock().getType();
if(List.of(Material.values()).contains(block)){
p.sendMessage("Invalid block. Break cancelled");
e.setCancelled(true);
}else{
p.sendMessage("Valid Block");
}
}
}
If you need to be able to customize what values are in the List you can use the singleton pattern to access that information globally.
The instance can be accessed statically from anywhere in the application:
import java.util.List;
public class BlockController {
public static BlockController instance = new BlockController();
private List<Material> allowedBlocks;
public BlockController() {
this.allowedBlocks = new ArrayList<>();
}
public void addAllowedBlock(Material mat) {
this.allowedBlocks.add(mat);
}
public void removeAllowedBlock(Material mat) {
this.allowedBlocks.remove(mat);
}
public boolean containsBlock(Material mat) {
return this.allowedBlocks.contains(mat);
}
public void clear() {
this.allowedBlocks.clear();
}
/**
* You can add more functionality here...
* This class can be accessed anywhere in the application
*
* use:
*
* BlockController controller = BlockController.instance;
* controller.containsBlock(Material.BLOCK);
*/
}
One approach to creating the list in a separate class is to use a static initializer block:
public class MyClass {
public static final List<Material> ALLOWED_MATERIALS = new ArrayList<>();
static {
ALLOWED_MATERIALS.add( Material.STONE );
}
public static List<Material> getAllowedMaterials() {
return Collections.unmodifiableList( ALLOWED_MATERIALS );
}
...
}
Try to create the List in a static context. This way the list is the same for all instances:
public class MyClass {
public static List<Material> allowedblocks = new ArrayList<Material>();
#EventHandler
public void onBreak(BlockBreakEvent e) {
allowedblocks.add(Material.STONE);
...
Then you can call the List from everywhere like this (e.g. if statement):
if(MyClass.allowedblocks.contains(block))
Your problem seems similar to this question, maybe this answer helps too: .
I have a class to generate an Arraylist it all seems to work but in main it produces a compilation problem which I guess does not recognize my variable name as an ArrayList
public class Order {
//Attributes
private ArrayList<DessertItem> order;
//Constructors
Order(){
order = new ArrayList<DessertItem>();
}
//Methods
public ArrayList<DessertItem> getOrderList(){
return order;
}//end of getOrderList
public void add(DessertItem aItem) {
order.add(aItem);
}//end of add
public int itemCount() {
return order.size();
}//end of itemCount
}//end of class
public class DessertShop {
public static void main(String[] args) {
//create order
Order order = new Order();
//create obj and adding to the order
Candy c1 = new Candy("Candy Corn", 1.5, .25);
order.add(c1);
for (DessertItem item : order) {//here is where is marked the error
System.out.printf("%s.%n", item.getName());
}
Your code is hard to read. I'd recommend paying attention to formatting.
order is an Order, not an ArrayList. It has an ArrayList. That's what you want to iterate over.
Try this:
for (DessertItem item : order.getOrderList()) {
System.out.printf("%s.%n", item.getName());
}
A lot of your comments are clutter. I'd remove them.
I'd prefer a static type of List<DessertItem> for order. You can change the implementation for the List if you need to.
I have a class named Preprocessing and has a method called Process()
, it has an ArrayList called datatweets that contains my data.
public void Process(){
//the process...
datatweets.add(mydata);
}
then I try to pass the datatweets and the value(my data) to another ArrayList on the different class. I've tried using getter method such as:
public ArrayList getMyList(){
return datatweets;
}
but it still doesn't print any value when I call it. please tell me what is wrong, and what should I do?
here's what i do to call the arrayList:
Preprocessing data = new Preprocessing();
ArrayList<String> dataset = new ArrayList<>();
dataset = data.getMyList();
for(int a=0;a<dataset.size();a++){
System.out.println(dataset.get(a));
}
As i understand you have an class named "Preprocessing". Now you should have "datatweets" as your instance variable of the class.
Now you should create an object of Preprocessing and call the method "Process". In the method process you should fill the arraylist "datatweets". Process method should contain below code.
if(this.dataTweets == null)
this.dataTweets = new ArrayList<>();
this.dataTweets.add(myData);
Once the datatweets is filled by calling the process method. You should have getter method in same class which should return datatweets
public List<String> getDataTweets(){
return this.dataTweets;
}
Now the main function should look like this
public static void main(String[] args){
Preprocessing preprocessor = new Preprocessing();
preprocessor.Process();
List<String> dataTweets = preprocessor.getDataTweets();
//Now iterate over this you will surely get data.
}
You class Preprocessor should be like this
public class Preprocessor{
private List<String> dataTweets;
public void process(){
//processing
this.dataTweets.add(data);
}
public List<String> getDataTweets(){
return this.dataTweets;
}
}
In a Android application I am making I have an array of instances of a certain class I made, and later in the program I need to use the getter and setter methods from that class on an instance of the class from the array. Do I need to assign the instance of the class from the array to a new class initializer? Here is some code to clear this up:
Class
public class ProfileInformation {
private String console;
private String gamertag;
public String getConsole() {
return console;
}
public void setConsole(String console) {
this.console = console;
}
public String getGamertag() {
return gamertag;
}
public void setGamertag(String gamertag) {
this.gamertag = gamertag;
}
}
Array
ArrayList<ProfileInformation> ProfTags = new ArrayList<>();
Some instances of ProfileInformation are then added to arraylist, and then I get one of the instances from the arraylist and try to use getGamertag() to set it to a string:
ProfileInformation profNew = ProfTags.get(ProfTags.size()-1);
String example = profNew.getGamertag();
The problem is example will equal null. Why is this?
First, an Arraylist is a List, try not to confuse that with actual arrays.
Do I need to assign the instance of the class from the array to a new class initializer?
You don't need to get an element out of the Arraylist, no. You can chain many methods together
String example = ProfTags.get(ProfTags.size()-1).getGamertag();
example will equal null. Why is this?
For the same reason any object is null... You never set it equal to anything else
This code runs on my laptop:
public static void main(String[] args) {
ArrayList<ProfileInformation> ProfTags = new ArrayList<>();
element = new ProfileInformation();
element.setGamertag("Actual Gamer tag value");
ProfTags.add(element);
ProfileInformation profNew = ProfTags.get(ProfTags.size()-1);
String example = profNew.getGamertag();
}
Output is:
Actual Gamer tag value
I guess you didn't call setGamertag(String).
I am trying to manipulate an object inside a method like this:
My class Problem:
public class TaxiProblem {
public Problem(final World world, final Agent agent) {
_world = world;
_world.setRandomAgent(_agentPlace);
}
private Place _agentPlace;
// Various other functions
}
and in the function .setRandomAgent() in the class World I am trying to manipulate the Place object in what I want it to be like this:
public void setRandomAgent(Place agentPlace) {
int rand = _random.nextInt(25);
agentPlace = _places.get(rand);
agentPlace.setHasAgent(true);
}
I basically want to grab a random Place from the List _places and have it in the variable agentPlace in .setRandomAgent() which in turn will have it in _agentPlace in the Problem class. I thought this would work since Java passes objects by reference in methods but it didn't and _agentPlace remains null.
By doing this
agentPlace = _places.get(rand);
you are overwriting the reference that was passed to the method and losing access to the object you want to alter.
In your setRandomAgent method, agentPlace is indeed a reference that points to your _agentPlace field, not the field itself. In the line I pasted above, what you do is make that reference point to a different object.
_agentPlace = _world.getRandomAgent();
public Place getRandomAgent() {
int rand = _random.nextInt(25);
Place agentPlace = _places.get(rand);
agentPlace.setHasAgent(true);
return agentPlace();
}
When you pass agentPlace to the method, you are creating a copy of the reference. So if you modify the object, then it would work when you return up the stack. But reassigning the variable makes you lose the object you were working with.
I suspect that your problem lies in the implementations as your understanding of pass by reference I believe is correct. The following code will produce the results you expect - That is, it will first print "Before change", then "I am changed!".
class Program
{
static void Main(string[] args)
{
var problem = new Problem();
}
}
public class Problem
{
public Problem()
{
var toChange = new ClassToChange();
toChange.ChangeMe = "Before change";
Console.WriteLine(toChange.ChangeMe);
var changer = new ClassThatChanges();
changer.ChangeSomething(toChange);
Console.WriteLine(toChange.ChangeMe);
Console.ReadLine();
}
}
public class ClassToChange
{
public string ChangeMe { get; set; }
}
public class ClassThatChanges
{
public void ChangeSomething(ClassToChange classToChange)
{
classToChange.ChangeMe = "I am changed!";
}
}