Possible loss of precision? Really weird!

Hello!
Can someone help me!? I wrote a short list to experiment with scope for variables.
The list is right below the error-message WHICH BUGS ME TO DEATH!
I can NOT understand where the 'possible loss of precision' could be??
Another strange thing, when I change line 9 to: x += y; ... I get no error!?
---------- Java compiler ----------
Scope.java:9: possible loss of precision
found : int
required: short
               x = x + y;
^
1 error
Normal Termination
Output completed (0 sec consumed).
// The list...
class Scope
     public static void main(String arguments[])
          short x = 10;
          System.out.println("x: " + x);
               short y = 30;
               x = x + y;
               System.out.println(x);
          System.out.println(x);
}

And to make it more confusing, you don't get a loss of precision when you try to add two integers, not even when they sum up to a value bigger (or less) than an int (the result is just cut of to fit in an int, 32-bit).
int x = Integer.MAX_VALUE+5;
long y = Integer.MAX_VALUE+5;
long z = Integer.MAX_VALUE+5L;
System.out.println("x = "+x); // -2147483644
System.out.println("y = "+y); // -2147483644
System.out.println("z = "+z); // 2147483652Actually I thought that y would show the correct result, but it doesn't because adding to ints will still be an int. For z I add an int and a long, so the result is a long. :)

Similar Messages

  • Possible Loss Of Precision Error

    I am a student that is new to Java and I am trying to create a simple Palindrome method.
    I get a "Possible loss of precision" error at:
    first = first + 1;
    Do I have to include something like this:
    userText.charAt(+1)
    to allow it to compile correctly?
    The rest of my code may be a bit off but I am really stuck at this. Thanks for any help :)
    Here is my code:
    public class SimpleInput
    public boolean isPalindrome(String userText)
    int letters = userText.length();
    if (letters <= 1)
    return true;
    else
    char first = userText.charAt(0);
    char last = userText.charAt(letters-1);
    if (first == last)
    while (first == last)
    first = first + 1;
    last = last - 1;
    return true;
    else
    return false;
    Message was edited by:
    jaamki

    Thank you guys so much.
    My class compiles alright, but when I create a new SimpleInput() and use the isPalindrome method, it gives me "Error: cannot find symbol - variable madam". (madam is what I entered as userText).
    It should return true.. but I am completely stuck and it is probably because my code may not be completely finished.
    Explanation please?!
    (Here is my new code:)
    public class SimpleInput
    public boolean isPalindrome(String userText)
    int letters = userText.length();
    if (letters <= 1) {
    return true;
    } else { }
    char first = userText.charAt(0);
    char last = userText.charAt(letters-1);
    if (first == last)
    { while (first == last)      
    first =(char)(first ++);
    last = (char)(last --);
    return true;
    else
    return false;
    }

  • Possible loss of precision and santiy

    I'm having a bit of a problem dealing with bitwise operators and the compiler complaining of
    possible losses of precision (although I know there won't be). So I constructed some "do or die" code ;
    public class byteWise {
         public static void main(String[] args) {
              byte a=1;
              byte b=64;
              byte c= a & b;
    and javac produced this reply:
    D:\Java\byteWise.java:5: possible loss of precision
    found : int
    required: byte
              byte c= a & b;
    ^
    1 error
    What does it mean, "found int, expected byte" ? There's no int in the entire source code.
    Please help!

    Possible loss of precision only denotes that a specific mathematical operation you are performing provides a value that of a data type different than that you are storing it into. It is simply type checking that is performed by the compiler. If you want to bypass this, then you need to do an explitic cast of the data type to the type that you are assigning the value.
    Example:
    double bob = 5.5;
    int jack = 3;
    int sue = bob + jack; //Possible loss of precision.
    int sue = (int)(bob + jack) //This tells the compiler I know what I am doing.
    -Jason Thomas

  • Possible Loss of Precision

    /* * * * * * * * * * * method quadtratize * * * * * * * * * * * * * * * *
    * Method to convert rectangle into a square with approximately the same
    * area - the closest possible for a square with an integer side.
    public int quadratize()
         double recArea = Math.sqrt (myWidth * myHeight);
         double lenSide = recArea / 4;
         return lenSide;
    i need to square root the recArea and round to nearest int. This is what i have so far, but it won't compile because it has a possible loss of precision. any suggestions on how to fix it?

    milanocookies wrote:
    did this.Did what? Your code is the same
    do i change everything to int?It depends on what you are trying to achieve. Is your method supposed to return an int or a double? If double then you need to change your method signature. If int then you need to do what I already said and cast your variable to an int before you return it. If you don'tknow what I mean by "cast" then perhaps you could read about it in your textbook.

  • Possible loss of precision - sorting 3 arrays respectively

    I have the following 2 arrays which need to be sorted according to a high-to-low sorted float array called avg. So float avg[5] is sorted high-to-low, and then String names[] is sorted respectively, for instance, before the sort, names[3]="Marty" and avg[3]=75, and after the sort 75 was in avg[0] because it was the highest, now Marty needs to be in names[0]. The same is with the int scores[5][8] array, the 5 rows need to be sorted corresponding to the new sorted avg array. Anyways here are the arrays and the sorting code i have. I get the error "possible loss of precision." Also the code tag on the forums isnt working for some reason.
    Arrays:
    float avg[]=new float[5];
    int temp[] = {34, 24, 78, 65, 45, 100, 90, 97, 56, 89, 78, 98, 74, 90, 98, 24, 45, 76, 89, 54, 12, 20, 22, 55, 66};
    String names[] = {"Mary","John","William","Debbie","Ralph"};
    int scores[][]= new int[5][8];
    for(a=0;a<=4;a++)
    for(b=0;b<=4;b++,c++)
    scores[a] = temp[c];
    Sort:
    public float sort(int[][] scores,String[] names, float avg[])
    int g,r,c,d,e;
    String q;
    for (r=0;r<=3;r++)
    for (g=r+1;g<=4;g++)
    if (avg[r]<avg[g])
    c=avg[r];
    avg[r]=avg[g];
    avg[g]=c;
    q=names[r];
    names[r]=names[g];
    names[g]=q;
    for(d=0;d<8;d++)
    e=scores[r][d];
    scores[r][d]=scores[g][d];
    scores[g][d]=e;

    The first time I got that error I misread it and got very excited: "possible lots of precision."
    Any way, you should point out the line where this occurs:
    c=avg[r];Here, c is an int and avg[r] a float. When you assign a float to an int, you loose
    the factional data, and as well, float have hold larger values than int. Why not make c a float?

  • Possible loss of precision with pi

    I'm trying to calculate the area of an oval but when I compile I get the error 'possible loss of precision
    public class Shapes extends Applet implements ActionListener
         Button buttonOval, buttonRectangle;                                        //Declaration of button variables
         Font fontVerdana;                                                            //Declare fonts
         TextField textx, texty, textwidth, textheight, areatext;          //Declare text fields
         Label labelx, labely, labelh, labelw;                                   //Declare label fields
         private boolean rectangleYesNo = false;
         final double pi = 3.142;                                //This is the variable I want to use to help calculate the area
         int x;                                                                           //Declare variable x as an integer value
         int y;
         int height;
         int width;
         int arearect;
         int areaoval;
         int radius;Then the code which should execute when the button is pressed (to work out the area) is...
    public void actionPerformed(ActionEvent ev)
              if (ev.getSource() == buttonRectangle)
                   x = Integer.parseInt(textx.getText());
                   y = Integer.parseInt(texty.getText());
                   width = Integer.parseInt(textwidth.getText());
                   height = Integer.parseInt(textheight.getText());
                   rectangleYesNo = true;
                   repaint();
                   arearect = width * height;
                   areatext.setText("The area is = " + arearect + "cm�");
                   areatext.setEditable(false);
              else if (ev.getSource() == buttonOval)
                   x = Integer.parseInt(textx.getText());
                   y = Integer.parseInt(texty.getText());
                   width = Integer.parseInt(textwidth.getText());
                   height = Integer.parseInt(textheight.getText());
                   rectangleYesNo = false;
                   repaint();
                   radius = width/2;
                   areaoval = radius * radius * pi;                  //This is where the error occurs!
                   areatext.setText("The area is = " + areaoval + "cm�");
                   areatext.setEditable(false);
              }I've changed it to float pi = 3.14f; but that still generates this error. Any ideas of how I can get this to successfully compile?
    I appreciate any help.
    Thanks!

    BIJ001 wrote:
    What is the difference?
    int areaoval;
    double areaoval;
    And in case that's not clear - areaoval (sic, standards suggest areaOval instead) is int. You can get rid of the error message by casting the result - which is a double - to an int, but rather, just make the resulting value fit into another double by changing areaOval a double.
    Clarity posting unnecessary ;o)

  • Error: possible loss of precision

    It seems very easy problem. But I can not understand why this is a problem? My code is:
    int items[];
    long current_capacity=250;
    items = new int[current_capacity];I want to get memory from heap that long length and type will be int. Is this illogical? Also, why this is an error? Why not warning?
    Regards.

    public static int consolidate ( Account acct1,Account acct2)
    if (acct1.acctNum == acct2.acctNum)
    System.out.println(" Same account cannot be consolidated\n\t Try again");
    else if (acct1.name.equals(acct2.name))
    return (acct1.balance + acct2.balance) ;
    Th above code in a class gave me a error:Error: possible loss of precision
    Can you help m correct th code-I would appreciate that very much.

  • Why "possible loss of precision"?

    I have a symbolic costant:
    private final byte[] COMANDI = {(byte)0xaa, 0x15, ...};
    then I have:
    byte cmd = Arrays.binarySearch(COMANDI, estraiByte(comando, 1));
    Why loss of precision and here under not?? Both COMANDI and cmd are byte ...
    byte cmd = (byte)Arrays.binarySearch(COMANDI, estraiByte(comando, 1));

    Arrays.binarySearch returns an index into the array. If you want the
    actual byte contents you would have to sayint ndx = Arrays.binarySearch(COMANDI, estraiByte(comando, 1));
    if(ndx < 0) {} // value not found!
    byte cmd = COMANDI[ndx];Obviously the index won't be good if the desired byte value isn't in the
    array.

  • Re: possible loss of precision

    Your problem is, that you are using a double where and int should be, I'm pretty sure. Find the line numbers where it says lost precition, then I can help.

    These are all good ideas on the subject but it is
    because of 64-bit binary...Erm, no. This is a complicated solution that doesn't address the problem. The problem is here:
    pricetotal = Double.parseDouble( Change );
    sum = Change - pricetotal;This code was later modified to this by another poster:
    sum = 0.5 + Double.parseDouble(Change) - pricetotal;To explain, the code is subtracting the value of pricetotal from itself, resulting in zero. This is then subtracted from 0.5, resulting in an answer of 0.5.
    It's simple subtraction, not any floating-point issue.

  • How do i make the compiler ignore loss of precision

    Hi i have the following code:
        public void Q1()
            float p = 665857.0;
            double dp = 665857.0;
            float q = 470832.0;
            double dq = 470832.0;
            p = p * p;
            q = q * q;
            dp = dp *dp;
            dq = dq * dq;
           float ans =  p - 2 * q;
           double ansd = dp - 2 *  dq;
           System.out.println (ans);
           System.out.println (ansd);
        }I get a error saying:
    cw2.java:11: possible loss of precision
    found : double
    required: float
    float p = 665857.0;
    ^
    cw2.java:14: possible loss of precision
    found : double
    required: float
    float q = 470832.0;
    ^
    I know this is happenging and i want the compiler to ignore it and continue..does anyone know what type of throw i need

    try
    float p = (float) 665857.0;
    or
    float p = 665857.0f;IHMO, The best option is don't use float unless it is an assignment or you have a VERY good reason.

  • Loss of Precision error?

    I am supposed to put together a program that does interest for 10 years for each rate of interest and I have to do it for 5,6,7,8,9 & 10 percent. I need to use a inner and outer for loop but for some reason I can't get it to work. I also had to add a scrolling pane to it. Here is my program and the errors it gets.
    import java.text.NumberFormat;
    import java.util.Locale;
    import javax.swing.*;
    public class Interest {
    public static void main( String args[] )
    double amount; // amount on deposit at end of each year
    double principal = 1000.0; // initial amount before interest
    // create NumberFormat for currency in US dollar format
    NumberFormat moneyFormat =
    NumberFormat.getCurrencyInstance( Locale.US );
    // create JTextArea to display output
    JTextArea outputTextArea = new JTextArea(20, 20);
    //attach a scroll pane
    JScrollPane scroller=new JScrollPane(outputTextArea);
    // set first line of text in outputTextArea
    outputTextArea.setText( "Year\tAmount on deposit\n" );
    // calculate amount on deposit for each of ten years
    for ( int year = 1; year <= 10; year++ ) {
    for( int rate=0.05; rate<=0.10; rate++ ){                   
    // calculate new amount for specified year
    amount = principal * Math.pow( 1.0 + rate, year );
    // append one line of text to outputTextArea
    outputTextArea.append( year + "\t" +
    moneyFormat.format( amount ) + "\n" );
    } // end inner for
    } // end outer for
    // display results
    JOptionPane.showMessageDialog( null, scroller,
    "Compound Interest", JOptionPane.INFORMATION_MESSAGE );
    System.exit( 0 ); // terminate the application
    } // end main
    } // end class Interest
    The error is
    Interest.java:31: possible loss of precision
    found : double
    required: int
    for( int rate=0.05; rate<=0.10; rate++ ){
    ^
    1 error
    Any help would greatly appreciated! Thanks!

    Interest.java:31: possible loss of precision
    found : double
    required: int
    for( int rate=0.05; rate<=0.10; rate++ ){
    ^
    1 error
    Any help would greatly appreciated! Thanks!In line 31 of your source code, you are assigning a double literal into an int variable. Since ints are whole numbers only, you will lose precision. In other words, setting int rate to 0.05 will actually set rate to 0. After the first execution of the loop, rate++ will set rate to 1, and the loop will exit.
    You need to make rate a double, and increment by the increment value ...
    for( double rate=0.05; rate<=0.10; rate += <someDoubleAmount> ){World spins
    RD-R
    � {�                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

  • Loss of precision

    Hi
    I have two variables:
    byte chksum;
    byte extr;
    I need to calculate a checksum by a simply xor:
    for ( ...) {
    chksum = chksum ^ extr;
    but the compiler says "possible loss of precision"; my checksum must have only one byte ...
    Do u have any suggestion?
    Thanks

    In 'byte' operations such as chksum ^ extr the arguments are first converted to integer so the result is an integer. You are then trying to convert back to a byte which the compiler, quite rightly, says may be a problem. Since you know that this is not a problem in your case you should use either
    chksum = (byte)(chksum ^ extr);
    or make chksum an int and conert to byte at the end of the computation.

  • Why loss of precision??

    Hi
    I have this part of code:
    int i;
    float j;
    switch (k) {
    case 1: j = 0.1; break;
    case 2: j = 0.01; break;
    Why in case statements compiler says "possible loss of precision?? I have defined double j and I solve the problem, but why??

    Java interprets floating point literals as double values. If you want floats, you'll need to cast the literal or specify it with the 'F' or 'f' suffix.
    Example:
    float j;
    j = 0.1F;

  • Dock acting really weird - Please help!

    After installing the Mobile ME update and iTunes 7.7, my dock has been acting really weird.
    1. I usually set the default dock size at the smallest possible. However, now when you left click on the separator of folders and applications, it allows the dock to become smaller than possible when setting from the Preference Pane
    2. The dock automatically becomes smaller over time until the icons are really tiny.
    Is this a bug encountered by anyone else? It really bugs me that I have to keep pulling the dock to a standard size. Can someone please help me out of this mess?

    Hey VK
    Thanks for the quick response.
    I did just that. Deleted the com.apple.dock.plist under my user home directory/Library/Preferences.
    While it reset the dock, the problem still remains. You can view the problem by
    1. Setting the dock to the smallest possible size via the Preference Pane
    2. Turn on magnification and bring it closer to the left side of the adjustable bar
    3. Now, use your mouse to drag the dock by the separator
    Observation: The dock will become smaller than is "set" by the bar in Preference Pane
    4. Click on the bar in the preference pane, set at small, the dock will resize itself again
    5. Choose the dock to be set on the right
    6. Choose it to be set at bottom
    Observation: The dock is a LOT smaller than it could ever have been.
    7. Click on the smallest possible size in the preference pane, the dock resizes itself
    8. The dock keeps getting smaller over time still. =(!

  • When I convert my pdf doc to word, the fonts go really weird and it also puts some text into boxes. when I try to select the test and change the font, it does not change it properly?

    When I convert my pdf doc to word, the fonts go really weird and it also puts some text into boxes. when I try to select the text and change the font, it does not change it properly? This is making it impossible to amend.

    Hi Janedance1,
    If the PDF that you converted already has searchable text, please try disabling OCR as described in this document: How to disable Optical Character Recognition (OCR) when converting PDF to Word or Excel. (If the PDF was created from a scanned document and doesn't already have searchable text, disabling OCR isn't a great option, as the text won't be searchable/editable in the converted Word doc.)
    Please let us know how it goes.
    Best,
    Sara

Maybe you are looking for