Double subtract

Hello,
Can you explain me what's wrong with the following code and the result I get?
Thank you for your help
Dom
// the code
import java.math.*;
public class SubtractMaxDouble{
static double r=0D;
public static final void main(String[] args){
System.out.println("Double.MAX_VALUE="+Double.MAX_VALUE);
r=Double.MAX_VALUE-1D;
if (r==Double.MAX_VALUE){System.out.println("BAD "+Double.MAX_VALUE+"-1="+r);}else{System.out.println("OK r="+r);}
System.out.println("MaxDouble= "+new BigDecimal(Double.MAX_VALUE).toString());
System.out.println("Diff = "+new BigDecimal(Double.MAX_VALUE-1D).toString());
// the output I get
Double.MAX_VALUE=1.7976931348623157E308
BAD 1.7976931348623157E308-1=1.7976931348623157E308
MaxDouble= 179769313486231570814527423731704356798070567525844996598917476803157260780028538760589558632766878171540458953514382464234321326889464182768467546703537516986049910576551282076245490090389328944075868508455133942304583236903222948165808559332123348274797826204144723168738177180919299881250404026184124858368
Diff = 179769313486231570814527423731704356798070567525844996598917476803157260780028538760589558632766878171540458953514382464234321326889464182768467546703537516986049910576551282076245490090389328944075868508455133942304583236903222948165808559332123348274797826204144723168738177180919299881250404026184124858368

Thanks for this answer, Danperkins.
I'm clearly a newbye with computer mathematics but also with american language...
Sig figs, dude. Sig figs.Sig figs, Google says Significant figures
I'm here to learn a maximum (Double.MAX_VALUE ?). Some "jargon" doesn't sound for me (I'm a french reader, I apologize). Can you explain me the meaning of "dude"? A cool nickname I hope!
About your explanation, I agree there is a big difference beetween the digits used to represent a "real" number (my human reading)
and the way they are represented inside the computer (using IEEE754). I perfectly understand that the continuum of real numbers cannot be represented.
So now the question is "what is the double X value that is enougth to obtain 1.7976931348623157E308-X=1.7976931348623156E308?"
X=1.7976931348623157E308-1.7976931348623156E308
I obtain X=1.9958403095347198E292
I'm really sorry but I have some difficulties to "agree" with such a huge X that means
All the "real" numbers from "1.7976931348623157E308-X+1" to "Double.MAX_VALUE" are represented by the internal IEE754 double 1.7976931348623157E308
that also means that for each Y in [Double.MIN_VALUE .. X-Double.MIN_VALUE] the answer to Double.MAX_VALUE-Y will be Double.MAX_VALUE
Where I'm wrong? And if I'm right "You know what Georges?" I'm not happy!
Dom
To satisfy your curiosity about adding the following class
import java.math.*;
public class AddMinDouble{
static double r=0D;
public static final void main(String[] args){
System.out.println("Double.MIN_VALUE="+Double.MIN_VALUE);
r=Double.MIN_VALUE+1D;
if (r==Double.MIN_VALUE){System.out.println("BAD "+Double.MIN_VALUE+"+1="+r);}else{System.out.println("OK r="+r);}
System.out.println("MinDouble= "+new BigDecimal(Double.MIN_VALUE).toString());
System.out.println("Add = "+new BigDecimal(Double.MIN_VALUE+1D).toString());
r=1.7976931348623157E-300+1D;// your value+1
if (r==1.7976931348623157E-300){System.out.println("BAD r=1.7976931348623157E-300");}else{System.out.println("OK r="+r);}
output
Double.MIN_VALUE=4.9E-324
OK r=1.0
MinDouble= 0.0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
31903114045278458171678489821036887186360569987307230500063874091535649843873124733972731696151400317153853980741262385655911710
389733598993664809941164205702637090279242767544565229087538682506419718265533447265625
Add = 1
OK r=1.0

Similar Messages

  • Has anyone else noticed a double subtraction problem?

    double value = 0.910;
    double one = 1.000;
    double afterSub = one - value;
    System.out.println(afterSub);
    Prints:
    0.08999999999999997
    I am developing on a Windows XP system with all current Patches installed.
    Using Java 1.4.2_04 (have also tested _05-b04, _01, _02, _03 and on Windows 2000, XP with latest service pack [multiple machines])
    Seems that lower double subtractions like 1.00 - 0.11 work fine, but as the second number approaches 1.0 the error increases.
    I have someone testing it on a Mac and on Solaris but haven't heard back from them yet.
    Am I doing something wrong? Has this been fixed in a later version? I checked the bug base but couldn't find anything about this (this could be user error.)
    Any help would be appreciated.
    Thanks.

    This question is off topic for this forum. In the future please post to a more appropriate forum. Although I'm not sure I see the issue here. You are subtracting two double precision floating point numbers. The computer can not represent .09 exactly so it approximates the value to 0.08999999999999997 which is pretty close. If your going to be doing floating pont math you should probably look at the java.math package.

  • How can I limit a double value to two decimal place?

    How can I limit a double value to two decimal place?
    Java keeps on adding zero's to a simple double subtraction:
    1497 - 179.64 = 1317.3600000000001The answer must have been simply: 1317.36

    If the trouble is with output ...
    If the trouble is with value accuracy ...The trouble is with OPs understanding of and/or expectations of IEEE 754 floating point numbers. o_O
    [And it's probably a view (output) issue.]
    how can i actually use numberformat to cut those
    unwanted decimal places?Read the API - Puce already provided the link.

  • Need help with calculator project for an assignment...

    Hi all, I please need help with my calculator project that I have to do for an assignment.
    Here is the project's specifications that I need to do"
    """Create a console calculator applicaion that:
    * Takes one command line argument: your name and surname. When the
    program starts, display the date and time with a welcome message for the
    user.
    * Display all the available options to the user. Your calculator must include
    the arithmetic operations as well as at least five scientific operations of the
    Math class.
    -Your program must also have the ability to round a number and
    truncate it.
    -When you multiply by 2, you should not use the '*' operator to perform the
    operation.
    -Your program must also be able to reverse the sign of a number.
    * Include sufficient error checking in your program to ensure that the user
    only enters valid input. Make use of the String; Character, and other
    wrapper classes to help you.
    * Your program must be able to do conversions between decimal, octal and
    hex numbers.
    * Make use of a menu. You should give the user the option to end the
    program when entering a certain option.
    * When the program exits, display a message for the user, stating the
    current time, and calculate and display how long the user used your
    program.
    * Make use of helper classes where possible.
    * Use the SDK to run your program."""
    When the program starts, it asks the user for his/her name and surname. I got the program to ask the user again and again for his/her name and surname
    when he/she doesn't insert anything or just press 'enter', but if the user enters a number for the name and surname part, the program continues.
    Now my question is this: How can I restrict the user to only enter 'letters' (and spaces of course) but allow NO numbers for his/her surname??
    Here is the programs code that I've written so far:
    {code}
    import java.io.*;
    import java.util.*;
    import java.text.*;
    public class Project {
         private static String nameSurname = "";     
         private static String num1 = null;
         private static String num2 = null;
         private static String choice1 = null;
         private static double answer = 0;
         private static String more;
         public double Add() {
              answer = (Double.parseDouble(num1) + Double.parseDouble(num2));
              return answer;
         public double Subtract() {
              answer = (Double.parseDouble(num1) - Double.parseDouble(num2));
              return answer;
         public double Multiply() {
              answer = (Double.parseDouble(num1) * Double.parseDouble(num2));
              return answer;
         public double Divide() {
              answer = (Double.parseDouble(num1) / Double.parseDouble(num2));
              return answer;
         public double Modulus() {
              answer = (Double.parseDouble(num1) % Double.parseDouble(num2));
              return answer;
         public double maximumValue() {
              answer = (Math.max(Double.parseDouble(num1), Double.parseDouble(num2)));
              return answer;
         public double minimumValue() {
              answer = (Math.min(Double.parseDouble(num1), Double.parseDouble(num2)));
              return answer;
         public double absoluteNumber1() {
              answer = (Math.abs(Double.parseDouble(num1)));
              return answer;
         public double absoluteNumber2() {
              answer = (Math.abs(Double.parseDouble(num2)));
              return answer;
         public double Squareroot1() {
              answer = (Math.sqrt(Double.parseDouble(num1)));
              return answer;
         public double Squareroot2() {
              answer = (Math.sqrt(Double.parseDouble(num2)));
              return answer;
         public static String octalEquivalent1() {
              int iNum1 = Integer.parseInt(num1);
    String octal1 = Integer.toOctalString(iNum1);
    return octal1;
         public static String octalEquivalent2() {
              int iNum2 = Integer.parseInt(num2);
              String octal2 = Integer.toOctalString(iNum2);
              return octal2;
         public static String hexadecimalEquivalent1() {
              int iNum1 = Integer.parseInt(num1);
              String hex1 = Integer.toHexString(iNum1);
              return hex1;
         public static String hexadecimalEquivalent2() {
              int iNum2 = Integer.parseInt(num2);
              String hex2 = Integer.toHexString(iNum2);
              return hex2;
         public double Round1() {
              answer = Math.round(Double.parseDouble(num1));
              return answer;
         public double Round2() {
              answer = Math.round(Double.parseDouble(num2));
              return answer;
              SimpleDateFormat format1 = new SimpleDateFormat("EEEE, dd MMMM yyyy");
         Date now = new Date();
         SimpleDateFormat format2 = new SimpleDateFormat("hh:mm a");
         static Date timeIn = new Date();
         public static long programRuntime() {
              Date timeInD = timeIn;
              long timeOutD = System.currentTimeMillis();
              long msec = timeOutD - timeInD.getTime();
              float timeHours = msec / 1000;
                   return (long) timeHours;
         DecimalFormat decimals = new DecimalFormat("#0.00");
         public String insertNameAndSurname() throws IOException{
              boolean inputCorrect = false;
                   while (inputCorrect == false) {
                        while (nameSurname == null || nameSurname.length() == 0) {
                             for (int i = 0; i < nameSurname.length(); i++) {
                             if ((nameSurname.charAt(i) > 'a') && (nameSurname.charAt(i) < 'Z')){
                                       inputCorrect = true;
                        else{
                        inputCorrect = false;
                        break;
                        try {
                             BufferedReader inStream = new BufferedReader (new InputStreamReader(System.in));
                             System.out.print("Please enter your name and surname: ");
                             nameSurname = inStream.readLine();
                             inputCorrect = true;
                        }catch (IOException ex) {
                             System.out.println("You did not enter your name and surname, " + nameSurname + " is not a name, please enter your name and surname :");
                             inputCorrect = false;
                        System.out.println("\nA warm welcome " + nameSurname + " ,todays date is: " + format1.format(now));
                        System.out.println("and the time is now exactly " + format2.format(timeIn) + ".");
                        return nameSurname;
              public String inputNumber1() throws IOException {
              boolean inputCorrect = false;
                   while (inputCorrect == false) {
                        try {
                             BufferedReader br = new BufferedReader (new InputStreamReader(System.in));
                             System.out.print("\nPlease enter a number you want to do a calculation with and hit <ENTER>: ");
                             num1 = br.readLine();
                             double number1 = Double.parseDouble(num1);
                             System.out.println("\nThe number you have entered is: " + number1);
                             inputCorrect = true;
                        } catch (NumberFormatException nfe) {
                             System.out.println("\nYou did not enter a valid number: " + "\""+ num1 + "\" is not a number!!");
                             inputCorrect = false;
                        return num1;
         public String calculatorChoice() throws IOException {
              System.out.println("Please select an option of what you would like to do with this number from the menu below and hit <ENTER>: ");
              System.out.println("\n*********************************************");
              System.out.println("---------------------------------------------");
              System.out.println("Please select an option from the list below: ");
              System.out.println("---------------------------------------------");
              System.out.println("1 - Add");
              System.out.println("2 - Subtract");
              System.out.println("3 - Multiply");
              System.out.println("4 - Divide (remainder included)");
              System.out.println("5 - Maximum and minimum value of two numbers");
              System.out.println("6 - Squareroot");
              System.out.println("7 - Absolute value of numbers");
              System.out.println("8 - Octal and Hexadecimal equivalent of numbers");
              System.out.println("9 - Round numbers");
              System.out.println("0 - Exit program");
              System.out.println("**********************************************");
              boolean inputCorrect = false;
                   while (inputCorrect == false) {
                        try {
                             BufferedReader inStream = new BufferedReader (new InputStreamReader(System.in));
                             System.out.print("Please enter your option and hit <ENTER>: ");
                             choice1 = inStream.readLine();
                             int c1 = Integer.parseInt(choice1);
                             System.out.println("\nYou have entered choice number: " + c1);
                             inputCorrect = true;
                        } catch (NumberFormatException nfe) {
                             System.out.println("You did not enter a valid choice number: " + "\""+ choice1 + "\" is not in the list!!");
                             inputCorrect = false;
                        return choice1;
         public String inputNumber2() throws IOException {
              boolean inputCorrect = false;
                   while (inputCorrect == false) {
                        try {
                             BufferedReader br2 = new BufferedReader (new InputStreamReader(System.in));
                             System.out.print("\nPlease enter another number you want to do the calculation with and hit <ENTER>: ");
                             num2 = br2.readLine();
                             double n2 = Double.parseDouble(num2);
                             System.out.println("\nThe second number you have entered is: " + n2);
                             System.out.println("\nYour numbers are: " + num1 + " and " + num2);
                             inputCorrect = true;
                        } catch (NumberFormatException nfe) {
                             System.out.println("You did not enter a valid number: " + "\""+ num2 + "\" is not a number!!");
                             inputCorrect = false;
                        return num2;
         public int Calculator() {
              int choice2 = (int) Double.parseDouble(choice1);
              switch (choice2) {
                        case 1 :
                             Add();
                             System.out.print("The answer of " + num1 + " + " + num2 + " is: " + decimals.format(answer));
                             break;
                        case 2 :
                             Subtract();
                             System.out.print("The answer of " + num1 + " - " + num2 + " is: " + decimals.format(answer));
                             break;
                        case 3 :
                             Multiply();
                             System.out.print("The answer of " + num1 + " * " + num2 + " is: " + decimals.format(answer));
                             break;
                        case 4 :
                             Divide();
                             System.out.print("The answer of " + num1 + " / " + num2 + " is: " + decimals.format(answer));
                             Modulus();
                             System.out.print(" and the remainder is " + decimals.format(answer));
                             break;
                        case 5 :
                             maximumValue();
                             System.out.println("The maximum number between the numbers " + num1 + " and " + num2 + " is: " + decimals.format(answer));
                             minimumValue();
                             System.out.println("The minimum number between the numbers " + num1 + " and " + num2 + " is: " + decimals.format(answer));
                             break;
                        case 6 :
                             Squareroot1();
                             System.out.println("The squareroot of value " + num1 + " is: " + decimals.format(answer));
                             Squareroot2();
                             System.out.println("The squareroot of value " + num2 + " is: " + decimals.format(answer));
                             break;
                        case 7 :
                             absoluteNumber1();
                             System.out.println("The absolute number of " + num1 + " is: " + decimals.format(answer));
                             absoluteNumber2();
                             System.out.println("The absolute number of " + num2 + " is: " + decimals.format(answer));
                             break;
                        case 8 :
                             octalEquivalent1();
                             System.out.println("The octal equivalent of " + num1 + " is: " + octalEquivalent1());
                             octalEquivalent2();
                             System.out.println("The octal equivalent of " + num2 + " is: " + octalEquivalent2());
                             hexadecimalEquivalent1();
                             System.out.println("\nThe hexadecimal equivalent of " + num1 + " is: " + hexadecimalEquivalent1());
                             hexadecimalEquivalent2();
                             System.out.println("The hexadecimal equivalent of " + num2 + " is: " + hexadecimalEquivalent2());
                             break;
                        case 9 :
                             Round1();
                             System.out.println("The rounded number of " + num1 + " is: " + decimals.format(answer));
                             Round2();
                             System.out.println("The rounded number of " + num2 + " is: " + decimals.format(answer));
                             break;
                        case 0 :
                             if (choice2 == 0) {
                                  System.exit(1);
                             break;
                   return choice2;
              public String anotherCalculation() throws IOException {
                   boolean inputCorrect = false;
                   while (inputCorrect == false) {
                             try {                              
                                  BufferedReader br3 = new BufferedReader (new InputStreamReader(System.in));
                                  System.out.print("\nWould you like to do another calculation? Y/N ");
                                  more = br3.readLine();
                                  String s1 = "y";
                                  String s2 = "Y";
                                  if (more.equals(s1) || more.equals(s2)) {
                                       inputCorrect = true;
                                       while (inputCorrect = true){
                                            inputNumber1();
                                            System.out.println("");
                                            calculatorChoice();
                                            System.out.println("");
                                            inputNumber2();
                                            System.out.println("");
                                            Calculator();
                                            System.out.println("");
                                            anotherCalculation();
                                            System.out.println("");
                                            inputCorrect = true;
                                  } else {
                                       System.out.println("\n" + nameSurname + " thank you for using this program, you have used this program for: " + decimals.format(programRuntime()) + " seconds");
                                       System.out.println("the program will now exit, Goodbye.");
                                       System.exit(0);
                             } catch (IOException ex){
                                  System.out.println("You did not enter a valid answer: " + "\""+ more + "\" is not in the list!!");
                                  inputCorrect = false;
              return more;
         public static void main(String[] args) throws IOException {
              Project p1 = new Project();
              p1.insertNameAndSurname();
              System.out.println("");
              p1.inputNumber1();
              System.out.println("");
              p1.calculatorChoice();
              System.out.println("");
              p1.inputNumber2();
              System.out.println("");
              p1.Calculator();
                   System.out.println("");
                   p1.anotherCalculation();
                   System.out.println("");
    {code}
    *Can you please run my code for yourself and have a look at how this program is constructed*
    *and give me ANY feedback on how I can better this code(program) or if I've done anything wrong from your point of view.*
    Your help will be much appreciated.
    Thanks in advance

    Smirre wrote:
    Now my question is this: How can I restrict the user to only enter 'letters' (and spaces of course) but allow NO numbers for his/her surname??You cannot restrict the user. It is a sad fact in programming that the worst bug always sits in front of the Computer.
    What you could do is checking the input string for numbers. If it contains numbers, just reprompt for the Name.
    AND you might want to ask yourself why the heck a calculator needs to know the users Name.

  • Why Can't I get my total to output to the text area?

    I can get the numbers to go to the text area and to clear the text area but, the only way I have figured out how to output the total is with a JOptionPane. Can someone look at my code and tell me how to fix this?
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class Calculator4 extends JApplet implements ActionListener
    String Nums="";
    String sNum="";
    double Num1=0;
    double Num2=0;
    double Add=0;
    double Subtract=0;
    double Multiply=0;
    double Divide=0;
    int choice=0;
    private JTextField displayField;
    private JButton Button0, Button1, Button2, Button3, Button4, Button5,
    Button6, Button7, Button8, Button9, ButtonAdd, ButtonSub,
    ButtonMult, ButtonDiv, ButtonClear, Buttontotal;
    public void init()
    Container container = getContentPane();
    container.setLayout(new FlowLayout());
    displayField = new JTextField(15);
    displayField.setEditable(false);
    container.add(displayField);
    Button1 = new JButton("1");
    Button1.addActionListener(this);
    container.add(Button1);
    Button2 = new JButton("2");
    Button2.addActionListener(this);
    container.add(Button2);
    Button3 = new JButton("3");
    Button3.addActionListener(this);
    container.add(Button3);
    ButtonAdd = new JButton("+");
    ButtonAdd.addActionListener(this);
    container.add(ButtonAdd);
    Button4 = new JButton("4");
    Button4.addActionListener(this);
    container.add(Button4);
    Button5 = new JButton("5");
    Button5.addActionListener(this);
    container.add(Button5);
    Button6 = new JButton("6");
    Button6.addActionListener(this);
    container.add(Button6);
    ButtonSub = new JButton("-");
    ButtonSub.addActionListener(this);
    container.add(ButtonSub);
    Button7 = new JButton("7");
    Button7.addActionListener(this);
    container.add(Button7);
    Button8 = new JButton("8");
    Button8.addActionListener(this);
    container.add(Button8);
    Button9 = new JButton("9");
    Button9.addActionListener(this);
    container.add(Button9);
    ButtonMult = new JButton("*");
    ButtonMult.addActionListener(this);
    container.add(ButtonMult);
    Button0 = new JButton("0");
    Button0.addActionListener(this);
    container.add(Button0);
    ButtonDiv = new JButton("/");
    ButtonDiv.addActionListener(this);
    container.add(ButtonDiv);
    ButtonClear = new JButton(" Clear ");
    ButtonClear.addActionListener(this);
    container.add(ButtonClear);
    Buttontotal = new JButton("=");
    Buttontotal.addActionListener(this);
    container.add(Buttontotal);
    public void actionPerformed(ActionEvent actionEvent)
    if(actionEvent.getSource() == Button1)
    play(getCodeBase(),"Ping.WAV");
    if(Nums==null)
    {  Nums= "";
    displayField.setText("1");}
    if(Nums!=null)
    {  Nums= Nums + 1;
    updateDisplay();}
    else if(actionEvent.getSource()==Button2)
    play(getCodeBase(),"Ping.WAV");
    if(Nums==null)
    {  Nums= "";
    displayField.setText("2");}
    if(Nums!=null)
    {  Nums= Nums + 2;
    updateDisplay();}
    else if(actionEvent.getSource()==Button3)
    play(getCodeBase(),"Ping.WAV");
    if(Nums==null)
    {  Nums= "";
    displayField.setText("3");}
    if(Nums!=null)
    {  Nums= Nums + 3;
    updateDisplay();}
    else if(actionEvent.getSource()==Button4)
    play(getCodeBase(),"Ping.WAV");
    if(Nums==null)
    {  Nums= "";
    displayField.setText("4");}
    if(Nums!=null)
    {  Nums= Nums + 4;
    updateDisplay();}
    else if(actionEvent.getSource()==Button5)
    play(getCodeBase(),"Ping.WAV");
    if(Nums==null)
    {  Nums= "";
    displayField.setText("5");}
    if(Nums!=null)
    {  Nums= Nums + 5;
    updateDisplay();}
    else if(actionEvent.getSource()==Button6)
    play(getCodeBase(),"Ping.WAV");
    if(Nums==null)
    {  Nums= "";
    displayField.setText("6");}
    if(Nums!=null)
    {  Nums= Nums + 6;
    updateDisplay();}
    else if(actionEvent.getSource()==Button7)
    play(getCodeBase(),"Ping.WAV");
    if(Nums==null)
    {  Nums= "";
    displayField.setText("7");}
    if(Nums!=null)
    {  Nums= Nums + 7;
    updateDisplay();}
    else if(actionEvent.getSource()==Button8)
    play(getCodeBase(),"Ping.WAV");
    if(Nums==null)
    {  Nums= "";
    displayField.setText("8");}
    if(Nums!=null)
    {  Nums= Nums + 8;
    updateDisplay();}
    else if(actionEvent.getSource()==Button9)
    play(getCodeBase(),"Ping.WAV");
    if(Nums==null)
    {  Nums= "";
    displayField.setText("9");}
    if(Nums!=null)
    {  Nums= Nums +9;
    updateDisplay();}
    else if(actionEvent.getSource()==Button0)
    play(getCodeBase(),"Ping.WAV");
    if(Nums==null)
    {  Nums= "";
    displayField.setText("0");}
    if(Nums!=null)
    {  Nums= Nums + 0;
    updateDisplay();}
    else if(actionEvent.getSource()==ButtonAdd)
    play(getCodeBase(),"Ping.WAV");
    choice = 1;
    sNum="";
    sNum = Nums;
    Nums=null;
    else if(actionEvent.getSource()==ButtonSub)
    play(getCodeBase(),"Ping.WAV");
    choice = 2;
    sNum="";
    sNum = Nums;
    Nums=null;
    else if(actionEvent.getSource()==ButtonMult)
    play(getCodeBase(),"Ping.WAV");
    choice = 3;
    sNum="";
    sNum = Nums;
    Nums=null;
    else if(actionEvent.getSource()==ButtonDiv)
    play(getCodeBase(),"Ping.WAV");
    choice = 4;
    sNum="";
    sNum = Nums;
    Nums=null;
    else if(actionEvent.getSource()==Buttontotal)
    play(getCodeBase(),"Ping.WAV");
    if(choice==0)
    JOptionPane.showMessageDialog(null,"Please Select Operation");
    if(choice!=0)
    switch(choice)
    case 1:
    if(Nums!=null)
    {    Num1 = Double.parseDouble(sNum);
    Num2 = Double.parseDouble(Nums);
    double Add = Addition(Num1, Num2);
    JOptionPane.showMessageDialog(null,"Your Sum is: " + Add);
    sNum = "";
    if(Nums==null)
    JOptionPane.showMessageDialog(null,"Please Enter Second number");
    Nums=null;
    break;
    case 2:
    if(Nums!=null)
    {    Num1 = Double.parseDouble(sNum);
    Num2= Double.parseDouble(Nums);
    double Subtract = Subtraction(Num1, Num2);
    JOptionPane.showMessageDialog(null,"Your Difference is: " + Subtract);
    sNum = "";
    if(Nums==null)
    JOptionPane.showMessageDialog(null,"Please Enter Second number");
    Nums=null;
    break;
    case 3:
    if(Nums!=null)
    {    Num1= Double.parseDouble(sNum);
    Num2= Double.parseDouble(Nums);
    double Multiply = Multiplication(Num1, Num2);
    JOptionPane.showMessageDialog(null,"Your Product is: " + Multiply);
    sNum = "";
    if(Nums==null)
    JOptionPane.showMessageDialog(null,"Please Enter Second number");
    Nums=null;
    break;
    case 4:
    if(Nums!=null)
    {    Num1 = Double.parseDouble(sNum);
    Num2= Double.parseDouble(Nums);
    double Divide = Division(Num1, Num2);
    JOptionPane.showMessageDialog(null,"Your Quotient is: " + Divide);
    sNum = "";
    if(Nums==null)
    JOptionPane.showMessageDialog(null,"Please Enter Second number");
    Nums=null;
    break;
    else if(actionEvent.getSource()==ButtonClear)
    play(getCodeBase(),"Ping.WAV");
    displayField.setText("");
    Nums=null;
    sNum="";
    choice=0;
    Num1=0;
    Num2=0;
    public void updateDisplay()
    displayField.setText(Nums);
    public double Addition(double Num1, double Num2)
    return ( Num1 + Num2);
    public double Subtraction(double Num1, double Num2)
    return ( Num1 - Num2);
    public double Multiplication(double Num1, double Num2)
    return ( Num1 * Num2);
    public double Division(double Num1, double Num2)
    return ( Num1 / Num2);
    }

    You mean something like this:
    private int currentNumber =0;
    private int total = 0;
    private JTextField Display = new JTextField(10);
    private JtextField Current = new JTextField(10);
    // Add all your buttons correctly
    // Try using a GridLayout to make it easier
    // blah blah
    public void actionPerformed( ActionEvent event )
    int number = -1;
    String Command = event.getActionCommand();
    // Play your sound here.....
      doPlaySound();
    try
       number = Integer.parseInt( command );
    catch( NumberFormatException NFE )
        //ignore
    if( number != -1 )
        doIsNumber( number );
        return;   // don't process further
    if( command == "Enter" )
        doEnter();
        return;
    if(command == "Plus" )
        doPlus();
        return;
    // and so on
    }//end actionPerformed
    private void doNumber( int number )
       String S;
        currentNumber = ( currentNumber * 10 ) + number;
        S = Integer.tostring( currentNumber );  //cant remember if that throws anything
       Current.setText( S );  //Display Work Number
      private void doPlus()
        String S;
        total = total + currentNumber;
        currentNumber = 0;
        Current.setText("");
        S = Integer.toString( total );
        Display.setText( S );
      private void doEnter()
        total = currentNumber;
        currentNumber = 0;
        Current.setText( "");
        Display.setText( Integer.toString( total ) );
      private void doDivide()
         System.out.println("Err you got to be kidding");
      }yeh and I'd definitely go for a GridLayout()
    4 * 4, with JLabels for the blank filler parts......
    So does this help

  • Passing arguments

    Our teacher just taught us about methods and passing arguments, etc. I have been over our text book and I don't quite understand how it works. Any help?
    PROBLEM:
    ?     Write a program with four methods. One is the main method. The other three are named startMessage, message, and finishMessage.
    ?     Within the startMessage method, place code to print out the message ?The program has started.?
    ?     Within the message method, place code to print out any message that is passed, as a String, into the method using a String parameter named output.
    ?     Within the finishMessage method, place code to print out the message ?The program is done.?
    ?     When the program begins call the startMessage method.
    ?     Then display the following dialog box:
    "Enter a message:"
    ?     Using a While loop, respond to the user?s input appropriately:
         If the user presses OK display whatever the user has entered by calling the message method with the user?s input as the argument. Continue to display the dialog box and display the user?s input until they press Cancel.
         When the user presses Cancel stop showing the dialog box, and do not display what the user has entered.
    ?     After the user presses Cancel, and before the program terminates, call the finishMessage method.
    ?     Terminate the program.
    here is what I have so far:
    public static void main(String[] args) {
              startMessage();
              String userMessage = JOptionPane.showInputDialog("Enter a message:");
              while (userMessage != null){
                   message(userMessage);
                   JOptionPane.showMessageDialog(null, "Here is message" + message());
                   userMessage = JOptionPane.showInputDialog("Enter a message:");
              finishMessage();
              System.exit(0);
         public static void startMessage(){
              JOptionPane.showMessageDialog(null, "The program has started.");
         public static String message (String output){
              output = userMessage;
              return(output);
         public static void finishMessage(){
              JOptionPane.showMessageDialog(null, "The program is done.");
    }what's giving me the problem is the message method; I can't figure out how to pass whatever they put in the userMessage variable to the message method

    I am stuck here
    PROBLEM:
    ?     Change your C6E2 class by adding a new method called getNumberInput. This method will be used to get a number input from the user, replacing the lines of code in the main method that were previously used. You will need to call this method twice from the main method, prompting for the first and second numbers in turn.
    ?     Write the method so that the prompt displayed in the input dialog box is passed through an argument.
    ?     The return type of this new method will be a double.
    I can't figure out how to pass the input paramater correctly, any help?
    public static void main(String[] args) {
              double num1 = 0;
              double num2 = 0;
              double addResult = 0;
              double subtractResult = 0;
              double multiplyResult = 0;
              double divideResult = 0;
              double input1 = getNumberInput(num1);//this is where I am stuck
              double input2 = getNumberInput(num2);
              addResult = add(num1, num2);
              subtractResult = subtract(num1, num2);
              multiplyResult = multiply(num1, num2);
              divideResult = divide(num1, num2);
              JOptionPane.showMessageDialog(null, addResult);
              JOptionPane.showMessageDialog(null, subtractResult);
              JOptionPane.showMessageDialog(null, multiplyResult);
              JOptionPane.showMessageDialog(null, divideResult);
              System.exit(0);
         }//main
         public static double getNumberInput (double input){
              double output = 0;
              Double.parseDouble(JOptionPane.showInputDialog("Enter a number:"));
              return output;
         public static double add (double term1, double term2){
              double result = term1 + term2;
              return result;
         }//add
         public static double subtract (double term1, double term2){
              double result = term1 - term2;
              return result;
         }//subtract
         public static double multiply (double term1, double term2){
              double result = term1 * term2;
              return result;
         }//multiply
         public static double divide (double term1, double term2){
              double result = term1 / term2;
              return result;
         }//divide
    }//class

  • Having trouble with a NullPointerException

    Hi, I'm having difficulties trying to figure out how to fix this problem. I'm trying to write a program that adds a few Point2D.Double objects to an array list, but it doesn't seem to be adding them correctly. I get a NullPointerException in my add and main method when I try to run the program. I tried doing myPolygon.add(new Point2D.Double(20,10)); inside the add method, which gave me a NullPointerException in the draw method as I tried to use myPolygon.get(0);.
    Any help would be appreciated. Thanks in advance.
    import java.awt.geom.*;
    import java.util.*;
    import apcslib.*;  
    public class IrregularPolygon
        private ArrayList myPolygon;
        SketchPad paper = new SketchPad(500, 500);
        DrawingTool pen = new DrawingTool(paper);
       public IrregularPolygon()
       public void add(Point2D.Double aPoint)
           myPolygon.add(aPoint); 
       public void draw()
           Point2D.Double coord = (Point2D.Double)myPolygon.get(0);
           pen.up();
           pen.move(coord.getX(), coord.getY());
           pen.down();
           for (int loop = 1; loop < myPolygon.size(); loop++)
               coord = (Point2D.Double)myPolygon.get(loop);
               pen.move(coord.getX(), coord.getY());
            pen.move(coord.getX(), coord.getY());
       public double perimeter()
           double total = 0;
           for(int loop = 0; loop < myPolygon.size() - 1; loop++)
               Point2D.Double coord = (Point2D.Double)myPolygon.get(loop);
               Point2D.Double coord2 = (Point2D.Double)myPolygon.get(loop+1);
               total += coord.distance(coord2);
           return total;
       public double area()
           double add = 0;
           double subtract = 0;
           for (int loop = 0; loop < myPolygon.size() - 1; loop++)
               Point2D.Double coord = (Point2D.Double)myPolygon.get(loop);
               Point2D.Double coord2 = (Point2D.Double)myPolygon.get(loop+1);
               add += coord.getX() * coord2.getY();
               subtract += coord.getY() * coord2.getX();
           return (add - subtract) / 2;
       public static void main(String[] args)
           IrregularPolygon poly = new IrregularPolygon();
           poly.add(new Point2D.Double(20,10));
           poly.add(new Point2D.Double(70,20));
           poly.add(new Point2D.Double(50,50));
           poly.add(new Point2D.Double(0,40));
           poly.draw();
           System.out.println("Perimeter: " + poly.perimeter());
           System.out.println("Area: " + poly.area());
    }

    Which is of course one of the reasons why XP is a
    popular programming technique.... and why there are so few cyclops in programming.

  • Please help with methods!

    hello
    i have a problem that i have been working on for a few days now. i have just started to learn about methods and how to use them. my first attempt has met with a few problems however. i was to make a calculator with a menu that did the four basic math operations. i have done that and the program is working perfectly. the only trouble is that i was to have 7 methods and i only have 6. this is how i was supposed to split it up
    4 for operations
    1 for number prompt and input
    1 for menu
    1 for output of results
    i am at a lost for how to put the outputs in ONE method. can anyone please help me. i realize i am using an unfamiliar console, but ican send it to you if you contact me. then you can test it out here is the program:
    import java.io.*;
    import java.awt.*;
    import hsa.Console;
    import java.text.*;
    public class calculator
        //Variable declaration -- defined global because they can be utilized by all methods
        static double num, num1, num2, mult, div, add, subtract;
        static int choice;
        static Console c;
        public static void main (String[] args)
            //variable initialization
            c = new Console ();
            num = 0;
            mult = 0;
            div = 0;
            add = 0;
            subtract = 0;
            num1 = input (num);
            num2 = input (num);
            do
                c.println ("\t\t Main Menu");
                c.println ("\t\t 1. Multiply the numbers");
                c.println ("\t\t 2. Divide the 1st by the 2nd number");
                c.println ("\t\t 3. Add the two numbers");
                c.println ("\t\t 4. Subtract the 2nd from the 1st number");
                c.println ("\t\t 5. End");
                do
                    c.print ("What is your choice (1-5): ");
                    choice = c.readInt ();
                    if ((choice < 1) || (choice > 5))
                        c.println ("Invalid...enter 1-5 only");
                while ((choice < 1) || (choice > 5));
                switch (choice)
                    case 1:
                        multiply (num1, num2, mult);
                        break;
                    case 2:
                        divide (num1, num2, div);
                        break;
                    case 3:
                        add (num1, num2, add);
                        break;
                    case 4:
                        subtract (num1, num2, subtract);
                        break;
            while (choice != 5);
            c.println ("\n\nThanks for using my calculator. Bye.....");
        //method used to input the 2 numbers
        public static double input (double num)
            c.setTextColor (Color.cyan);
            c.print ("Please enter a number: ");
            num = c.readDouble ();
            return num;
        //method used to multiply
        public static double multiply (double num1, double num2, double mult)
            DecimalFormat z = new DecimalFormat ("##,###,##0.00");
            mult = (num1 * num2);
            c.setTextColor (Color.red);
            c.println ("The numbers multiplied equals: " + z.format (mult));
            return mult;
        //method used to divide
        public static double divide (double num1, double num2, double div)
            DecimalFormat z = new DecimalFormat ("##,###,##0.00");
            //if ( num2 = 0 );
            //c.println("You can not divide by zero");
            div = (num1 / num2);
            c.setTextColor (Color.red);
            c.println ("The 1st number divided by the 2nd number equals: " + z.format (div));
            return div;
        //method used to add
        public static double add (double num1, double num2, double add)
            DecimalFormat z = new DecimalFormat ("##,###,##0.00");
            add = (num1 + num2);
            c.setTextColor (Color.red);
            c.println ("The numbers added equals: " + z.format (add));
            return add;
        //method used to subtract
        public static double subtract (double num1, double num2, double subtract)
            DecimalFormat z = new DecimalFormat ("##,###,##0.00");
            subtract = (num1 - num2);
            c.setTextColor (Color.red);
            c.println ("The 2nd number subtracted from the 1st equals: " + z.format (subtract));
            return subtract;
    }Thanks

    Tradeoff wrote:
    the only trouble is that i was to have 7 methods and i only have 6. this is how i was supposed to split it up
    4 for operations
    1 for number prompt and input
    1 for menu
    1 for output of results
    i am at a lost for how to put the outputs in ONE method. can anyone please help me.You can solve a problem in many ways, and when you design a class the number of methods used may vary from solution to solution. But it seems likely in this case that your teacher expected the operations to be:
    4 for operationsSo, after getting two numbers from the user, perform the operation and return the result. Note that this means that the operation methods would take TWO parameters, not three as you've been doing.
    1 for number prompt and inputOK. This would not take a number as a parameter, so you've done that wrong.
    1 for menuYou haven't done that part yet. You've stuck that stuff into the main method. You're probably supposed to create seven methods in addition to the main method.
    1 for output of resultsSo, print the number that's the result of the operation. This is the number that's been returned by the operation, which you're ignoring in your code.
    Of course, if you're confused about the assignment, you should ask your teacher, not here. We can't read your teacher's mind. Like I said there are lots of ways to solve a problem and they might not all be the same way your teacher had in mind.
    You seem to be confused about the whole idea of functions and return values. If you want a method to act as a function -- that is, to operate on its arguments and return a result without side effects -- then you don't pass the result value as a variable. You do this:
    double result = someOperation(arg1, arg2);and not this, as you have been doing:
    double result = someOperation(arg1, arg2, result);The latter case makes no sense. The method only gets a copy of "result" when the method is called, so any changes to it are lost except for what it returns. Do it like the former example above.

  • Area.subtract( Shape ) doesn't work on Shape Line2D.Double?

    Hi all,
    I'm working on a method that will return a Shape from a BufferedImage that has transparent values, much like the one that dfgstg developed in [this thread|http://forums.sun.com/thread.jspa?messageID=9809317] . I'm having trouble understanding the difference between using this ( I'll call it line mode 1 ):Shape = Area.subtract( new Area( new Line2D().getBounds2D ) ) and this ( I'll call it line mode 2 ):Shape = Area.subtract( new Area( new Line2D().getBounds() ) ). When I use line mode 1, nothing gets subtracted when you use vertical or horizontal lines. When I use line mode 2, things show up, but I get the sense that it introduces artifacts into the resulting shape. Why is it necessary to turn a Line2D into a rectangle in order to subtract it from an Area? Line2D implements the Shape interface, so theoretically, it should be able to be subtracted from an Area. A program to demonstrate this problem ( between line mode 1 and line mode 2 ) is attached. Dfgstg uses line mode 2. Why is this necessary?
    // ShapeTest2.java
    // --- this code should compile ---
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.*;
    class ShapeTest2 extends JComponent
        public static final int LINE_MODE_1 = 1;
        public static final int LINE_MODE_2 = 2;
        Area _shape;   
        int _radius;
        int _diameter;
        Point2D.Double _center;
        ShapeTest2( int mode, int diameter )
            _diameter = diameter;
            _radius = _diameter/2;
            _center = new Point2D.Double( _diameter/2.0, _diameter/2.0 );
            setPreferredSize( new Dimension( _diameter, _diameter ) );
            _shape = new Area(
                new Ellipse2D.Double(
                    0, 0, _diameter, _diameter 
            switch( mode )
                case LINE_MODE_1:lineMode1();break;
                case LINE_MODE_2:lineMode2();break;
                default: break;                          
        private void lineMode1()
            Point2D p1 = new Point2D.Double();
            Point2D p2 = new Point2D.Double();
            double random1, random2, random3;
            boolean inside;
            // make and subtract fifty lines
            for ( int i = 0; i < 50; i++ )
                inside = false;
                // search random points until you find two that are
                // less than the radius' distance from the center
                while( inside == false )
                    random1 = Math.random()*_diameter;
                    random2 = Math.random()*_diameter;
                    random3 = Math.random()*_diameter;
                    // make sure they are horizontally related
                    // they have y in common
                    p1 = new Point2D.Double( random1, random2 );
                    p2 = new Point2D.Double( random3, random2 );
                    if ( ( p1.distance( _center ) < _radius )
                            && ( p2.distance( _center ) < _radius ) )
                        inside = true;
                _shape.subtract(
                    new Area(
                        // notice the getBounds2D - it returns a Rectangle2D
                        // it also doesn't show up for some reason
                        new Line2D.Double( p1, p2 ).getBounds2D()
        private void lineMode2()
            Point2D p1 = new Point2D.Double();
            Point2D p2 = new Point2D.Double();
            double random1, random2, random3;
            boolean inside;
            for ( int i = 0; i < 50; i++ )
                inside = false;
                while( inside == false )
                    random1 = Math.random()*_diameter;
                    random2 = Math.random()*_diameter;
                    random3 = Math.random()*_diameter;
                    // make sure they are horizontally related
                    p1 = new Point2D.Double( random1, random2 );
                    p2 = new Point2D.Double( random3, random2 );
                    if ( ( p1.distance( _center ) < _radius )
                            && ( p2.distance( _center ) < _radius ) )
                        inside = true;
                _shape.subtract(
                    new Area(
                        // getBounds() returns a rectangle
                        new Line2D.Double( p1, p2 ).getBounds()
        @Override
        protected void paintComponent( Graphics g )
            super.paintComponent( g );
            Graphics2D g2d = ( Graphics2D )g;
            g2d.setColor( Color.BLACK );
            g2d.draw( _shape );
        public static void main( String[] args )
            JFrame frame = new JFrame( "ShapeTest2" );
            int diameter = 300;
            ShapeTest2 lineMode1 =
                new ShapeTest2( ShapeTest2.LINE_MODE_1, diameter );
            ShapeTest2 lineMode2 =
                new ShapeTest2( ShapeTest2.LINE_MODE_2, diameter );
            frame.setLayout( new FlowLayout() );
            frame.add( lineMode1 );
            frame.add( lineMode2 );
            frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
            frame.setLocation( 100, 100 );
            frame.pack();        
            frame.setVisible( true );
    }

    Keep all of your shapes right where they are! To make your text into hyperlinks then, just insert another shape...make it big or small enough to cover your text. Go ahead and drag it right over your text. Now attach the hyperlink to this shape. Now in the INspector,click over to the Graphics tab and change the opacity of this shape to 1%.
    You have now created a "hotspot" hyperlink over your text! All without moving any of your other shapes around! Publish and see the results... Let me know if it works out for you!

  • Subtracting two numbers in double format gives incorrect result

    Hello,
    I have a table with two fields in Number (Field Size: Double; Decimal Places: Auto).  When using a query i try to subtract one field from the other I get incorrect results:
    Field1
    Field2
    Result
    2.60299223923846
    2.60259423701324
    3.98002225218796E-04
    0.644498511499839
    0.645908903902985
    -1.41039240314556E-03
    1.51021791504783
    1.51372591514976
    -3.50800010193808E-03
    <tfoot></tfoot>
    When I paste the above into Excel, I get the correct results:
    Field1
    Field2
    Result
    2.60299223923846
    2.60259423701324
                         0.00039800222521880
    0.64449851149984
    0.64590890390299
                       (0.00141039240314556)
    1.51021791504783
    1.51372591514976
                       (0.00350800010193808)
    Would much appriciate any help in how to get the correct values in Access Query.
    Thank you

    Field1
    Field2
    Result
    2.60299223923846
    2.60259423701324
    3.98002225218796E-04
    0.644498511499839
    0.645908903902985
    -1.41039240314556E-03
    1.51021791504783
    1.51372591514976
    -3.50800010193808E-03
    Hi Vasilii,
    In my opinion the results are correct, only they are presented in scientific notation. You can do some formatting, to display the results the way you want.
    See the Help on the use of Format.
    Imb.

  • Java dont know subtract double or float?!!!

    The next simple java program print out Result: 6.999999999999999 when
    it should be 7. What is the reason? (i try with float 14.89 7.89 and other variations and the result is incorrect too).
    import java.io.*;
    public class subtract{
    public static void main(String argv[]){
    double n1 = 14.87;
    double n2 = 7.87;
    double result = n1 - n2;
    System.out.println("Result: "+result);
    }

    In my opinion the complexity of the internal
    operations should be transparent for the programmer.
    What i do expect is that the result of the trivial
    mathematical operations be exact. For example my
    cassio calculator do the 14.87-7.87=7 without error
    and java do not (the windows calculator give me the
    correct result, and excel too for example). How can i
    use a double in java if i know that it is not exact?Java also gives a "correct" result if you round the numbers.
    Remember that calculators are applications. They're written in some programming languages that treat floating point operations just like Java does. But the programmer has applied rounding before any result is displayed. When writing an application in Java you are that programmer.

  • Subtracting very small double value

    i'm having trouble figuring this out..i'm sure it's a simple solution..anyhoo..i'm trying to run the following line of code
    value=1-((1-b1[8+(i%classes)])*(1-b2[4+(i%classes)]));
    let me point out that value is a double value, and b1 and b2 are double arrays...
    the values of b1 and b2 are very small(around E-60)
    the PROBLEM is that value returns 0.0 when i run my code instead of the small value. I'm sure it's something I'm doing/not doing, but I'd appreciate some help on what is going on. Also as a note, I'm running J2SE 1.3.1. I saw on the API that the min double value is supposed to be around E-324 but any suggestions people? Thanks!!

    1-b1[8+(i%classes)]This is 1 - (10^-60), right? A double value only has about 16 significant digits, not 60, so the nearest possible double number to that is 1. Hence you get 1 - 1*1. There's a whole school of mathematics called "numerical analysis" that deals with questions like this. In this particular case, if b1[x] and b2[x] are always extremely small, you should evaluate the expression in advance so that it looks like b1 + b2 - b1*b2, which in turn will round to b1 + b2.
    PC&#178;

  • What tool do i use to add or subtract frames to a clip?

    hi,
    I want to click on a clip and add (or subtract) frames to a clip.
    is it possible to add or subtract frames to one end of a clip as opposed both ends at the same time?
    i need to add or subtract one frame at a time literarily. Control clicking is not precise enough.
    what tool is this, or how do i do it?
    thanks,
    humbucker

    Double click your clip in the Timeline and it opens in the Viewer.
    You should see a double row of dots in the Viewer Scrubber Bar if it's opended correctly.
    Make sure the playhead is at the end on the clip or exactly on the out point if one is entered.
    Tap the back arrow key once to to move one frame backwards or however many frames required.
    Set the new out point.
    Note: A gap will appear in the Timeline that will need to be closed.
    Al

  • Trying To Understand Pattern in Variable of Type Double

    Does any one know what could have caused the following strange pattern? Focus on finding the sequence 1211
    -2.9164014687882487
    3.1835985312117456
    -2.51640146878826
    -20.216401468788252
    2.5835985312117393
    -11.716401468788257
    3.483598531211757
    1.8835985312117554
    11.383598531211748
    -1.216401468788253
    I would like to understand the reason for the pattern. Here's how each number comes about:
    1. From a txt file pull two digit precision numbers i.e., 2.01, 3.65, 4.94 etc.
    2. Subtract two of these and divide by another number of the same precision.
    3. Assign the result to a double variable called result.
    4. printout the result
    I suspect that I am just catching some junk after the two digits and somehow that junk is mostly consistent -probably pointing at the same memory location or something like that. Still I would like to understand this a little better.
    Also, note that sequence 1211 consistently shows up in positive numbers while the sequence 8788 shows up consistently in negative numbers.
    Any feedback appreciated.

    It's not leftover junk in memory locations or anything like that. Java isn't that stupid. It's more likely to be something to do with the number you are dividing by.
    For example if you always divided by 3 (a simple example), your result would eventually go "...33333" or "...66666". This isn't a fluke or a bug, it's just something about the number 3.

  • Converting a double to an int

    Can I convert a variable of type double to a variable of type int? The reason for this is I am creating a program that will draw graphs of parabolas, cubics, etc. and the user will be able to change the values for stretches, translations, etc.
    So my code for the drawing of a parabola at the moment is somewhat primitive, I just want the basic parabola drawn in. I've done a program that does exactly this using Turing (of all things...) but Java is proving to be more picky.
    int count = 0;
    int X = 0;
    double tempY = 0;
    int Y = 0;
    while(count <= 600){
         tempY = Math.pow(X - 300,2) + 200;
         Y = tempY;     //error here
         if(Y >= 0 && Y <= 400){
              g.fillOval(X, Y, 1, 1);
         count++;
         X++;
         }Don't worry about paintComponent() and all that, it's there I'm just posting the necessary parts you guys need to see.
    So the error I get is 'possible loss of precision' at the line indicated, and I know this, it's pretty obvious, but this is what I want/need to do as the fillOval will only accept ints for it's coordinates. I also tried forgetting about having the double value of tempY and doing the math to an int but then I get 'possible loss of precision' in the math line. If anyone can give me ideas/fixes to change a double into an int it would be much appreciated as this is what I really want to do, or if you can come up with alternative ways of doing what I need to do that would also be appreciated.
    EDIT
    In case you are wondering why I am adding and subtracting those values it's because my panel I'm drawing on is (600,400) and of course (0,0) is the top left corner rather than the center where it would be on a Cartesian plane, so I think I've made all the necassary adjustments so (0,0) is now in essentially the center of the panel. It's basically scanning across from the left to right and finding X^2 from '-300' to '300' but only drawing it in if the value for Y will appear in the panel. I know it's pretty fucked up and probably some really messy code, lol. I'm somewhat inexperienced and probably being a bit too adventurous.
    Edited by: vortex on Jan 15, 2008 11:07 AM
    Edited by: vortex on Jan 15, 2008 11:15 AM

    I haven't tried that, I will try that when I get to school. I think the issue could be that -300^2 may be too big to be an int? I was just thinking before I fell asleep about it last night and that could be it too...So naturally I'll just start from say, -100, or even -25 as that isn't exactly gonna fit on the graph so I'm just wasting processor power currently I suppose. Anyways I'm gonna try both of these out and get back to you guys.
    Another issue I'm foreseeing is that one of the graphs is the root of x, so I'm going to be dealing with decimals, that's fine for double but when I turn that into an int (assuming I ever figure out how to, hoping your idea, possibly coupled with mine works) how can I round/drop the decimals?
    Edited by: vortex on Jan 16, 2008 8:10 AM

Maybe you are looking for

  • Which Table stores Purchase Order Related to Parked Invoice

    Hi Which Table stores Purchase Order Related to Parked Invoice?  I am not able to get that information. Thanks a lot in advance for any help. Thanks Arghadip

  • Steps to create a ZRSU5_SAPI_BADI

    Hi, Could anyone please provide me the steps with program code to create a filter dependent ZRSU5_SAPI_BAdi. Thanks in advance Snehasish

  • How to handle OOME in OSB/ALSB

    In WebLogic the advice on OutOfMemoryError is to restart the server via the panic action in overload configuration. However, in OSB an OOME is always caught by an OSB errorhandler, so I think that leaves you with the following options 1. in all your

  • SAP Business Consolidation without Planning License

    Would like to know what features are not available in BPC if the Planning License is not owned. How would it affect the BPC BW layer? Would some cubes be hidden? Will there be less packages available in Data Manager? Am trying to understand , what wo

  • Report Server Central Cache

    My configuration Oracle 9ias 1.0.2.2.x Reports 6i Patch 13 (cannot upgrade yet - vendor support issues), 2 W2K servers running a copy of print server each. If I want to use report clustering (Master / Slave) or just be able for the application to sea