I'm in an intro programming class, in the lab that I'm currently working on we have to have two classes and pull the methods from one class, "Energy" and have them run in "Energy Driver."
I'm having trouble calling the methods (testOne, testTwo, testThree) over into "EnergyDriver"
public class EnergyDriver
{
public static void main(String [] args)
{
System.out.println(mass1 + " kiolograms, " + velocity1 +
"meters per second: Expected 61250," + " Actual " + kineticE1);
System.out.println(mass2 + " kiolograms, " + velocity2 +
"meters per second: Expected 61250," + " Actual " + kineticE2);
System.out.println(mass3 + " kiolograms, " + velocity3 +
"meters per second: Expected 61250," + " Actual " + kineticE3);
}
}
public class Energy
{
public static void main(String [] args)
{
public double testOne;
{
double mass1;
double velocity1;
double holderValue1;
double kineticE1;
mass1 = 25;
velocity1 = 70;
holderValue1 = Math.pow(velocity1, 2.0);
kineticE1 = .5 *holderValue1 * mass1;
}
public double testTwo;
{
double mass2;
double velocity2;
double holderValue2;
double kineticE2;
mass2 = 76.7;
velocity2 = 43;
holderValue2 = Math.pow(velocity2, 2.0);
kineticE2 = .5 *holderValue2 * mass2;
}
public double testThree;
{
double mass3;
double velocity3;
double holderValue3;
double kineticE3;
mass3 = 5;
velocity3 = 21;
holderValue3 = Math.pow(velocity3, 2.0);
kineticE3 = .5 *holderValue3 * mass3;
}
}
You must have only one main method in any one of class. To call a method from another class you can create an object of that class a call their respective method. Another way is by keeping the calling method to be static so you can access that method via Classname.Methodname.
public class EnergyDriver
{
public static void main(String [] args)
{
Energy energy=new Energy();
System.out.println(mass1 + " kiolograms, " + velocity1 +
"meters per second: Expected 61250," + " Actual " + energy.testOne());
System.out.println(mass2 + " kiolograms, " + velocity2 +
"meters per second: Expected 61250," + " Actual " + energy.testTwo());
System.out.println(mass3 + " kiolograms, " + velocity3 +
"meters per second: Expected 61250," + " Actual " + energy.testThree());
}
}
class Energy
{
public double testOne()
{
double mass1;
double velocity1;
double holderValue1;
double kineticE1;
mass1 = 25;
velocity1 = 70;
holderValue1 = Math.pow(velocity1, 2.0);
kineticE1 = .5 *holderValue1 * mass1;
return kineticE1;
}
public double testTwo()
{
double mass2;
double velocity2;
double holderValue2;
double kineticE2;
mass2 = 76.7;
velocity2 = 43;
holderValue2 = Math.pow(velocity2, 2.0);
kineticE2 = .5 *holderValue2 * mass2;
return kineticE2;
}
public double testThree()
{
double mass3;
double velocity3;
double holderValue3;
double kineticE3;
mass3 = 5;
velocity3 = 21;
holderValue3 = Math.pow(velocity3, 2.0);
kineticE3 = .5 *holderValue3 * mass3;
return kineticE3;
}
}
You can get the value of Kinetic Engergy 1,2,3 by using this code.
You can also use the below code which will use only one method to calculate different values by giving different arguments.
public class EngergyDriver
{
public static void main(String [] args)
{
Energy energy=new Energy();
double mass=25;
double velocity=70;
System.out.println(mass+ " kiolograms, "+velocity+"meters per second: Expected 61250," + " Actual " + energy.testOne(mass,velocity));
}
}
class Energy
{
public double testOne(double mass, double velocity)
{
double mass1;
double velocity1;
double holderValue1;
double kineticE1;
mass1 = 25;
velocity1 = 70;
holderValue1 = Math.pow(velocity1, 2.0);
kineticE1 = .5 *holderValue1 * mass1;
return kineticE1;
}
}
Java programs have SINGLE point of entry and that is through the main method.
Therefore in a single project only one class should have the main method and when compiler will look for that when you run it.
Remember that static methods cannot access non static methods hence main is static therefore it can not access testone two nor three UNLESS you create and object of that type. Meaning in the main method you can have Energy e = new Energy() then access those methods that were not declared with keyword static like e.testone() .
However take note that non static methods can access static methods through Classname.Method name because keyword static entails that only a single copy of that method/variable exists therefore we do not need an object to access it since only one copy exists.
I recommend watching the Java videos from Lynda.com or reading the books Java Head First and Java How To Program (Deitel,Deitel) to give you a boost on your Java knowledge they come with alot of exercises to enhance your knowledge.
Also there are plenty of other questions like this on SO search for them
Related
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
I am not sure how to implement a comparable interface into my complex class. I have the following example code that I am using to try and get my head around it. I know it should be something like public double compareTo (Complex o) and something like that but I am not so sure on how to do it. Any suggestions on how i will implement it?:
import java.util.Scanner;
public class Complex implements Cloneable, Comparable {
private double real;
private double imag;
/*
* public Object clone() throws CloneNotSupportedException { Complex
* objClone = new Complex(); objClone.setReal(this.real);
* objClone.setImag(this.imag); return objClone; }
*/
public Complex(double real, double imag) {
this.real = real;
this.imag = imag;
}
public Complex(double real) {
this.real = real;
}
public Complex() {
}
public void setReal(double real) {
this.real = real;
}
public void setImag(double imag) {
this.imag = imag;
}
public double getReal() {
return real;
}
public double getImag() {
return imag;
}
public void add(Complex num1, Complex num2) {
this.real = num1.real + num2.real;
this.imag = num1.imag + num2.imag;
}
public Complex subtract(Complex num) {
Complex a = this;
double real = a.real - num.real;
double imag = a.imag - num.imag;
return new Complex(real, imag);
}
public Complex multiply(Complex num) {
Complex a = this;
double real = a.real * num.real - a.imag * num.imag;
double imag = a.real * num.imag + a.imag * num.real;
return new Complex(real, imag);
}
public Complex divide(Complex c1, Complex c2) {
return new Complex((c1.real * c2.real + c1.imag * c2.imag) / (c2.real * c2.real + c2.imag * c2.imag),
(c1.imag * c2.real - c1.real * c2.imag) / (c2.real * c2.real + c2.imag * c2.imag));
}
public double absolute() {
return Math.sqrt(real * real + imag * imag);
}
public String toString() {
return this.real + " + " + this.imag + "i";
}
#Override
public Complex clone() throws CloneNotSupportedException {
super.clone();
return new Complex(real, imag);
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter the first set of complex numbers respectively: ");
double a = in.nextDouble();
double b = in.nextDouble();
Complex c1 = new Complex(a, b);
System.out.print("Enter the second set of complex numbers respectively: ");
double c = in.nextDouble();
double d = in.nextDouble();
Complex c2 = new Complex(c, d);
Complex result = new Complex(c, d);
result.add(c1, c2);
System.out.println("(" + a + " + " + b + "i) + (" + c + " + " + d + "i) = " + result.toString());
System.out.println("(" + a + " + " + b + "i) - (" + c + " + " + d + "i) = " + c1.subtract(c2));
System.out.println("(" + a + " + " + b + "i) * (" + c + " + " + d + "i) = " + c1.multiply(c2));
System.out.println("(" + a + " + " + b + "i) / (" + c + " + " + d + "i) = " + result.divide(c1, c2).toString());
System.out.println("|" + a + " + " + b + "i| = " + c1.absolute());
}
public double compareTo(Complex other) {
return this.getReal() - other.getReal();
}
}
First, the compareTo method of Comparator interface returns int, not double. Second, if you want to compare two double values in Comparator, you should never use a - b pattern. Instead, use predefined Double.compare method:
public int compareTo(Complex other) {
return Double.compare(this.getReal(), other.getReal());
}
This method carefully handles all the special values like -0.0 or NaN which are not very easy to handle manually. Note that similar methods exist for other types: Integer.compare, Long.compare and so on. It's preferred to use them.
Of course it should be noted that there's no natural order for complex numbers. Here you just compare the real parts, completely ignoring the imaginary parts.
From a mathematical standpoint, Complex numbers can't be ordered, and as such aren't a good fit for the the Comparable interface. To quote the wikipedia article:
Because complex numbers are naturally thought of as existing on a two-dimensional plane, there is no natural linear ordering on the set of complex numbers.
There is no linear ordering on the complex numbers that is compatible with addition and multiplication. Formally, we say that the complex numbers cannot have the structure of an ordered field. This is because any square in an ordered field is at least 0, but i2 = −1.
Having said that, there's nothing technically stopping you from implementing this interface. E.g., you can decide that you are sorting by the real part first and by the imaginary part second. Note that the contract of the compareTo method requires you to return an int, not a double. Also, you should define your class as extending Comparable<Complex> instead of a raw Comparable, so you don't have to mess around with casting and runtime type checking:
#Override
public int compareTo(Complex other) {
int realCompare = Double.compare(getReal(), other.getReal());
if (realCompare != 0) {
return realCompare;
}
return = Double.compare(getImag(), other.getImag());
}
EDIT:
The improvements in JDK 8's Comparator interface allow for a much more elegant implementation with the same behavior:
public int compareTo(Complex other) {
return Comparator.comparingDouble(Complex::getReal)
.thenComparingDouble(Complex::getImag)
.compare(this, other);
}
A few points worth noting.
As other answers have noted you generally should only implement Comparable if there's a natural ordering for instances of the class. As there's no natural ordering for complex numbers you likely shouldn't implement Comparable.
If you are going to provide a natural ordering then you should implement Comparable<Complex> to denote comparing to other instances of Complex (rather than comparing to other objects).
A better alternative to implementing Comparable is to provide one or more Comparator objects for your class that can be used to provide as many orderings as you want. For example:
public class Complex {
private double real;
private double imaginary;
public static final Comparator<Complex> COMPARE_BY_REAL =
Comparator.comparingDouble(Complex::getReal);
public static final Comparator<Complex> COMPARE_BY_IMAGINARY =
Comparator.comparingDouble(Complex::getImaginary);
public static final Comparator<Complex> COMPARE_BY_MODULUS =
Comparator.comparingDouble(Complex::getModulus);
private double getModulus() {
return Math.sqrt(real * real + imaginary * imaginary);
}
}
Then the user of the class can choose the ordering that makes sense to the use:
Optional<Complex> closestToOrigin = complexList.stream().min(Complex::COMPARE_BY_MODULUS);
fix me plz. i get multiple error messages
"variable airSpeed_km might not have been initialized"
"variable width might not have been initialized"
"variable length might not have been initialized"
import java.util.Scanner;
public class V4_________1{
public static void main (String args[])
{
Scanner keyboard = new Scanner(System.in);
double KNOTS_TO_KMPHR;
double airSpeed_km;
double airSpeed_knots;
double width;
double length;
***// need to do something in the main but not sure what exactly***
airSpeed_knots = keyboard.nextDouble();
System.out.println("what is your current airspeed in knots?");
System.out.println("your current airspeed in km is: " + airSpeed_km + "your holding pattern width is: " + width + "your holding patter length is: " + length);
}
public static double getAirSpeed(double airSpeed_knots, double KNOTS_TO_KMPHR, double airSpeed_km)
{
KNOTS_TO_KMPHR = 1.852;
airSpeed_km = airSpeed_knots * KNOTS_TO_KMPHR ;
return airSpeed_km;
}
public static double calcPatternWidth(double width, double airSpeed_km)
{
width = (airSpeed_km) / (60 * Math.PI) * 2;
return width;
}
public static double calcPatternLength(double airSpeed_km, double length)
{
length = (airSpeed_km) / (60 * Math.PI) * 2 + ((airSpeed_km) / 60);
return length;
}
}
You declare:
double airSpeed_km;
And after use it:
System.out.println("your current airspeed in km is: " + airSpeed_km + "your holding pattern width is: " + width + "your holding patter length is: " + length);
without any assignment. So you get an error, you can prevent this by giving it a default value of 0 for example.
double airSpeed_km = 0;
(same goes for your other errors)
In Java, the compiler gets upset if a variable even MIGHT be used without a value.
So it is best practice to always give a value to variables when you first declare them.
Since you normally don't know the value a variable will have at the time of declaration, it is common practice to give it a value of zero.
So your declarations should look like this:
double KNOTS_TO_KMPHR=0;
double airSpeed_km=0;
double airSpeed_knots=0;
double width=0;
double length=0;
This will take care of all your "[] might not have been initialized" compiler errors.
Your code is in correct. Your cannot set variable when you pass them into a function. See both approaches and understand what going on.
You can do this:
public static void main (String args[])
{
Scanner keyboard = new Scanner(System.in);
double KNOTS_TO_KMPHR=1.852;
double airSpeed_knots;
System.out.println("what is your current airspeed in knots?");
airSpeed_knots = keyboard.nextDouble();
System.out.println("your current airspeed in km is: " + getAirSpeed(airSpeed_knots) + "your holding pattern width is: " + calcPatternWidth(getAirSpeed(airSpeed_knots)) + "your holding patter length is: " + calcPatternLength(getAirSpeed(airSpeed_knots));
}
public static double getAirSpeed(double airSpeed_knots)
{
return airSpeed_knots * KNOTS_TO_KMPHR ;
}
public static double calcPatternWidth(double airSpeed_km)
{
return (airSpeed_km) / (60 * Math.PI) * 2;
}
public static double calcPatternLength(double airSpeed_km)
{
return (airSpeed_km) / (60 * Math.PI) * 2 + ((airSpeed_km) / 60);
}
Or do this if you want to set variables:
public static void main (String args[])
{
Scanner keyboard = new Scanner(System.in);
double KNOTS_TO_KMPHR=1.852;
double airSpeed_knots;
System.out.println("what is your current airspeed in knots?");
airSpeed_knots = keyboard.nextDouble();
double airSpeed_km=getAirSpeed(airSpeed_knots);
double width=calcPatternWidth(airSpeed_km);
double length= calcPatternLength(airSpeed_km);
System.out.println("your current airspeed in km is: " + airSpeed_km + "your holding pattern width is: " + width + "your holding patter length is: " + length);
}
public static double getAirSpeed(double airSpeed_knots)
{
return airSpeed_knots * KNOTS_TO_KMPHR ;
}
public static double calcPatternWidth(double airSpeed_km)
{
return (airSpeed_km) / (60 * Math.PI) * 2;
}
public static double calcPatternLength(double airSpeed_km)
{
return (airSpeed_km) / (60 * Math.PI) * 2 + ((airSpeed_km) / 60);
}
I am new to Java and actually this code is to ask the user for 2 numbers for the conversion from inch to centimeter and vice versa. But when I built it, it said "error: cannot find symbol" and I still cannot figure it out although I kept checking the code. Below is my code:
import java.util.Scanner;
import java.util.DecimalFormat;
public class Practical2Q2 {
public Practical2Q2() {}
public static void inchToCentimeter(double a) {
System.out.println("Inches " + "Centimeters");
System.out.print("\n");
for (double i = 1.0; i <= a; i++) {
double cm = i * 2.54;
System.out.println(i + " " + df.format(cm));
}
}
public static void centimeterToInch(double b) {
System.out.print("\n");
System.out.println("Centimeters " + "Inches");
System.out.print("\n");
for (double i = 5.0; i <= b; i += 5) {
double inch = i / 2.54;
System.out.println(i + " " + df.format(inch));
}
}
public static void main(String args[]) {
Scanner newScanner = new Scanner(System.in);
DecimalFormat df = new DecimalFormat("0.00");
System.out.println("Please enter 2 numbers :\n" + "Number a for the conversion from inch to centimeter,\n"
+ "while number b for the conversion from centimeter to inch");
System.out.println("Number a : ");
double c = newScanner.nextDouble();
System.out.println("Number b : ");
double d = newScanner.nextDouble();
inchToCentimeter(c);
centimeterToInch(d);
}
}
Could you please state the wrong part?
You've created DecimalFormat df in the main method, it means that you can't access to it outside the method. I'v edited your code and i've created the field DecimalFormat df outside the main method.
I also changed the for loop inside the centimetersToInch() method, now it prints out all the values like in the inchToCentimeters() method.
Here's the code:
import java.text.DecimalFormat;
import java.util.Scanner;
public class Main {
static DecimalFormat df;
public static void inchToCentimeter(double a)
{
System.out.println("Inches " + "Centimeters");
System.out.print("\n");
for (double i = 1.0; i <= a; i++)
{
double cm = i * 2.54;
System.out.println(i + " " + df.format(cm));
}
}
public static void centimeterToInch(double b)
{
System.out.print("\n");
System.out.println("Centimeters " + "Inches");
System.out.print("\n");
for (double i = 1.0; i <= b; i++)
{
double inch = i / 2.54;
System.out.println(i + " " + df.format(inch));
}
}
public static void main(String args[])
{
Scanner newScanner = new Scanner(System.in);
df = new DecimalFormat("0.00");
System.out.println("Please enter 2 numbers :\n" + "Number a for the conversion from inch to centimeter,\n"
+ "while number b for the conversion from centimeter to inch");
System.out.println("Number a : ");
double c = newScanner.nextDouble();
System.out.println("Number b : ");
double d = newScanner.nextDouble();
inchToCentimeter(c);
centimeterToInch(d);
}
}
Your variable df is local only to your main method. Methods inchToCentimeter and centimeterToInch are unaware of this variable. Either make it a global variable or pass it as arguements to these methods.
Your df variable is not in there. Add the following line in your code.
static DecimalFormat df = new DecimalFormat("0.00");
Declare df variable as instance variable.
While doing an assignment for a BMI calculator I keep running into problems with the compiler and the method being used.
The assignment requires me to call a function double bmi to calculate the bmi. I am having problems getting the calling of the function correct. Any help would be great.
One of the errors:
Prog5.java:44: error: illegal start of expression
public static double calculateBmi(double height, double total) {
^
Code:
import java.util.Scanner;
public class Prog5 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
double avgweight,bmi,total,wReading;
int heightft,heightin,height,k;
String category,weightreading;
System.out.print("Enter the height(in feet and inches separated by spaces): ");
heightft = sc.nextInt();
heightin = sc.nextInt();
height = ((heightft*12)+heightin);
System.out.print("Enter the weight values separated by spaces followed by a negative number: ");
wReading = sc.nextDouble();
While (wReading >=0);
{
total = wReading+total;
Count++;
wReading = sc.nextDouble();
}
avgweight = 0;
total = 0;
weightreading = "Weight readings: " + wReading;
avgweight = total/Count;
public static double calculateBmi(double height, double total) {
{
double bmi = 0;
double total = 0;
double height = 0;
bmi = (height*703) / (total*total);
}
return bmi;
}
if ( bmi > 30)
category=("Obese");
else if (bmi >= 25)
category=("Overweight");
else if (bmi >= 18.5)
category=("Normal");
else {
category=("Underweight");
}
System.out.println("");
System.out.println("Height: "+ heightft + " feet " + heightin + " inches" );
System.out.println("Weight readings: "+ count);
System.out.println("Average weight: " + avgweight + "lbs");
System.out.println("");
System.out.printf("BMI: " + "%.2f", bmi);
System.out.println("");
System.out.println("Category: " + category);
System.out.println("");
}
private static void ElseIf(boolean b) { }
private static void If(boolean b) { }
}
The problem you mention is due to you beginning another method inside main. You instead want a structure something like:
public class Prog5
{
public static void main(String[] args)
{
// code here
}
public static double calculateBMI(double height, double total)
{
//other code
}
}
Your problem is that you are attempting to define a method (namely, public static double calculateBMi) inside a method (public static void main), and Java does not let you do that. (Basically, methods that aren't main need to be attached to a class.)
In the future, you may want to look around before asking this kind of question, since duplicate versions of this have been asked. Your question is basically: Function within a function in Java
Exercise 1: Write an application that prints the hundreds digit in two integers read from the keyboard. For example, if the data values are 1456 and 254 respectively, your program should print 4 and 2. You may choose the integers yourself. Your output should include the original number followed by the digit in the hundreds position. Label your output appropriately.
That was my question; here's the code I attempted to write using Eclipse.
public class Hundreds
{
int first1 = 1523;
first2 = first1 % 1000;
first3 = first2 / 100;
System.out.println("Original number equals: " + first1);
System.out.println("Hundreds digit equals: " + first3);
int second1 = 589;
second2 = 589 / 100;
System.out.println("Original number equals: " + second1);
System.out.println("Hundreds digit equals: " + second2);
}
I'm sure there would be a better method to naming the numbers; that's just what I came up with… but Eclipse shows an error reading:
java.lang.NoSuchMethodError: main
Exception in thread "main"
when I attempt to run it. Any ideas on what I've done incorrectly here?
You need a main() method. The error message you see is because the JVM wants to run main(), but it cannot find it.
A canonical Java example (taken from http://en.wikipedia.org/wiki/Java_(programming_language)#Hello_world) is:
class HelloWorldApp {
public static void main(String[] args) {
System.out.println("Hello World!"); // Display the string.
}
}
You need to put your logic in a main method:
public class Hundreds {
public static void main(String[] args) {
int first1 = 1523;
first2 = first1 % 1000;
first3 = first2 / 100;
System.out.println("Original number equals: " + first1);
System.out.println("Hundreds digit equals: " + first3);
int second1 = 589;
second2 = 589 / 100;
System.out.println("Original number equals: " + second1);
System.out.println("Hundreds digit equals: " + second2);
}
}
You need to have a main method as in the Java programming language, every application must contain a main method (entry point) whose signature is:
public static void main(String[] args)
So your code should look like:
public class Hundreds
{
public static void main(String[] args) {
int first1 = 1523;
int first2,first3,second2;
first2 = first1 % 1000;
first3 = first2 / 100;
System.out.println("Original number equals: " + first1);
System.out.println("Hundreds digit equals: " + first3);
int second1 = 289;
second2 = 589 / 100;
System.out.println("Original number equals: " + second1);
System.out.println("Hundreds digit equals: " + second2);
}
}
You could see The Method main; it's a short explanation of its usages.
You need a main method.
public class Hundreds {
public static void main(String[] args) {
// put code here
}
}
Dude...
Where is your main method?
public static void main.....
The rest of your code should go inside it...
BTW, this is the part where you hit your forehead and say "duh..." ;-)
Good luck