Getting a constructor error in processing - constructor

I'm playing with processing from some days, but I encountered an error that i didn't understand. I declared the class and the constructor with the proper arguments, maybe you can help me. This is the code:
Cell[][] grid;
int rnc = 5;
int side = 5;
void setup(){
size(rnc*side,rnc*side);
grid = new Cell[rnc][rnc];
for(int i = 0; i < rnc; i++){
for(int j = 0; j < rnc; j++){
grid[i][j] = new Cell(i,j);
rect(grid[i][j].row*side,grid[i][j].column*side,side,side);
}
}
}
void draw(){}
class Cell
{
boolean isChecked;
int row,column;
int side;
void Cell(int trow, int tcolumn){
row=trow;
column=tcolumn;
}
void toggleCheck(){
if(isChecked == true){
isChecked = false;
}else{
isChecked = true;
}
}
}
The error I got after i tried to ran the program is : The constructor sketch.Cell(int,int) is undefined.
Thank you in advance.

I'm assuming this is Java, although you haven't specified a language. If so, this is the problem:
void Cell(int trow, int tcolumn){
row=trow;
column=tcolumn;
}
That's not a constructor. That's a method called Cell, with a void return type. You meant:
Cell(int trow, int tcolumn){
row=trow;
column=tcolumn;
}
(Or possibly public Cell(...).)
At that point, you should be okay. Note that this would have been a compile-time error - not an execution-time error. Don't try to run your code until it compiles.
Also, it's not clear why you've made your constructor parameters trow and tcolumn - what's the t meant to be for? I'd also make your variables private, and final if possible, and simplify your toggleCheck method. For example:
public final class Cell {
private final int row, column;
private boolean checked;
// It's not clear what side was for
public Cell(int row, int column) {
this.row = row;
this.column = column;
}
public void toggleChecked() {
checked = !checked;
}
public boolean isChecked() {
return checked;
}
}

Related

Why am I getting an java.lang.ArrayIndexOutOfBoundsException exception?

I am writing the following code for a program that returns a boolean of whether or not three consecutive numbers in an array of ints add up to 7. I am getting the following exception instead of the output that I want: "java.lang.ArrayIndexOutOfBoundsException:5". Please can someone explain how I can fix this issue?
public static void main(String[] args) {
int[] numbers ={2,1,5,1,0};
System.out.println(luckysevens(numbers));
}
public static boolean luckysevens(int array[]) {
boolean isLucky= false;
for (int i=0; i<=array.length; i++){
if (array[i]+array[i+1]+array[i+2]==7){
isLucky=true;
}
else {
i++;
}
}
return isLucky;
}
}
Because you are accessing the array elements beyond its length.
For an array of length L, you can access elements in index range of 0 to L-1.
The above exception arises when you access elements beyond this index range.
You don't even need to increment in the else condition.
public static void main(String[] args) {
int[] numbers ={2,1,5,1,0};
System.out.println(luckysevens(numbers));
}
public static boolean luckysevens(int array[]) {
boolean isLucky= false;
for (int i=0; i<array.length-2; i++){
if (array[i]+array[i+1]+array[i+2]==7){
isLucky=true;
}
}
return isLucky;
}
}
You're comparing from 0 - 5 (i.e. 6 elements, but your array has only 5), so you're going out of the bounds.
All you have to do is to go from 0 - array.length-1; therefore have to change condition part i<=array.length; to like this i<(array.length-1);
public static void main(String[] args) {
int[] numbers ={2,1,5,1,0};
System.out.println(luckysevens(numbers));
}
public static boolean luckysevens(int array[]) {
boolean isLucky= false;
for (int i=0; i<(array.length-1); i++){
if (array[i]+array[i+1]+array[i+2]==7){
isLucky=true;
}
else {
i++;
}
}
return isLucky;
}
public static void main(String[] args)
{
int[] numbers ={2,1,5,1,0};
System.out.println(luckysevens(numbers));
}
public static boolean luckysevens(int array[])
{
boolean isLucky= false;
//Use array.length-2 in the code
for (int i=0; i<=array.length-2; i++)
{
if (array[i]+array[i+1]+array[i+2]==7)
{
isLucky=true;
return isLucky;
}
}
return isLucky;
}

Mockito and JUnit issue

I have this test:
#Test
public void shouldReturn2Hours() {
Float expectedHours = 2f;
WorkChronometer workChronometer = Mockito.mock(WorkChronometer.class);
Mockito.when(workChronometer.getAccumulatedMinutes()).thenReturn(120);
Assert.assertEquals(expectedHours, workChronometer.getAccumulatedHours());
}
and the implementation of WorkChronometer:
public class WorkChronometer {
private DateTime startingInstant;
private DateTime stoppingInstant;
private Boolean counting;
//More methods
public Integer getAccumulatedMinutes() {
if (counting)
throw new RuntimeException("Call stopCount first!");
if (startingInstant == null || stoppingInstant == null)
return 0;
return Minutes.minutesBetween(startingInstant, stoppingInstant).getMinutes();
}
public Float getAccumulatedHours() {
Integer accumulatedMinutes = getAccumulatedMinutes();
return accumulatedMinutes / 60f;
}
}
When I execute the test, it fails:
junit.framework.AssertionFailedError: expected:<2.0> but was:<0.0>
But I don't know why. It seems the mock is not returning what I want.
What am I doing wrong?
Thanks.
You're mocking the class under test. Doing that relaces all the methods by methods doing nothing, and returning default values.
If you want to do that, you'll need a spy, or a partial mock.
With a spy:
#Test
public void shouldReturn2Hours() {
Float expectedHours = 2f;
WorkChronometer workChronometer = new WorkChronometer();
WorkChronometer spy = Mockito.spy(workChronometer);
doReturn(120).when(spy).getAccumulatedMinutes();
Assert.assertEquals(expectedHours, spy.getAccumulatedHours());
}
With a partial mock:
#Test
public void shouldReturn2Hours() {
Float expectedHours = 2f;
WorkChronometer workChronometer = Mockito.mock(WorkChronometer.class);
Mockito.when(workChronometer.getAccumulatedHours()).thenCallRealMethod();
Mockito.when(workChronometer.getAccumulatedMinutes()).thenReturn(120);
Assert.assertEquals(expectedHours, workChronometer.getAccumulatedHours());
}

Seems scheduleUpdate not working

I'm trying to create a ScrollView class with cocos2d-2.0-rc2-x-2.0.1 and I mean to do something in update function to implement the auto-scroll effect.Unfortunately,I find the function has never been called.Though I've done a lot of work like searching on the internet,debuging step by step and so on,the possible solutions I found helped little.
As far as I know,my ScrollView class derive from CCNode and I've implemented the update function.The declaration of ScrollView is as following:
class ScrollView:public CCNode,public CCTouchDelegate
{
ClippingNode* visible_view;
CCNode* content_view;
//CCArray* items;
float row_margin;
float col_margin;
float interval_margin;
float last_y;//起始y方向坐标
float interval_dis;//间隔时间段内y方向上的位移。
bool touch_stopped;//标识触摸是否停止,主要用于自动滚动。
float up_bounder_y,down_bounder_y;//content_view的y方向坐标上下限
int items_num;
public:
static ScrollView* New(CCSize visible_view_size,float row_margin,float col_margin,float interval_margin,CCNode* background = NULL);
void ccTouchBegin(cocos2d::CCNode *node,const cocos2d::CCPoint &point);
void ccTouchMove(cocos2d::CCNode *node,const cocos2d::CCPoint &point);
void ccTouchEnd(cocos2d::CCNode *node,const cocos2d::CCPoint &point);
virtual void onEnter();
protected:
CCNode* makeCard();
void initContent();
private:
ScrollView():visible_view(NULL),content_view(NULL),touch_stopped(true){}
virtual ~ScrollView();
bool init(CCSize visible_view_size,float row_margin,float col_margin,float interval_margin,CCNode* background);
void update(float dt);
};
And here is the definition of update function:
void ScrollView::update(float dt)
{
CCLOG("update");
if(touch_stopped)
{
if(abs(interval_dis) < a)
{
interval_dis = 0.0f;
this->unscheduleUpdate();
}else
{
if(interval_dis < 0)
interval_dis += a;
else
interval_dis -= a;
const float future_y = content_view->getPositionY() + interval_dis;
if(future_y > down_bounder_y && future_y < up_bounder_y)
{
content_view->setPositionY(interval_dis);
}else if(future_y <= down_bounder_y)
{
content_view->setPositionY(down_bounder_y);
interval_dis = 0.0f;
}else
{
content_view->setPositionY(up_bounder_y);
interval_dis = 0.0f;
}
}
}
}
So I can ensure the type of the param is float instead of CCTime or ccTime which may cause update function never to be called.Moreover,I invoke the scheduleUpdate in the init method like the following:
bool ScrollView::init(CCSize visible_view_size,float row_margin,float col_margin,float interval_margin,CCNode* background)
{
visible_view = ClippingNode::New(visible_view_size);
CHECK_RETURN(visible_view,NULL,false);
visible_view->retain();
content_view = CCNode::create();//node函数中已调用autorelease
CHECK_RETURN(content_view,NULL,false);
content_view->retain();
this->row_margin = row_margin;
this->col_margin = col_margin;
this->interval_margin = interval_margin;
this->setAnchorPoint(ccp(0.5f,0.5f));
this->setContentSize(visible_view_size);
visible_view->setPosition(0,0);
content_view->setAnchorPoint(ccp(0,1));
content_view->setPosition(row_margin,visible_view_size.height);
content_view->setContentSize(CCSize(visible_view_size.width - 2 * row_margin,2 * col_margin));
this->addChild(visible_view);
visible_view->addChild(content_view);
down_bounder_y = visible_view_size.height;
up_bounder_y = content_view->getContentSize().height > visible_view_size.height?content_view->getContentSize().height:visible_view_size.height;
UserData* user_data = UserData::getUserData(this,true);
CHECK_RETURN(user_data,NULL,false);
user_data->setContainer(true);
items_num = 0;
initContent();
if(background)
{
background->setScaleX(visible_view_size.width/background->getContentSize().width);
background->setScaleY(visible_view_size.height/background->getContentSize().height);
background->setAnchorPoint(ccp(0.5f,0.5f));
background->setPosition(visible_view_size.width/2,visible_view_size.height/2);
user_data = UserData::getUserData(background,true);
user_data->setHitable(false);
this->addChild(background,-1);
}
this->scheduleUpdate();
return true;
}
Through debug,I can ensure the sentence "this->scheduleUpdate()" is invoked.In addition,I created a ScrollView object named scroll_view and added it to the main node through addChild function.So,where am I wrong?Any addvice would be appreciated and thanks for watching:p
I forgot to invoke the CCNode::onEnter in my own onEnter function. Thus all we need to do is invoke CCNode::onEnter in the ScrollView::onEnter. Hope other people don't make the mistake as I did.
If you invoke the onEnter, scheduleUpdate() may be not working.
CCDirector::sharedDirector()->getScheduler()->scheduleUpdateForTarget(this,0,false);
or
CCDirector::sharedDirector()->getScheduler()->scheduleSelector(schedule_selector(NewGame::update),this,0.1,false);
Dont know why your code is not working but have you tried this:
CCDirector::sharedDirector()->getScheduler()->scheduleUpdateForTarget(cocos2d::CCObject *pTarget, int nPriority, bool bPaused);
you can check whether the node responds to update() call using:
pNode->getIsRunning();

Get all static variables in a class

I have this ObjectType class which is a class to help me do something like this:
object.type = ObjectType.TWO
//ObjectType.as
package
{
public class ObjectType
{
public static var ONE:String = "one";
public static var TWO:String = "two";
public static var THREE:String = "three";
public function ObjectType()
{
}
}
}
Let's suppose I'm creating a new class and I need a property named type. In that property set function I want to make sure that it's value is one of the ObjectType variables. How can I achieve this?
public function set type(value:String):void
{
for (var o:Object in ObjectType) {
if (value == o)
this._type = value;
} else {
//error
}
}
}
Not performance aware but without modifying anything you can use describeType function to check the static field and get the value back:
function valueInClass(clazz:Class, value:*):Boolean {
return describeType(clazz).variable.(clazz[#name.toString()] == value).length() != 0
}
public function set type(value:String):void
{
if (valueInClass(ObjectType, value)) {
this._type = value;
} else {
//error
}
}
I suppose the second code example you presented doesn't work...
I think it is because you're using the for in loop a little bit wrong.
for (var blah:String in somewhere){
// blah represents a KEY of the somewhere object
// to get the value of this key, use:
var theValue = somewhere[blah];
}
It's the for each loop that loops through the values. But for now I'll use the for in.
Also, it's not in ObjectType, but rather in the class' prototype, that is in ObjectType.prototype.
So, to fix this:
for (var o:* in ObjectType.prototype) {
if (value == ObjectType.prototype[o])
this._type = value;
} else {
//error
}
}
You can solve this using reflection.
A similar question was asked just a few days ago, you should be able to use the same solution, found here.
It should be noted that while the the accepted answer is right, it's also really slow. Not something that you want to do a lot. There are three simpler solutions.
One: Check the value itself:
public function set type(value:String):void
{
if( value != ObjectType.ONE && value != ObjectType.TWO && value != ObjectType.THREE )
return;
}
Obviously, the more constants you have the check the harder this becomes.
Two: Use ints as your constants
Change your ObjectType class to use ints:
public class ObjectType
{
public static var NONE:int = 0;
public static var ONE:int = 1;
public static var TWO:int = 2;
public static var THREE:int = 3;
public static var TOTAL:int = 4;
}
Notice the NONE and TOTAL in there? This makes it easy to check if your value is in the right range:
public function set type(value:int):void
{
if( value <= ObjectType.NONE || value >= ObjectType.TOTAL )
return;
}
You can add more values as needed and you just need to update TOTAL and it'll still work. This needs each value to be in order though.
Three: Use Enums
While Flash has no in-build class for enums, there's a lot of solutions available. Check our the Enum class from Scott Bilas: http://scottbilas.com/blog/ultimate-as3-fake-enums/
Using this as your base class your ObjectType class becomes:
public final class ObjectType extends Enum
{
{ initEnum( ObjectType ); } // static ctor
public static const ONE:ObjectType = new ObjectType;
public static const TWO:ObjectType = new ObjectType;
public static const THREE:ObjectType = new ObjectType;
}
And your check now becomes:
public function set type(value:ObjectType):void
{
...
}
Here, your setter now becomes type safe and will throw errors if anything other than an ObjectType is used.
It turns out that if using an ENUM type of check you should check for the constants property, not variables as showin in the example here:
ActionScript - Determine If Value is Class Constant

How do I implement a fibonacci sequence in java using try/catch logic?

I know how to do it using simple recursion, but in order to complete this particular assignment I need to be able to accumulate on the stack and throw an exception that holds the answer in it.
So far I have:
public static int fibo(int index) {
int sum = 0;
try {
fibo_aux(index, 1, 1);
}
catch (IntegerException me) {
sum = me.getIntValue();
}
return sum;
}
fibo_aux is supposed to throw an IntegerException (which holds the value of the answer that is retireved via getIntValue) and accumulates the answer on the stack, but so far I can't figure it out. Can anyone help?
I don't know what your implementations for fibo_aux and IntegerException look like, but the following two implementations work with your existing code (I don't think there's anything wrong with the code you posted, so I assume something is awry in either fibo_aux or IntegerException). Maybe you'll find this helpful.
public static void fibo_aux(int index, int a, int b) throws IntegerException
{
if (--index > 0)
fibo_aux(index, b, a + b);
else
throw new IntegerException(a + b);
}
An implementation for IntegerException:
public class IntegerException extends Exception
{
private static final long serialVersionUID = -6795044518321782305L;
private Integer intValue;
public IntegerException(int i)
{
this.intValue = i;
}
public Integer getIntValue()
{
return intValue;
}
}
Here you go :
public class ExcFib {
/**
* #param args
*/
public static void main(String[] args) {
new ExcFib().fibo ( 10 );
}
class FiboException extends Throwable
{
public int n;
public FiboException(int n)
{
this.n = n;
}
private static final long serialVersionUID = 1L;
}
public void fibo(int idx) {
try {
fibo_aux(idx-1,1,1);
} catch (FiboException e) {
System.out.println ( "F(" + idx + ") = " + e.n );
}
}
private void fibo_aux(int i, int j, int k) throws FiboException {
if ( i < 1 )
{
throw new FiboException(k);
}
fibo_aux(i - 1, k, j + k );
}
}