How to get proper modulus in java.

-3 % 5 should return 2
Java returns -3 instead. This is wrong since the sign should equal the divisor's.
Is there some builtin method/library in java which returns the correct value?
I know this can be fixed by using an if/while statement to check whether the number is negative, but I don't want that.

    public static void main(String[] args) throws Exception {
        System.out.println(mod(-3, 100));
        System.out.println(mod2(-3, 100));
    public static int mod(int a, int b) {
        return Math.abs(b) % Math.abs(a);
    public static int mod2(int a, int b) {
        return ((a%b)+b)%b;
    }Mine print outs 1
Yours prints out 97
How is your method giving the modulus?

Similar Messages

  • How to get return value from Java runtime.getRuntime.exec?

    I'm running shell commands from an Oracle db (11gr2) on aix.
    But, I would like to get a return value from a shell comand... like you get with "echo $?"
    I use a code like
    CREATE OR REPLACE JAVA SOURCE NAMED common."Host" AS
    import java.io.*;
    public class Host {
      public static int executeCommand(String command) {
        int retval=0;
        try {
            String[] finalCommand;
            finalCommand = new String[3];
            finalCommand[0] = "/bin/sh";
            finalCommand[1] = "-c";
            finalCommand[2] = command;
          final Process pr = Runtime.getRuntime().exec(finalCommand);
          pr.waitFor();
       catch (Exception ex) {
          System.out.println(ex.getLocalizedMessage());
          retval=-1;
        return retval;
    /but I do not get a return value... because I don't know how to get return value..
    Edited by: user9158455 on 22-Sep-2010 07:33

    Hi,
    Have your tried pr.exitValue() ?
    I think you also need a finally block that destroys the subprocess
    Regards
    Peter

  • How to get the parameter from Java Script into the Parameter crystal Report

    Hi All,
    Crystal Report is integrated with Oracle 10g. I created the base SQL query for col1, col2, col3 and col4. Java Script pass parameter value (185) to Col1.
    My question is how to create crystal report to make Col1 as parameter and how to get the parameter value 185(Col1) from Java Script. Is there any additional code I need to include in the crystal report?
    FYI.
    Java script sends the right parameter value.There is no issue in java script.
    This is an automatic scheduled process when batch runs, Java script should pass the parameter value and the crystal report should get the value and produce the output report.

    Not sure if this is an application question or if you are trying to hook into Crystal Reports parameter UI? If the later then no option other than report design. If an application then I can move this to the Java Forums.
    If you are asking how to alter the parameters I suggest you remove the Java reference and post a new question so it's not confusing the issue.
    Please clarify?

  • How to get rid of the java update virus?

    Everytime i go on a web page something pops up saying to install Java Runtime Environment in order to web content and it gives me the option to click more info (to go to the page to download the Java Runtime Environment) OR ok. Before i clicked ok until it continued to pop and and began to annoy me so i decided to install it. It still pops up and won't go away. I found out it is a virus and i don't know how to get rid of it.
    PLEASE HELP!

    Most likely, you have a web plugin that depends on the Java runtime distributed by Apple, such as the Facebook video calling plugin or the "NexDef" plugin for watching baseball streams. If you no longer need the plugin, remove it. Otherwise, install Java.

  • How to get rid of the java icon on the window

    There is a java icon(top right habd corner) on every window panel.
    How to get rid of it?

    What r u using, AWT r JAVA Swing? would please explain
    ur problem clearlyLOL. No offense, but you might consider phrasing your responses clearly as well...
    r == "are" || r == "or" || r == "argh" :o)
    §

  • How to Get Proper Video Screen Captures (Screencasts) of Photoshop and Lightroom in Win?

    Hello. I would like to get proper screen captures of Lightroom and Photoshop on Win 7/64, showing all screen elements as you see them. I tried FastStone Capture 8 and SnagIt 11.1, but they have various differing issues. Do you have a good hint?
    What's more: In my screen capture, i also want a mouse-click-sound each and every time the mouse is clicked. This is not "system audio", because the computer doesn't play a sound for every ordinary click. The capture software must add that sound. (I'm aware i can add the sound manually in post production, but want it recorded together with video.)
    Experience with Faststone Capture 8's video captures:
    I get well usable footage
    Does optionally record mouse-click-sound for each click, with adjustable volume
    Does not properly record some elements of Photoshop or Lightroom screens:
      - cursors sometimes look rough or double-sized 
    - Lightrooms "TAT (Target Correction Tool)" disappears while being dragged on the image
    - the color selector box of Lightroom's Adjustment Brush is not shown, while the cursor working within that color selector box is shown
    - Lightroom's three-second-splash-message after Undo etc. is not shown
    (All these missing elements do show up in *still* captures with Faststone Capture. They also *do* show up in video captures done with SnagIt, see below)
    Experience with Snagit 11.1's video captures:
    Does properly capture all those elements that FastStone does *not* capture (listed above)
    Does *not* optionally include a mouse-click-sound for each and every mouse click (they record "system audio", but a sound on every click is not "system audio", so a regular click on a menu item has no sound)
    Videos are less smooth, cursor sometimes "jumping"
    Now, do you know a screen capture software for Win 7 that can
    properly record *anything* that's seen within Lightroom and Photoshop
    and automatically add a mouse-click-sound for each and every click i do
    and produce smooth footage without "jumping cursors"?
    Thanks for your real-life experiences!

    Myles, thanks again, here are my findings with Camtasia:
    Camtasia:
    DOES record overlays like adjustment brush's colour selector
    .camrec format isn't offered for recording, only .trec and .avi (on Win 7), but trec is usable just as .camrec i guess
    Exported MP4 looks blurry and has colour blotches, that are not visible in the initial recording, only after exporting; this doesn't change at all after setting very high quality MP4 options; i guess i didn't look properly
    i see how to add mouse-click sounds; i don't like the sound they provide so much; maybe it can be exchanged.
    Other tests:
    Camstudio:
    mouse click sounds very weird (my mistake?)
    does NOT record LR overlays like adjustment brush's colour selector
    Screen-cast-o-matic, optionally online, free version:
    DOES record overlays like adjustment brush's colour selector. Mouse-click-sound not in free version. "System audio" is promised in paid version, but that does not necessarily mean a sound for each mouse-click. Contacted support for more
    Straightforward using, lots of short video tutorials (useful for absolute beginners).
    Free downloaded program 1.4 only works on primary monitor, the online launched app also records on secondary monitor
    Don't see option to record a "window", only set resolutions
    More "jumpy" than Faststone
    More interesting pro-version seems to be rent-only-licenced, at 15 USD per year, not a one-time-buy

  • How to get printer IPAddress using java code

    Hi all,
    Can some one suggest in java
    1) how to get printer IPaddress
    2) send a printer job to a particular printer either by using printer name or by printer IPaddress ?

    Hi all,
    Can some one suggest in java
    1) how to get printer IPaddress
    2) send a printer job to a particular printer either by using printer name or by printer IPaddress ?

  • How to get stylesheet object from JAVA RESOURCE stored in DB

    Hi,
    I stored a xslt file in the database and have a JAVA RESOURCE file now. How can i get a stylesheet object from this resource file?
    I took the following class to get an impression how to get the contents of the resource but -although the name of the resource was spelled correctly- i got a file not found exception.
    Whats wrong?
    public class PrintRessource {
    public static void print (String p_ressource){
    try {
    Class c = PrintRessource.class;
    System.out.println(c.toString());
    InputStream file = c.getResourceAsStream(p_ressource);
    if (file == null)
    throw new FileNotFoundException("XSLT file not in DB");
    byte[] buffer = new byte[4096];
    int bytes_read;
    while ((bytes_read = file.read(buffer)) != -1)
    System.out.println(new String(buffer, 0 , buffer.length));
    catch (Exception exp) {
    System.out.println(exp);
    Thanks

    The code works as is. I just forgot to add the slash in front of the Resource file name.

  • af:chooseDate - how to get selected month in java class

    <af:chooseDate id="choose_date_ID"
    binding="#{EventsBackingBean.choose_date_ID}">
    </af:chooseDate>
    in adf ,how to get the selected month value in the component.
    and if we change the the month from the drop down,then again new value should be reflected in java class.

    Hi Hoque,
    As per the documentation of af:choose at http://download.oracle.com/docs/cd/E12839_01/apirefs.1111/e12419/tagdoc/af_chooseDate.html
    "In order to indicate that a particular inputDate should be updated in response to chooseDate selection changes, the the inputDate's "chooseId" attribute must be set to the id of the associated chooseDate component.ts mentioned that the the af:choose "
    So, i believe that if you can create a binding to the af:inputDate component in your backing bean, you can extract the newly selected date in a ValueChangedListener using the getValue() function on the bound component.
    private RichInputDate chooseDateInput;
        public void setChooseDateInput(RichInputDate chooseDateInput) {
            this.chooseDateInput = chooseDateInput;
        public RichInputDate getChooseDateInput() {
            return chooseDateInput;
        public void chooseDateInput(ValueChangeEvent valueChangeEvent) {
          Date selectedDate = (Date)chooseDateInput.getValue();
        }Regards,
    Ryan

  • How to get SEO url in java

    Hi
    My requirement is to generate a product feed which has its product url as one of the fields.
    Now does anybody know how to get the SEO url of a product in a java file.
    I know form front end we generate it via ItemLinkDroplet.
    But is there a way i can generate it in my java class?
    Thanks

    Assuming you have used ATG SEO Repository and ATG DirectUrlTemplate and IndirectUrlTemplate etc..for SEO URL generation.
    Now, create a standalone jsp, example, seolinkbuilder.jsp.
    Let it take following parameters,
    productId
    categoryId
    brandId
    siteId
    and any other ids as needed by your application.
    Suppose you just needed SEO url for a given product id.
    /contextpath/seolinkbuilder.jsp?productId=12345
    The JSP would contain a droplet which would construct a SEO url and set it as oparam which can be written to JSP.
    Finally, from an independent JAVA program, using Apache HTTPClient API, call seolunkbuilder.jsp by passing productId. Read the response for SEO url.
    Let me know if you have further questions.

  • How to get applets running with Java Plug-in on Win but also on Mac OS X???

    I've converted to the use of Java Plug-in for my applets, but I need to have those same applets executable from browsers on Mac OS X platform. Surely this has been done, but I don't see how. The browsers I've tried on Mac OS X (Netscape, IE) don't seem to recognize the <OBJECT> tag used for the java plug-in. I've seen no news about the Java plug-in being ported to Macs. How can one get the same applet to run with the Java plug-in on Windows browsers, and also to run with at least one of the common browsers on Mac OS X? Any help would be SO much appreciated!

    Those ten dukes look good to me. But the passing of fifteen months has me thinking you've probably moved on. In any case, here's my effort.
    I've been through a trial trying to get my applet, developed with 1.4.1_03, to run on my Mac OS X v.10.2.6 in multiple browsers. I'm posting my results here. Comments and feedback are welcome.
    JVM support for 1.4.1 is limited to the Safari browser. All other browsers running in Mac OS X that I've tried ( Camino, Opera, Internet Explorer, Mozilla ) are using the 1.3.1 plugin. According to a bug report by Mozilla on this topic ( see Bugzilla Bug # 197813 http://bugzilla.mozilla.org/show_bug.cgi?id=197813 )
    with the release of Apple's version of Sun's Java 1.4.1 the applet programming model has changed, and only Safari has adapted with this change. Other browsers, according to the report, could not because of a lack of documentation. The use of the MRJCarbon plugin offered by Mozilla (here - http://www.mozilla.org/oji/MRJPluginCarbon.html) only allows Mozilla to use the J 1.3.1. And I have not found any information on the Microsoft site about how to get IE 5.2 to recognize the newer version of Java.
    Regarding the use of the OBJECT tag in Safari, it is a matter of debate. A current post on this topic exists in the Applet Development forum:
    http://forum.java.sun.com/thread.jsp?forum=421&thread=441002
    In my experience, I have not been able to determine that Safari v1.0 recognizes the OBJECT tag. My experience is that the APPLET tag is required to run applets in Safari. The Bugzilla report echoes the problem with the BadMagicNumber error that can arise in Safari. Nonetheless, I enjoy Safari and I enjoy Mac OS X.

  • How to get php content with java ??

    i have made a php file what will display a number,
    here's a example
    <?php
    if ($action == "answer"){
    echo "18274926";
    ?>
    no i want to get the number with java
    so here's my java code
    import java.io.*;
    import java.net.*;
    import java.util.Date;
    class URLConnecties
        public static void main(String args[]) throws Exception
            int teken;
            URL url = new URL("http://www.gamer.mineurwar.nl/net/javachallenge.php?command=DaTe");
            URLConnection urlconnection = url.openConnection();
            System.out.println("Type inhoud: " +
                urlconnection.getContentType());
            System.out.println("Datum document: " +
                new Date(urlconnection.getDate()));
            System.out.println("Laatst gewijzigd: " +
                new Date(urlconnection.getLastModified()));
            System.out.println("Document vervalt: " +
                urlconnection.getExpiration());
            int lengteinhoud = urlconnection.getContentLength();
            System.out.println("Lengte inhoud: " + lengteinhoud);
            if (lengteinhoud > 0) {
                InputStream in = urlconnection.getInputStream();
                while ((teken = in.read()) != -1) {
                    System.out.print((char) teken);
                in.close();
    }if you change the url ro a .html file it displays the code correctly(source),
    but when trying to get the content of a php file (the number)
    it says that there is no content from the php file
    yhe source of the original php file what's in the code can be found at
    www.gamer.mineurwar.nl/net/javachallenge.txt

    The 'content' is generated dynamically by a PHP script so the "content lenght" can't be known in advance by the server. For this reason connection.getContentLenght() returns -1; it doesn't mean that there is no content, only that it can't be known how much there will be.
    To solve the issue, remove the if statement from around the while-loop:// if (lengteinhoud > 0) { DELETE THIS LINE
    InputStream in = urlconnection.getInputStream();
    while ((teken = in.read()) != -1) {
        System.out.print((char) teken);
    // } and this too

  • How i get hardware info with Java Applet

    Hello Everybody.
    first I am sorry for my english. This my first topic. I am a php developer and learning Java. I am developing a Java Applet.
    Can i get client hardware info with Java Applet
    Ýf i can How i do get hardware info with Java Applet.
    I need sample code or documentation.
    Thanx.

    TrojanMyth wrote:
    Hello;
    Can i get hardware info with Java ?? Have not a know people ?Applets are restricted, unless, as already noted, they are signed and accepted by the user. See
    http://java.sun.com/docs/books/tutorial/deployment/applet/security.html
    http://java.sun.com/docs/books/tutorial/deployment/applet/properties.html
    In general, since Java is designed to run on multiple operating systems and machine architectures it does not provide much access to the underlying hardware. As mentioned, you can access the os via methods in the java.lang.ProcessBuilder and Runtime classes.

  • IPC:How to get  ITM_TYPE val in java PricingExit?

    hi friends,
    I have to write a requirement formula in the pricingexit of IPC. I need the value of item type (Item Category) of a CRM document. However i can't find any methods like
    "getItemType" or something like that.
    Does anybody know how to get the value of item category of an item of a CRM document ?
    Or as an alternative way of reaching the same item type value :
    does anybody know the way to add new attributes coming from CRM to IPC? i may add a new field in pricing (ZZITM_TYPE)and fill it in the pricing BADIs of CRM system. After that, I may read the value of ZZITM_TYPE in the IPC pricingexit under
        public boolean checkRequirement(IConditionFindingManagerUserExit item,
      IStep step, int reqNo) {
            switch (reqNo) {
                case 911:
        // how to read the value of item category of
        // an item of a CRM document(bussiness transaction)
        // right here ??
      thanks in advance for your interest and valuable help.
      Mehmet Karasu
      Arista Consulting

    Hi Mehmet
    You are right with your "alternative".
    All attributes needed for pricing should be added to the field catalog (and thus the communication structure). You can fill the communication structure value via the BAdi CRM_COND_COM_BADI.
    Once you have done this and checked it in the ABAP debugger, you need to explicitly provide that attribute to your routines:
         public String[] determineRelevantAttributesForScaleBaseFormula(boolean headerAttributes,
                                                int scaleBaseFormulaNo) {
    //           Header?
              if (headerAttributes) {
                   // KOMK fields
                   return new String[] { };               
    //           Item
              else {          
                   return new String[] { "ZZITM_TYPE" };
    And then you can read it like any other attribute in your routine 911:
    String itemCategory = prItem.getItemAttributeValue("ZZITM_TYPE").getValue();
    Cheers
    Dom
    More info here: https://www.sdn.sap.com/irj/servlet/prt/portal/prtroot/com.sap.km.cm.docs/library/uuid/107adc1a-0501-0010-de8e-973e0fb4049b

  • How to Get Proper Video Screen Captures (Screencasts) of Lightroom or Photoshop in Win?

    Hello. I would like to get proper screen captures of Lightroom on Win 7/64, showing all screen elements as you see them. I tried FastStone Capture 8 and SnagIt 11.1, but they have various differing issues. Do you have a good hint?
    In my screen capture, i want a mouse-click-sound each and every time the mouse is clicked. This is not "system audio", because the computer doesn't play a sound for every ordinary click. The capture software must add that sound. (I'm aware i can add the sound manually in post production, but want it recorded together with video.)
    Experience with Faststone Capture 8's video captures:
    I get well usable footage
    Does optionally record mouse-click-sound for each click, with adjustable volume
    Does not properly record some elements of Photoshop or Lightroom screens:
    - cursors sometimes look rough or double-sized
    - Lightrooms "TAT (Target Correction Tool)" disappears while being dragged on the image
    - the color selector box of Lightroom's Adjustment Brush is not shown, while the cursor working within that color selector box is shown
    - Lightroom's three-second-splash-message after Undo etc. is not shown
    (All these missing elements do show up in *still* captures with Faststone Capture. They also *do* show up in video captures done with SnagIt.)
    Experience with Snagit 11.1's video captures:
    Does properly capture all those elements that FastStone does *not* capture (listed above)
    Does *not* optionally include a mouse-click-sound for each and every mouse click (they record "system audio", but a sound on every click is not "system audio")
    Videos are less smooth, cursor sometimes "jumping"
    Now do you know a screen capture software for Win 7 that can
    properly record *anything* that's seen within Lightroom and Photoshop
    and automatically add a mouse-click-sound for each and every click i do
    and produce smooth footage without "jumping cursors"?
    Thanks for your real-life experiences!

    Hi, thanks for your suggestions. Now i also tried:
    Camstudio:
    - mouse click sounds very weird (my mistake?), does NOT record LR overlays like adjustment brush's colour selector
    Screen-cast-o-matic, optionally online, free:
    - DOES record overlays like adjustment brush's colour selector. Mouse-click-sound not in free version. "System audio" is promised in paid version, but that does not necessarily mean a sound for each mouse-click. Contacted support for more
    Straightforward using, lots of short video tutorials (useful for absolute beginners).
    Free downloaded program 1.4 only works on primary monitor, the online launched app also records on secondary monitor
    Don't see option to record a "window", only set resolutions
    More "jumpy" than Faststone
    More interesting pro-version seems to be rent-only-licenced, at 15 USD per year, not a one-time-buy
    Camtasia:
    DOES record overlays like adjustment brush's colour selector
    .camrec format isn't offered for recording, only .trec and .avi (on Win 7)
    Exported MP4 looks blurry and has colour blotches, that are not visible in the initial recording, only after exporting; this doesn't change at all after setting very high quality MP4 options; i guess i didn't look properly

Maybe you are looking for

  • ATI Fire GL X1-128 vs Radeon 9700pro?

    What is the main difference in these cards? I think I might have the FireGL instead of the Radeon 9700pro. I was given a bunch of parts when my friend upgraded and he did not tell me what all of it was at the time. This explains the memory problems I

  • Bootcamp program? and Anime Studio 5 Installing help.

    Bootcamp program. Hi i downloaded bootcamp. I have a mac book. When i try extracting the .dmg file and when the new finder window opens. The .pkg icon didnt show up. It wont open and says choose application to open it. I can read the readme files. Bu

  • IPhoto Doesn't Import All of My Raw Images

    I am using a Canon 10D (which is a supported device) to take pictures in RAW format (".crw" extension). I also have a relatively new MacBook with iPhoto 6 and have downloaded all the recent iPhoto updates. The problem is that when attempt to I import

  • ITunes Store video not synching

    I recently purchased an 8 part video series fron iTunes. I've updated my iPod but only parts 7 and 8 are on the iPod although all 8 are shown in iTunes. Any ideas?

  • New iMovie

    Hi sorry I've big problem. You know in the older version of iMovie were always timeline, and in that timeline u caould edit volume in time. I mean I want in the middle of the clip turn the music down and then a few seconds after turn it up again. Can