Using Parameter Passing in Netbeans/Java - java

I am new to net beans and java and by using net beans GUI, I have to create a linear conversion table. These are the choices: Inches to Centimeters
Feet to Centimeters
Yards to Meters
Miles to Kilometers. The following formulas can be used to convert English Imperial units of measurements to Metric units:
Centimeters = Inches * 2.54
Centimeters = Feet * 30
Meters = Yards * 0.91
Kilometers = Miles * 1.6
It should be created using parameter passing and should return values back to method call.`
This is what I have done so far:
int conversion;
double centimetres = 0,value, metres = 0, kilometres = 0;
conversion=Integer.parseInt(conversioninput.getText());
value=Integer.parseInt(valueinput.getText());
if (conversion==1)
centimetres=value*2.54;
output.setText(""+value+" inches = "+centimetres+ " centimetres");
if (conversion==2)
centimetres=value*30;
output.setText(""+value+" feet = "+centimetres+ " centimetres");
if (conversion==3)
metres=value*0.91;
output.setText(""+value+" yards = "+metres+ " metres");
if (conversion==4)
kilometres=value*1.6;
output.setText(""+value+" miles = "+kilometres+ " kilometres");
I need to include parameter passing and I have no idea how to do it. I am doing an online course and it does not explain anything

What you would want to do is something like this:
public float conversion(int value, int conversion) {
// put your code inside this method
}
Then to call it inside your main method just do:
conversion(40, 2);
It seems like you are new to programming in general, but I would look into enums for the conversion variable. And setup a class something like:
public enum Conversion {
InchToCentimeter,
FeetToCentimeter,
YardsToMeters,
KilometersToMiles
}
Here's a good starting point for enums: https://docs.oracle.com/javase/tutorial/java/javaOO/enum.html

Related

Java: method for an equation relevant to the Karplus-Strong equation does not return the anticipated result; unclear cause

In Part 1 of a prompt, I am expected to integrate an equation into Java to get the value for a period (T). The equation is as follows: T = FS / (440 * (2 ^(h/12))
NOTE:
FS = sample rate, which is 44100 / 1.
h = halfstep, which is provided by the user.
An example of this equation is: 44100 / (440 * (2 ^(2/12)) = 89.3
The code I wrote is as follows:
public static double getPeriod(int halfstep) {
double T = 100; // TODO: Update this based on note
double FS = 44100 / 1;
double power = Math.pow(2, (halfstep / 12));
double denominator = 440 * (power);
double result = (FS) / (denominator);
T = Math.round(result);
return T;
}
// Equation test.
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("halfstep is: ");
int halfstep = in.nextInt();
double period = getPeriod(halfstep);
System.out.print("Period: " + period + " ");
}
But when I run through this code with h = 2, T = 100.0 instead of the anticipated 89.3 and I am not sure what the issue is. Any thoughts on what's going on?
Because halfStep is an int, when you write
(halfstep / 12)
the calculation is done by taking halfStep / 12 and rounding down to the nearest integer. As a result, if you plug in 2 here, then halfStep / 12 will come back as 0 instead of 1/6. That's messing up the computation and is likely what's giving you the wrong answer.
You have a few options for how to proceed here. One would be to change halfStep to be a double rather than an int. Another would be to rewrite the division as
halfStep / 12.0
which, since 12.0 is a double literal, will perform the division in the way you intend.
One other potential issue - you declare the variable T as 100.0, but never use T anywhere in the calculation and ultimately overwrite it before returning it. I'm not sure whether this is intentional or whether that indicates that one of the formulas is incorrect.
Hope this helps!

How to convert a given length in centimeter and represent it as a combination of kilometers, meters and centimeters?

I need to get a centimeter number input by the user, and then representing it as a combination of kilometers, meters, and centimeters. For example, 1005020 centimeters will be 10km, 50meters, and 20 centimeters.
I just started out and I feel It's a really basic question and I feel so frustrated.
I've tried to code and unfortunately can't reach the desired result
Scanner scanner = new Scanner(System.in);
System.out.println("This program takes centimeter number and represent it as a combination of kilometer, meter, and centimeter");
System.out.println("Please enter centimeters:");
double centimeters = scanner.nextDouble();
double convertedCentimeters = centimeters;
double kilometers = (int) (convertedCentimeters / 100000);
convertedCentimeters /= 100000;
double meters = (int)(convertedCentimeters / 100);
convertedCentimeters /= 100;
It will print 10km and 0.0 meters and 0.10050200000000001 centimeters.
I've tried without casting and km is wrong, tried to put everything as int and still wrong. I will really appreciate the help, I need to win this one. If you can lead me to the solution and not tell me it directly that will be great.
The major thing missing from your answer is use of the modulus, which you need to correctly answer your question. Consider the following working script:
int centimeters = 1005020;
int kilometers = centimeters / 100000;
int meters = (centimeters % 10000) / 100;
int centimetersFinal = centimeters % 100;
Given that you want to report whole numbers for each unit, I recommend starting off and working with integers everywhere. This also makes the arithmetic much easier.
The kilometer value is obtained by just taking the floor of the centimeter amount converted to kilometers. In this case, we get 10km, what you expect, but we don't include the remainder, because that goes to the meter and centimeter components.
The meter value takes the mod 10000 to isolate only the components that are strictly less than one kilometer. Then, we divide by 100 to remove the centimeter component.
Finally, the centimeter component is just the remainder when dividing the original amount by 100.

Trying to multiply within the public static void. Any help is appreciated

So, for one of my homework pieces I have to make a Body Mass Index. When I asked my teacher about how to do math within the public void main, he explained that I could just do it in the void main. But when I try It gives me "The Operator * is undefined for the arguments type(s): String, Int".
Here's the code and Instructions:
(Instructions)
Create a new Java project named Your_Name_BMI. Create a class named BMI and write a program using JOptionPane dialog boxes that calculates and displays a person’s body mass index (BMI). The BMI is often used to determine whether a person with a sedentary lifestyle is overweight or under-weight for his or her height. A person’s BMI is calculated with the following formula:BMI = (weight*703) /(height2) Where weight is measured in pounds and height is measured in inches. The program should display messages to the user asking for their weight and height and store the values in appropriately named variables. After making the calculations the program should display a message indicating whether the person has optimal weight, is underweight, or is overweight. A sedentary person’s weight is considered optimal if his or her BMI is between 18.5 and 25. If the BMI is less than 18.5, the person is considered underweight. If the BMI value is greater than 25, the person is considered overweight.
import javax.swing.JOptionPane;
public class Doswell_BMI
{
//declaring important things
static String weight;
static String height;
static int multi;
static int multi2;
static String diagnosis;
static int bmi;
public static void main(String[] args)
{
weight= JOptionPane.showInputDialog("What is your weight?");
height= JOptionPane.showInputDialog("What is your height?");
multi = 703;
multi2 = 2;
bmi = weight * multi / height * multi2;
bmi = Integer.parseInt(diagnosis);
}
}
Yes, you can not multiply Strings as they are so you need to convert to an Integer first
int w = Integer.valueOf (weight);
String cannot be multiply, try this:
bmi = Integer.valueOf(weight) * multi / Integer.valueOf(height) * multi2;
I would advise against using ints to calculate BMI. The equation for calculating BMI in pounds and inches is as follows:
If you’re 5’5” (65”) in height and 150lbs in weight, you would calculate your BMI as follows:
(150lbs / (65 inches²)) x 703 = 24.96.
150 / 65*65 = 0.03550295858 <- This is the reason you want to be using a data type such as double.
weight= JOptionPane.showInputDialog("What is your weight?");
height= JOptionPane.showInputDialog("What is your height?");
These two statements return String values.
You cannot perform mathematical operations to string variables in JAVA.
Hence, you have to convert them to Integer using
either,
Integer.parseInt(weight)
this will convert the string into the primitive type int
or
Integer.valueOf(weight)
this will convert the string into an object of the wrapper class Integer
bmi = weight * multi / height * multi2;
This multiplication is not very accurate as your requirement above is to first multiply the two sections separately and then divide
It is better if you write this as bmi = (weight * multi) / (height * multi2)
so the final statement will be bmi = (weight.Integer.parseInt(weight) * multi) / (height.Integer.parseInt(height) * multi2)

Imperial to kg converter

An exercise on my problem worksheet asks us to write a method public static double imperialToKg(double ton, double once, double drachm, double grain) that converts masses given in the imperial system to kg.
We've been given a conversion table for this but what I don't understand, being completely new to java, is HOW can I get my method to differentiate between these input arguments?
For example if I want the method to return the kg value of 11 stone what's to stop it from returning the value of 11 tons (tons being the first argument)
public class W1_E2{
public static double imperialToKg(double ton, double hundredweight, double quarter, double stone, double pound, double once, double drachm, double grain){
ton = 1016.04691;
hundredweight = 50.8023454;
quarter = 12.7005864;
stone = 6.35029318;
ounce = 0.02834952;
drachm = 0.00177185;
grain = 0.0000648;
}
}
I've listed the conversions as variables but I don't know what to do with them...
For 11 stone, you would have to call that like:
returnedFoo = imperialToKg(0,0,0,11,0,0,0);
If you want to call it with a value of 11 tons, you use:
returnedFoo = imperialToKg(11,0,0,0,0,0,0);
For our stone example, try:
On the implementation end, you would use something like:
public static double imperialToKg(double ton, double hundredweight, double quarter, double stone, double pound, double once, double drachm, double grain){
{
double kg = (ton * 1016.04691) + (hundredweight * 50.8023454) + (quarter * 12.7005864) + (stone * 6.35029318) + (ounce * 0.02834952) + (drachm * 0.00177185) + (grain * 0.0000648);
return kg;
}
This is quick and dirty; there is a multitude of better ways to do this, please confirm that the exercise is actually requesting we call the function like this.
Nowhere does it state that you require one method to make all your conversions, but that you require a main method to test your code.
So, make an individual method for each type of conversion required, as an example:
public static double tonToKg(double val){
return val * 1016.04691;
}
To test:
public static void main(String[] args){
System.out.println(tonToKg(11));
}

Why in this Java program the Doubles in a String Output have too many decimals?

In a solution to an exercise in the Book Art and Science of Java I had to write a program that converts Kilograms into the corresponding values in Pounds and Ounces.
I wrote the program but when I try to convert say 1kg, the result the program gives me is:
1 kg = 2 pounds and 3.200000000000006 ounces
Now my constants are 2.2 pounds per kg and 16 ounces per pound so 3.2 ounces is correct. But not with so many 0's and that 6 at the end freaks me out.
Anyone know why this happens and how it can be solved? Thank you!
Here's the code:
/*
* File: KgsLibras.java
* Program that converts kilograms in pounds and ounces.
*/
import acm.program.*;
public class KgsLibras extends ConsoleProgram {
public void run () {
println ("This program will convert kilograms in pounds and ounces");
double kgs = readDouble ("Insert kgs value: ");
double libras = kgs * LIBRAS_POR_KG;
double oncas = (libras - (int)libras) * ONCAS_POR_LIBRA;
println ((int)libras + " libras" + " e " + oncas + " Onças.");
}
private static final double LIBRAS_POR_KG = 2.2;
private static final int ONCAS_POR_LIBRA = 16;
}
That's just a consequence of how floating point works - literally thousands of other references to these issues here on SO alone. The short version is that not all numbers can be represented exactly using floating point numbers, which leads to oddities like the one you're seeing. This document should teach you all you should know about floating point.
In the mean time you can use format to get printf-like formatting options:
System.out.format ("%.0f libras e %.2f Onças.\n",libras,oncas);
or if you have to use that specific println method, use String's format:
println(String.format ("%.0f libras e %.2f Onças.",libras,oncas) );
You can do something like this:
String libras = String.format("$%.2f", VALUE); //For example..
Then, printing libras will suits your needs.
Regarding of your question about Why your program prints it that way, #fvu was faster than me :)

Categories

Resources