Return a range to compare with BigDecimal - java

In my code a user enters in a specified temperature range with this method (The default range is 0 - 100):
public class range {
public void rangeset ()
{
int range1 = 0;
int range2 = 100;
System.out.println("Please note that the default temp range is 0-100");
System.out.println("What is the starting temperature range?");
range1 = sc.nextInt();
System.out.println("What is the ending temperature range?");
range2 = sc.nextInt();
System.out.println("Your temperature range is " + range1 + " - " + range2);
HW_5.mainMenureturn();
}//end rangeset method (instance method)
}//range class
Further down, I have an input that asks the user for a number that they want to convert to Fahrenheit.
public class HW_5 {
public static double fahrenheit2Centigrade ()
{
double result;
BigDecimal quotient = new BigDecimal("1.8");
//take in input, take input as BigDecimal
System.out.println("Please enter the fahrenheit temperature you wish to convert to celsius");
BigDecimal fah = sc.nextBigDecimal();
}
}
So, what I want to do is make sure that the number they entered (which is a BigDecimal) falls within the ranges specified in the other method.
1) How do I get my rangeset method to return the beginning number of the range and the ending number of the range since you can't return two values?
2) How do I then use those returned values to check if the BigDecimal in the fahrenheit2centigrade method falls within those values?
Please ask for clarification. Thanks.

This is an issue of scope. Currently you are declaring your two range variables inside the rangeset() method, which means that they are only visible within the "scope" of the method (aka only that method has access to those variables).
What you should consider doing is instead have those variables be visible to the entire class.
public class range {
private int lowerBound;
private int upperBound;
public void rangeset ()
{
int lowerBound = 0;
int upperBound = 100;
System.out.println("Please note that the default temp range is 0-100");
System.out.println("What is the starting temperature range?");
lowerBound = sc.nextInt();
System.out.println("What is the ending temperature range?");
upperBound = sc.nextInt();
System.out.println("Your temperature range is " + range1 + " - " + range2);
HW_5.mainMenureturn();
}//end rangeset method (instance method)
public int getLowerBound()
{
return lowerBound;
}
public int getUpperBound()
{
return upperBound;
}
}//range class
Once you have things set up in this way, you can create a new range class in your main class, call the relevant methods on it, and use your getter methods to extract the data that you care about. Something like:
public class HW_5 {
public static double fahrenheit2Centigrade ()
{
double result;
BigDecimal quotient = new BigDecimal("1.8");
range myRange = new range();
myRange.rangeset();
System.out.printf("%d - %d", myRange.getLowerBound(), myRange.getUpperBound());
//take in input, take input as BigDecimal
System.out.println("Please enter the fahrenheit temperature you wish to convert to celsius");
BigDecimal fah = sc.nextBigDecimal();
}
}
Ps. Generally you should use capital letters to start your class names, ie. Range instead of range.

Related

How to create a helper method that takes 2 double inputs into a class global array?

I'm new to java and I have a question about an assignment I have. I've written a bunch of methods that are different formulas, like the duration of a storm. The assignment asks me to write two helper methods to get input from the user. One of them is called get_S_Input() and I was able to implement it correctly I think. But the one I'm stuck on is this other helper method called get_2_Invals(). It wants me to prompt the user with my parameter, and read in 2 double values. It wants me to record the values in a class global array of doubles and then exit the method, but I don't know how to do this. I want to put it in the else statement in the method below. Here is my code so far...
import java.lang.Math;
import java.util.Scanner;
public class FunFormulas {
public void sd(){
double durationOfStorm = Math.sqrt(((Math.pow(get_S_Input("Enter the diameter of storm in miles:"), 3) / 216)));
if (durationOfStorm > 0)
System.out.println("The storm will last: " + durationOfStorm);
}
public void sl(){
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the number of seconds since the lightning strike:");
double secondsSinceLightning = Double.valueOf(scanner.nextLine());
double distanceFromLightning = (1100 * secondsSinceLightning);
System.out.println(distanceFromLightning);
}
public void si(){
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the edge of cube in inches:");
double edgeOfCubeInInches = Double.valueOf(scanner.nextLine());
if (edgeOfCubeInInches < 0){
System.out.println("ERROR: please enter a non-negative number!!!");
}
double weightOfCube = (0.33 * (Math.pow(edgeOfCubeInInches, 3)));
System.out.println(weightOfCube);
}
public void dt(){
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the time in hours:");
double timeInHours = Double.valueOf(scanner.nextLine());
if (timeInHours < 0){
System.out.println("ERROR: please enter a non-negative number!!!");
}
System.out.println("Enter the rate of speed in mph:");
double rateOfSpeed = Double.valueOf(scanner.nextLine());
if (rateOfSpeed < 0){
System.out.println("ERROR: please enter a non-negative number!!!");
}
double distanceTravelled = (rateOfSpeed * timeInHours);
System.out.println(distanceTravelled);
}
public void sa(){
Scanner scanner = new Scanner(System.in);
System.out.println("Enter your weight in pounds:");
double weight = Double.valueOf(scanner.nextLine());
weight = weight * 0.4536;
System.out.println("Enter your height in inches:");
double height = Double.valueOf(scanner.nextLine());
height = height * 2.54;
double BSA = ((Math.sqrt(weight * height)) / 60);
System.out.println(BSA);
}
public double get_S_Input(String promptStr){
//Scanner helper method
System.out.println(promptStr);
Scanner scanner = new Scanner(System.in);
double value = Double.valueOf(scanner.nextLine());
if (value < 0 ){
System.out.println("ERROR: please enter a non-negative number!!!");
}
return value;
}
public void get_2_Invals(String promptStr){
/*Prompt the user with the promptStr passed in as a parameter
ii. Read in the first double precision value entered by the user with the Scanner
iii. Read in the second double precision value entered by the user with the Scanner
iv. Check to make sure the values entered by the user are non-negative
a. If either number entered by the user is negative, the method should print out an
error message, and return to step i. above.
b. If the number is non-negative (that is greater than or equal to zero) the method
should record the numbers obtained from the user in a class-global array of
doubles and exit.*/
System.out.println(promptStr);
Scanner scanner = new Scanner(System.in);
double firstValue = scanner.nextInt();
double secondValue = scanner.nextInt();
if (firstValue < 0 || secondValue < 0)
System.out.println("ERROR: please enter non-negative number!");
else
}
public static void main(String [] args){
FunFormulas fun = new FunFormulas();
fun.sd();
}
}

How do I call a method into my main method so it can execute the program?

Obviously, I'm not looking for all the answers but some direction would be much appreciated.
So I have this program that prompts the user to enter their annual interest rate and savings amount. The program calculates the compound value for 6 months.
I'm having issues calling the new method into the main method to execute the calculations. The main method asks the users for their annual interest rate and the savings amount. It calls the new method, and if all are positive numbers it executes the program. If any are negative it comes up with an error.
I thought I called the method in the last line with calling it but obviously I am wrong. I have tried googling and am having trouble understanding this calling aspect. Any information would be appreciated. I'm new so I'm still working on this programming thing! Not sure why that last curly bracket isn't in the code. Here's the code:
import java.text.DecimalFormat;
import javax.swing.JOptionPane;
public class FifthAssignment {
static double savingAmount = 0.0; // the 2 given static doubles
static double annualInterestRate = 0.0;
int sixthMonth;
public static double compoundValueMethod(double savingAmount, double annualInterestRate, int sixthMonth) {
return sixthMonth; // sixMonth is the compound value
}
{
DecimalFormat formatter = new DecimalFormat(".00");
double monthlyInterestRate = annualInterestRate / 12;
if (savingAmount < 0)
if (annualInterestRate < 0) {
JOptionPane.showMessageDialog(null, "Error. Both of your values are negative!");
System.exit(0);
}
if (savingAmount < 0) {
JOptionPane.showMessageDialog(null, "Error. Your savings amount is negative!");
}
else if (annualInterestRate < 0) {
JOptionPane.showMessageDialog(null, "Error. Your annual interest rate is negative!");
}
else {
for (int i = 1; i <= 6; i++) {
sixthMonth = (int) ((savingAmount + sixthMonth) * (1 + monthlyInterestRate));
}
}
}
public static void main(String[] args) {
DecimalFormat formatter = new DecimalFormat(".00"); // bring in the
// decimal
// formatting for
// program
String SA = JOptionPane.showInputDialog("What is your savings amount? "); // Window
// pops
// up
// asking
// for
// your
// savings
// amount.
// As
// a
// string?
savingAmount = Double.parseDouble(SA); // Returns a double given to
// value in string above
String AIR = JOptionPane.showInputDialog("What is the annual interest rate? "); // Window
// pops
// up
// asking
// for
// annual
// interest
// rate.
// String
// as
// above.
annualInterestRate = Double.parseDouble(AIR); // Returns the same as
// savings amount but
// for annual interest
// rate
{
JOptionPane.showMessageDialog(null, "Your total compounded value after 6 months is "
+ compoundValueMethod(savingAmount, annualInterestRate, 6));
}
}
}
Function Call should have parenthesis
Try This:
JOptionPane.showMessageDialog(null, "Your total compounded value after 6 months is " + compoundValueMethod(savingAmount,annualInterestRate,6));
Your function should return the computed value, but in your case you are returning 'void', so it should be like this
public static int compoundValueMethod(double savingAmount, double annualInterestRate, int sixthMonth) {
int res = 0;
DecimalFormat formatter = new DecimalFormat(".00");
sixthMonth = 6;
double monthlyInterestRate = annualInterestRate / 12;
if (savingAmount < 0)
if (annualInterestRate < 0) {
JOptionPane.showMessageDialog(null, "Error. Both of your values are negative!");
System.exit(0);
}
if (savingAmount < 0) {
JOptionPane.showMessageDialog(null, "Error. Your savings amount is negative!");
}
else if (annualInterestRate < 0) {
JOptionPane.showMessageDialog(null, "Error. Your annual interest rate is negative!");
}
else {
for (int i = 1; i <= 6; i++) {
res = (int) ((savingAmount + res ) * (1 + monthlyInterestRate));
}
}
return res;
}
Based on the current code you have written, the function is not called properly and should look like :
JOptionPane.showMessageDialog(null, "Your total compounded value after 6 months is " + compoundValueMethod(savingAmount,annualInterestRate,6));
If you always want the value of 6 to be passed to your function, then instead of having it as a parameter to the function, you should be better off declaring a static final class variable like this:
private final static int SIXTH_MONTH = 6;
If you want to read the number of months, then yes your function should have that parameter, you should read that parameter just like the other 2 params you are reading and pass it along. And you should remove the line that is assigning the value of 6 to your method parameter.
sixthMonth = 6;
and instead use the value passed in to the function from the main() function

Incompatible types: possible lossy conversion from double to int [duplicate]

This question already has an answer here:
What does "possible lossy conversion" mean and how do I fix it?
(1 answer)
Closed 3 years ago.
Help? I don't know why I am getting this error. I am getting at in line 39:
term[1] = differentiate(Coeff[1], exponent[1]);
How can I fix this issue?
Full code listing:
public class Calcprog {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int numTerms = 7;
double[] Coeff = new double[6];
double[] exponent = new double[6];
String[] term = new String[6];
System.out.println("Enter the number of terms in your polynomial:");
numTerms = input.nextInt();
while (numTerms > 6) {
if (numTerms > 6) {
System.out.println("Please limit the number of terms to six.");
System.out.println("Enter the number of terms in your polynomial:");
numTerms = input.nextInt();
}
}
for (int i = 1; i < numTerms + 1; i++) {
System.out.println("Please enter the coefficient of term #" + i + " in decimal form:");
Coeff[i] = input.nextDouble();
System.out.println("Please enter the exponent of term #" + i + " in decimal form:");
exponent[i] = input.nextDouble();
}
term[1] = differentiate(Coeff[1], exponent[1]);
}
public String differentiate(int co, int exp) {
double newco, newexp;
String derivative;
newexp = exp - 1;
newco = co * exp;
derivative = Double.toString(newco) + "x" + Double.toString(newexp);
return derivative;
}
}
You are trying to pass double arguments to a method that accepts ints, which requires a casting that may result in loss of information.
You can make it work by an explicit cast :
term[1] = differentiate((int)Coeff[1], (int)exponent[1]);
Or you can change your differentiate method to accept double arguments, which would probably make more sense :
public String differentiate(double co, double exp)
your method is not static, and you calling in the main which is static, remember a non static method can be access direct in a static method, you have to create an instance of the class to access that method, and also the parameter you are passing is double and not int. Your method should be like that public static String differentiate(double co, double exp){
change the argument types of the differentiate method to double. This should then look as follows
public String differentiate(double co, double exp){
...
}

Java Averaging Program

Write a class called Average that can be used to calculate average of several integers. It should contain the following methods:
 A method that accepts two integer parameters and returns their average.
 A method that accepts three integer parameters and returns their average.
 A method that accepts two integer parameters that represent a range. Issue an error message and return zero if the second parameter is less than the first one. Otherwise, the method should return the average of the integers in that range (inclusive).
I am totally new to Java and programming, this has me completely lost! Here's what I've tried.
import java.util.Scanner;
public class Average {
public static void main(String[] args) {
double numb1, numb2, numb3;
System.out.println("Enter two numbers you'd like to be averaged.");
Scanner keyboard = new Scanner(System.in);
numb1 = keyboard.nextInt();
numb2 = keyboard.nextInt();
}
public double average (int num1, int num2) {
return (num1 + num2) / 2.0;
}
public double average (int num1, int num2, int num3)
{
return (num1 + num2 + num3) / 3.0;
}
}
The program doesn't go past getting the values from the user. Please help!
You have to actually call your methods.
Just place
Average avg = new Average();
System.out.println("The average is: " + avg.average(numb1, numb2));
at the end of your main method.
Alternatively you can make the methods static:
public static double average (int num1, int num2) {
return (num1 + num2) / 2.0;
}
More info on constructors and static.
It looks like your not actually printing out the results. Try the following.
System.out.print(average(numb1, numb2));
Let's detail what you did there.
public static void main(String[] args) {
//Create variables numb1, numb2 & numb3
double numb1, numb2, numb3;
System.out.println("Enter two numbers you'd like to be averaged.");
//Read standard input (keyboard)
Scanner keyboard = new Scanner(System.in);
//Retrieve first input as an int
numb1 = keyboard.nextInt();
//Retrieve second input as an int
numb2 = keyboard.nextInt();
}
Then your two next methods compute for two or three given integers their average.
The main method is the first method called during your program execution. The jvm will execute everything inside. So it will declare the three doubles, read two values from keyboard and then end.
If you want to compute the average of numb1 & numb2 using your method, you have to create an object Average and call your average method like this
public static void main(String[] args) {
//Create variables numb1, numb2 & numb3
double numb1, numb2, numb3;
System.out.println("Enter two numbers you'd like to be averaged.");
//Read standard input (keyboard)
Scanner keyboard = new Scanner(System.in);
//Retrieve first input as an int
numb1 = keyboard.nextInt();
//Retrieve second input as an int
numb2 = keyboard.nextInt();
//Declare the average value
double average;
//Create an average instance of the class average
Average averageObject = new Average();
//Call your average method
average = averageObject.average(numb1,numb2);
//Print the result
System.out.println("Average is : " + average);
}
Everything in Java is object (read about Object Oriented Programming).
Writing your class "Average" defines how your object is structured. It has attributes (characteristics) and methods (actions). Your Average object has no attributes. However it has two methods (average with two and three numbers) acting on integers.
However your class is just the skeleton of your object. You need to create an object from this skeleton using the keyword new as :
Average averageObject = new Average();
Sincerely
public class Marks {
int roll_no;
int subject1;
int subject2;
int subject3;
public int getRoll_no() {
return roll_no;
}
public void setRoll_no(int roll_no) {
this.roll_no = roll_no;
}
public int getSubject1() {
return subject1;
}
public void setSubject1(int subject1) {
this.subject1 = subject1;
}
public int getSubject2() {
return subject2;
}
public void setSubject2(int subject2) {
this.subject2 = subject2;
}
public int getSubject3() {
return subject3;
}
public void setSubject3(int subject3) {
this.subject3 = subject3;
}
public void getDetails(){
Scanner sc = new Scanner(System.in);
System.out.println("Enter the marks of subject1");
this.subject1 = sc.nextInt();
System.out.println("Enter the marks of subject2");
this.subject2 = sc.nextInt();
System.out.println("Enter the marks of subject3");
this.subject3 = sc.nextInt();
System.out.println("Enter the roll number");
this.roll_no = sc.nextInt();
}
public int getAverage(){
int avg = (getSubject1() + getSubject2() + getSubject3()) / 3;
return avg;
}
public void printAverage(){
System.out.println("The average is : " + getAverage());
}
public void printRollNum(){
System.out.println("The roll number of the student is: " + getRoll_no());
}
public static void main(String[] args){
Marks[] e1 = new Marks[8];
for(int i=0; i<2; i++) {
System.out.println("Enter the data of student with id:");
e1[i] = new Marks();
e1[i].getDetails();
e1[i].printAverage();
}
System.out.println("Roll number details");
for(int i=0; i<2; i++){
e1[i].printRollNum();
}
}
}
If you'd like your program to find the average you need to include a call to that method in your main method.
numb1 = keyboard.nextInt();
numb2 = keyboard.nextInt();
System.out.println("The average of " + numb1 + " and " + numb2 + " is " + average(numb1,numb2);
}
you need to call the methods that you have written after you accept the input.
...
System.out.println("Enter two numbers you'd like to be averaged.");
Scanner keyboard = new Scanner(System.in);
numb1 = keyboard.nextInt();
numb2 = keyboard.nextInt();
System.out.println(average (int numb1 , int numb2 ))
...
You probably want to provide a menu of options for the user to select to determine which method to call
System.out.println("Select one option");
System.out.println("1. Enter two numbers you'd like to be averaged.");
System.out.println("2. Enter the 3 numbers you want averaged.");
System.out.println("3. Enter the number Range you want averaged.");
and based on that answer you can determine which method to call
After the access specifier (public) and before the return type (double) place the Java keyword static. You shouldn't worry about what this means right now.
You have to use bitwise operators.
average of int a and b can be calculated as
avg= (a >> 1) + (b >> 1) + (((a & 1) + (b & 1)) >> 1);
The main method will only execute what it is asked to. If you want the average methods to be executed, you will have to create an object, pass the required variable and call the methods from the main method. Write the following lines in the main method after accepting the input.
Average avrg = new Average();
System.out.println("The average is: " + avrg.average(numb1, numb2, numb3));
Write only numb1 and numb2 if you want to average only two numbers.

Java Overloaded Methods

I am trying to use one file to create a menu in the command window. The user selects from those menu options. They are prompted to enter a number. The number is passed to two overloaded methods which determine if the number is an integer or a float. After the calculation is done the result is printed to the screen and the menu reappears. Here is the code from my two files.
MyMathOpsTest class:
import java.util.Scanner; // import Scanner class
public class MyMathOpsTest
{
//method to pause until a key is pressed
public static void pause()
{
try
{
System.out.print("Press <Enter> to continue...");
System.in.read();
}
catch (Exception e)
{
System.err.printf("Error %s%c\n",e.getMessage(),7);
}
}//end pause
public static void main( String args[] )
{
//variables to capture keyboard input
Scanner keyBd = new Scanner( System.in );
char selection;
//int selection;
do{//display menu
System.out.println( "1. Square a Number");
System.out.println( "2. Cube a Number");
System.out.println( "3. Raise a Number to a Power");
System.out.println( "4. Maximum of Three Numbers");
System.out.println( "5. Minimum of Three Numbers");
System.out.println( "6. Exit");
System.out.print( "Selection[1-6]: " );
//get menu selection
selection = keyBd.next().charAt(0);
//selection = keyBd.nextInt();
//process menu selection
switch (selection){
case '1':
MyMathOpsTest.squareTheNumber();
pause();
break;
case '2':
MyMathOpsTest.cubeTheNumber();
pause();
break;
case '3':
MyMathOpsTest.raiseTheNumber();
pause();
break;
case '4':
MyMathOpsTest.maximumNumber();
pause();
break;
case '5':
MyMathOpsTest.minimumNumber();
pause();
break;
case '6':
//recognize as valid selection but do nothing
break;
default :
System.out.printf("%c\n",7);
System.out.println("Invalid Selection");
}//end switch
}while( selection != '6');
} // end method main
public static void squareTheNumber()
{
}
public static void cubeTheNumber()
{
}
public static void raiseTheNumber()
{
}
public static void maximumNumber()
{
MyMathOps.maximum();
}
public static void minimumNumber()
{
}
} // end class MyMathOpsTest
MyMathOps class:
import java.util.Scanner;
public class MyMathOps
{
public static int square(x:Integer):Integer
{
}
public static double square(x:Double):Double
{
}
public static int cube(x:Integer):Integer
{
}
public static double cube(x:Double):Double
{
}
public static int maximum(x:Integer, y:Integer, z:Integer):Integer
{
// create Scanner for input from command window
Scanner input = new Scanner( System.in );
// obtain user input
System.out.print( "Enter three integer values separated by spaces: ");
int numberl = input.nextInt();
// read first integer
int number2 = input.nextInt();
// read second double
int number3 = input.nextInt();
// read third double
// determine the maximum value
int result = maximum( numberl, number2, number3 );
// display maximum value
System.out.println( "Maximum is: " + result );
} // end method maximum
public static double maximum(x:Double, y:Double, z:Double):Double
{
// create Scanner for input from command window
Scanner input = new Scanner( System.in );
// obtain user input
System.out.print( "Enter three floating-point values separated by spaces: ");
number1 = input.nextDouble();
// read first double double
number2 = input.nextDouble();
// read second double
double number3 = input.nextDouble();
// read third double
// determine the maximum value
double result = maximum( numberl, number2, number3 );
// display maximum value
System.out.println( "Maximum is: " + result );
} // end method maximum
public static int minimum(x:Integer, y:Integer, z:Integer):Integer
{
// create Scanner for input from command window
Scanner input = new Scanner( System.in );
// obtain user input
System.out.print( "Enter three integer values separated by spaces: ");
int numberl = input.nextInt();
// read first integer
int number2 = input.nextInt();
// read second double
int number3 = input.nextInt();
// read third double
// determine the minimum value
int result = minimum( numberl, number2, number3 );
// display minimum value
System.out.println( "Minimum is: " + result );
} // end method minimum
public static double minimum(x:Double, y:Double, z:Double):Double
{
// create Scanner for input from command window
Scanner input = new Scanner( System.in );
// obtain user input
System.out.print( "Enter three floating-point values separated by spaces: ");
number1 = input.nextDouble();
// read first double double
number2 = input.nextDouble();
// read second double
double number3 = input.nextDouble();
// read third double
// determine the minimum value
double result = minimum( numberl, number2, number3 );
// display minimum value
System.out.println( "Minimum is: " + result );
} // end method minimum
} // end class MyMathOps
This code is a combination of code I type myself and example code from my text book. This will not compile for me in jGRASP. I get these errors.
MyMathOps.java:10: <identifier> expected
public static int square(x:Integer):Integer
^
MyMathOps.java:96: ')' expected
} // end method minimum
^
2 errors
----jGRASP wedge: exit code for process is 1.
----jGRASP: operation complete.
What am I doing wrong here? I have spent hours working on this and reading in my textbook. If I do not get this right. I will get a bad grade. I need to get a good grade in this class so I can get into a top notch Computer Science University. Thanks for your help.
In the unlikely event that my instructor or any administrator from Salt Lake Community College ever comes across this question, let me make my intentions clear. This question is posted in the greatest spirit of academic honesty. I ask this question to seek general advice and help in understanding the proper way to use the Java programming language. I in no way use the work of others and represent it as my own work. I use the answers provided here as a general aid in my understanding. I do all my own work and do not copy work provided by people answering my question.
The lines like this are not valid Java syntax:
public static int square(x:Integer):Integer
public static int maximum(x:Integer, y:Integer, z:Integer):Integer
...
This looks like a UML or pseudo-code syntax. "x:Integer" is "language-agnostic" notation that means that x is an Integer type (which maps to an int or Integer object in Java). The ":Integer" at the end means that the method returns an Integer type, which you are doing correctly already.
Try changing all your method declarations to look like this:
public static int square(int x) // Or "Integer x" if you want to use the Integer class, rather than the primitive int
public static int maximum(int x, int y, int z)
....
I am guessing that you are used to Pascal (or a derivative).
public static int square(x:Integer):Integer
in Java that is
public static int square(int x)
Also since the code is inside of "MyMathOpsTest" you do not need to prefix the method calls with "MyMathOpsTest.".
Also, why call it "MyMathOps" instead of "MathOperationsTest"? Of course it is yours - it doesn't be long to me or anyone else! Pick names that have meaning, try to avoid shorthands like "Ops", unless it is common for the field you are working in (URL is a good one, "Ops" isn't).
And now for the generl programming advice for a beginner:
write a single line of code
get that line of code to compile
once that line of code compiles work on the next one
get the next line of code to compile
keep doing that until the program is done.
There is no point in making the same mistakes over and over again - all you get good at is making mistakes, and that isn't much fun.
So to get you started...
Step 1:
public class MathOperations
{
public static int maximum(final int x, final int y, final int z)
{
}
}
(compile the above code)
Step 2:
public class MathOperations
{
public static int maximum(final int x, final int y, final int z)
{
final Scanner input;
}
}
(compile the above code)
Step 3:
public class MathOperations
{
public static int maximum(final int x, final int y, final int z)
{
final Scanner input;
intput = new Scanner(System.in);
}
}
(compile the above code)
and then keep going one line at a time. Once you get the hang of it you can do more than one line, but at the start, doing it one line at a time will show you immediately when you make a mistake. Make sure that you fix ALL of the mistakes before you move on to the next line.
Also, at the end of the first method pause(), you need another curly brace:
public static void pause()
{
try
{
System.out.print("Press <Enter> to continue...");
System.in.read();
}
catch (Exception e)
{
System.err.printf("Error %s%c\n",e.getMessage(),7);
}
}<-- this one is missing in yours
Hope this helps!
I don't know what the point of the exercise is - the math ops, the overloading, or the menu. But I'd recommend that you start over with these as your basis. At least they compile and run:
public class MyMathOps
{
public static int square(int x)
{
return x*x;
}
public static double square(double x)
{
return x*x;
}
public static int cube(int x)
{
return x*x*x;
}
public static double cube(double x)
{
return x*x*x;
}
public static int maximum(Integer... values)
{
Integer maxValue = Integer.MIN_VALUE;
for (Integer value : values)
{
if (value.compareTo(maxValue) > 0)
{
maxValue = value;
}
}
return maxValue;
}
public static double maximum(Double... values)
{
Double maxValue = Double.MIN_VALUE;
for (Double value : values)
{
if (value.compareTo(maxValue) > 0)
{
maxValue = value;
}
}
return maxValue;
}
public static int minimum(Integer... values)
{
Integer minValue = Integer.MAX_VALUE;
for (Integer value : values)
{
if (value.compareTo(minValue) < 0)
{
minValue = value;
}
}
return minValue;
}
public static double minimum(Double... values)
{
Double minValue = Double.MIN_VALUE;
for (Double value : values)
{
if (value.compareTo(minValue) < 0)
{
minValue = value;
}
}
return minValue;
}
}
and the test class (simplified):
public class MyMathOpsTest
{
public static void main(String args[])
{
Integer [] intValues = { 1, 2, 3, };
Double [] doubleValues = { 11.0, 14.0, -6.0 };
for (Integer value : intValues)
{
System.out.println("value : " + value);
System.out.println("squared: " + MyMathOps.square(value));
System.out.println("cubed : " + MyMathOps.cube(value));
System.out.println("min : " + MyMathOps.minimum(intValues));
System.out.println("max : " + MyMathOps.maximum(intValues));
}
for (Double value : doubleValues)
{
System.out.println("value : " + value);
System.out.println("squared: " + MyMathOps.square(value));
System.out.println("cubed : " + MyMathOps.cube(value));
System.out.println("min : " + MyMathOps.minimum(doubleValues));
System.out.println("max : " + MyMathOps.maximum(doubleValues));
}
}
}
When this is done running, you'll know that your methods are correct. Spare yourself the difficulties of reading in values on the first try.

Categories