Question:

Help! I need a Java nerd (no offense) to proofread this small Java Program. Giving 10 points for Best answer!?

by  |  earlier

0 LIKES UnLike

This program is supposed to solve the distance formula. But when I compile it, an error called "operator^ cannot be applied to double,double Pops up. Why? I will give 10 points for the best answer.

import java.lang.Math;

import java.util.Scanner;

class DistanceFormula {

public static void main(String args[]) {

Scanner myScanner = new Scanner(System.in);

double x1;

double x2;

double y1;

double y2;

double distance;

System.out.print("x1= ");

x1 = myScanner.nextDouble();

System.out.print("x2= ");

x2 = myScanner.nextDouble();

System.out.print("y1= ");

y1 = myScanner.nextDouble();

System.out.print("y2= ");

y2 = myScanner.nextDouble();

System.out.print("Distance= ");

distance = Math.sqrt((x2-x1)^2+(y2-y1)^2);

}

}

 Tags:

   Report

3 ANSWERS


  1. ^ is not a power operator in java it is a bitwise operator which can be applied only for int data types

    use math.pow in place of ^

    math.pow((x2-x1),2);


  2. I believe in Java, the caret (^) is a bitwise operator, not an exponential operator.  You need to use Math.sqrt((x1-x2)(x1-x2) + (y1-y2)(y1-y2));

  3. Replace the last calculation with this one:

    distance = Math.sqrt(Math.pow((x2-x1),(double)2) +

       Math.pow((y2-y1), (double)2));

    System.out.println("" + distance);

Question Stats

Latest activity: earlier.
This question has 3 answers.

BECOME A GUIDE

Share your knowledge and help people by answering questions.