Print 1 to N numbers without using while/If loop - output

*>printing 1 to a numbers without using if and while ,but this is not working in java
**class printOut{//class started here
static int PrintN(int x)
{
(x>1)?(System.out.println(PrintN(x--))):System.out.println(x);
//above code is recursively calling PrintN to print decreemented value
return 0;
}
public static void main(String args[])
{
int a=10;//initialized variable
PrintN(a);//calling the static method wihout creating its object
}
}***
//my question was to write a program to find out 1 to n numbers without using while or if loops.

Since you want to print, starting at 1, until reaching some initial input number, your logic should be to first make the recursive call, then print afterwards, on the way back. Something like this:
public static void printN(int x) {
if (x > 1) {
printN(x - 1);
}
System.out.println(x);
}
I don't think your recursive method has to return any value, because the number/state to be printed is passed along the method calls. Note also that the base case occurs when the number becomes 1. In this case, we don't make another recursive call, but rather just print ourself and then return to the higher caller.
Demo

Related

Web API controller returns empty JSON even if returned var is not empty

In my API, I have to return a json composed of 2 distinct objects, one is a unique entity and the other a list. When I return each separatly there is no problem, but when I try to return them as a single json, the result is empty, even though my var in the return ok(var) contains what is supposed to be returned.
The controller looks like this:
[System.Web.Mvc.HttpGet]
public IHttpActionResult GetOne(int id)
{
var x = Service.GetOne(id);
return Ok(x)
}
(If I put a breakpoint on the return line, I can see that x contains the single object and the list that I want in my json)
"Service" is where I merge the 2 objects by caling a model constructor that takes the single object and the list as input, it looks like this:
public class mergedObject
{
IEnumerable<SingleObject> y;
IEnumerable<ListObject> z;
public mergedObject GetOne(int Id)
{
mergedObject x = new mergedObject(RepoSingleObject.getOne(Id) a,
RepoList.GetAll(Id) b)
this.y = a
this.z = b
}
It calls the corresponding repository(which contains the sql query) for each object and I know this part is working, since like I said earlier, I can properly return each object individually.
The console returns absolutely no error, I did everything the same way as with the individual objects, except for the merging and when I use breakpoints everything seems to go fine, but yet, using postman to test it, I always get an empty return. Does anyone have an explanation?
EDIT
The controller is derived from ApiController + added full definition of the mergedObject class up there. I use IEnumerable even on the single object because I reuse some part of the code where this single element is in fact a list, so I figured it would only be a list of 1 element and wouldn't cause any problem.

very basic java exception handling

Is there any point in including the "throws ArithmeticException" declaration in the divide method?
try
{
divide(10,0);
}
catch(ArithmeticException e)
{
System.out.println("Exception caught.");
}
}
public static void divide(int x, int y) throws ArithmeticException
{
int result = 0;
result = x / y;
System.out.println("Quotient is " + result);
return;
}
One of the reasons for it is to catch whether your division is done with the denominator as '0'. Anything that is divided by 0 is infinity. Your program won't be able to interpret the result and therefore an exception error will be thrown for the divide method.
ArithmeticException is only thrown when dividing by zero or when working with BigDecimal and not rounding. Since your divide method is working with the "int" data type I would just use an if statement that only allows you to do the division of y does not equal zero.
I noticed this is a void method and you are not doing anything other than printing the result. I am not sure if that is your intention but if you need the value you should consider rewriting this to fit your needs.

Sending Paramters to a CCCallFuncND::create Cocos2d-X

I have the following code in my Cocos2d-X application
void SampleRequest::setResponseCallback(CCCallFuncND* cb){
if(cb){
cb->retain();
stored_cb=cb;
}
}
void SampleRequest::executeStoredCallback(){
if(stored_cb)
stored_cb->execute();
}
void SampleRequest::releaseCallback(){
if(stored_cb){
stored_cb->release();
stored_cb=NULL;
}
}
and a simple class
void RequestHandler::handleSampleRequest(int data){
CCLog("--------------------------------------------> Its here for me to do %d",data);
}
and another peace of code
int i=10;
SampleRequest *t=new SampleRequest();
t->setResponseCallback(
CCCallFuncND::create(
this,
callfuncND_selector(RequestHandler::handleSampleRequest),
(void*)&i));
but the value of i recieved is 0. How can i send the value of I back to the call back function, and how can i send multiple parameters to this function.
Kind Regards,
int i=10;
Are you declaring i as a temporary variable on the stack, rather than on the heap, or as request object instance data?
If so, your i variable will be destroyed when the block within which it is created exits (variable scope ends).
That could explain why the callback receives a value pointing to undefined memory, that has been destroyed at the time of the call.
Try using the new operator, or storing your i value inside your request object up until the cb call is made.
how can i send multiple parameters to this function
You would not ; Simply pass a pointer to a structure or object. If all your stored data is in your "request" instance, you can pass the instance itself, as well.
For an example, assuming, again, that the data passed to the callback is going to remain in memory at the time of the call to the callback function (ie, the "RequestData" instance below):
struct RequestData
{
int value1 ;
int value2 ;
// ....
} ;
class RequestHandler: public cocos2d::CCObject
{
// ...
public:
void requestCallback( CCNode* sender, void* pData ) ;
}
In your implementation:
RequestHandler::requestCallback( CCNode* sender, void* pData )
{
RequestData* pRequestData = static_cast<RequestData*>( pData ) ;
if ( pRequestData )
{
// do something ...
}
}
To construct your call, build an instance of RequestData containing all the data you need to pass to the callback, make sure it is allocated on the heap with "new" or part of another object (in a queue, for instance) so that its data will still be valid in memory at the time the callback is called. I insist a bit on this point because you need some kind of data storage mechanism as part of your design, otherwise your callbacks may find themselves working off invalid addresses in memory (dangling pointers).
Essentially, from your previous code:
RequestData* pRequestData = new RequestData();
// fill in the structure data here...
SampleRequest *t=new SampleRequest();
t->setResponseCallback(
CCCallFuncND::create(
this,
callfuncND_selector(RequestHandler::requestCallback),
(void*)pRequestData));
// Use like this
void* data = (int*) 10;
int value = *((int*) &data);

What is the image of a void function?

If functions are borrowed from the mathematical concept of mapping a value from some set S onto T, then the function:
int increment(int input)
{
return input + 1;
}
would be the mapping from the integers onto the integers. And so the logic goes for most functions, but what about if the return value of a function is void. Does that still fit the mathematical paradigm, or is that a departure, or what is that?

How can I use SWIG to handle a JAVA to C++ call with a pointer-to-pointer argout argument?

The problem involved a JAVA call to a C-function (API) which returned a pointer-to-pointer as an argout argument. I was trying to call the C API from JAVA and I had no way to modify the API.
Using SWIG typemap to pass pointer-to-pointer:
Here is another approach using typemaps. It is targetting Perl, not Java, but the concepts are the same. And I finally managed to get it working using typemaps and no helper functions:
For this function:
typedef void * MyType;
int getblock( int a, int b, MyType *block );
I have 2 typemaps:
%typemap(perl5, in, numinputs=0) void ** data( void * scrap )
{
$1 = &scrap;
}
%typemap(perl5, argout) void ** data
{
SV* tempsv = sv_newmortal();
if ( argvi >= items ) EXTEND(sp,1);
SWIG_MakePtr( tempsv, (void *)*$1, $descriptor(void *), 0);
$result = tempsv;
argvi++;
}
And the function is defined as:
int getblock( int a, int b, void ** data );
In my swig .i file. Now, this passes back an opaque pointer in the argout typemap, becaust that's what useful for this particular situation, however, you could replace the SWIG_MakePtr line with stuff to actually do stuff with the data in the pointer if you wanted to. Also, when I want to pass the pointer into a function, I have a typemap that looks like this:
%typemap(perl5, in) void * data
{
if ( !(SvROK($input)) croak( "Not a reference...\n" );
if ( SWIG_ConvertPtr($input, (void **) &$1, $1_descriptor, 0 ) == -1 )
croak( "Couldn't convert $1 to $1_descriptor\n");
}
And the function is defined as:
int useblock( void * data );
In my swig .i file.
Obviously, this is all perl, but should map pretty directly to Java as far as the typemap architecture goes. Hope it helps...
[Swig] Java: Using C helper function to pass pointer-to-pointer
The problem involved a JAVA call to a C-function (API) which returned a pointer-to-pointer as an argout argument. I was trying to call the C API from JAVA and I had no way to modify the API.
The API.h header file contained:
extern int ReadMessage(HEADER **hdr);
The original C-call looked like:
HEADER *hdr;
int status;
status = ReadMessage(&hdr);
The function of the API was to store data at the memory location specified by the pointer-to-pointer.
I tried to use SWIG to create the appropriate interface file. SWIG.i created the file SWIGTYPE_p_p_header.java from API.h. The problem is the SWIGTYPE_p_p_header constructor initialized swigCPtr to 0.
The JAVA call looked like:
SWIGTYPE_p_p_header hdr = new SWIGTYPE_p_p_header();
status = SWIG.ReadMessage(hdr);
But when I called the API from JAVA the ptr was always 0.
I finally gave up passing the pointer-to-pointer as an input argument. Instead I defined another C-function in SWIG.i to return the pointer-to-pointer in a return value. I thought it was a Kludge ... but it worked!
You may want to try this:
SWIG.i looks like:
// return pointer-to-pointer
%inline %{
HEADER *ReadMessageHelper() {
HEADER *hdr;
int returnValue;
returnValue = ReadMessage(&hdr);
if (returnValue!= 1) hdr = NULL;
return hdr;
}%}
The inline function above could leak memory as Java won't take ownership of the memory created by ReadMessageHelper, since the HEADER instance iscreated on the heap.
The fix for the memory leak is to define ReadMessageHelper as a newobject in order for Java to take control of the memory.
%newobject ReadMessageHelper();
JAVA call now would look like:
HEADER hdr;
hdr = SWIG.ReadMessageHelper();
If you are lucky, as I was, you may have another API available to release the message buffer. In which case, you wouldn’t have to do the previous step.
William Fulton, the SWIG guru, had this to say about the approach above:
“I wouldn't see the helper function as a kludge, more the simplest solution to a tricky problem. Consider what the equivalent pure 100% Java code would be for ReadMessage(). I don't think there is an equivalent as Java classes are passed by reference and there is no such thing as a reference to a reference, or pointer to a pointer in Java. In the C function you have, a HEADER instances is created by ReadMessage and passed back to the caller. I don't see how one can do the equivalent in Java without providing some wrapper class around HEADER and passing the wrapper to the ReadMessage function. At the end of the day, ReadMessage returns a newly created HEADER and the Java way of returning newly created objects is to return it in the return value, not via a parameter.”