How to invoke method from another - java

I'm trying to do temperature conversion and I know I need to invoke convertTemp in main, but I just don't know what I'm doing. Can someone take a look at this and help me out?
import java.util.Scanner;
public class TemperatureConverter {
public static void convertTemp() {
Scanner keyboard = new Scanner(System.in);
double temperature;
String temperatureScale = " ";
if (temperatureScale.equals("f"))
{
// code that converts from Fahrenheit to Celsius
temperature = (5/9)*(keyboard.nextDouble() - 32);
// and prints the result to the screen
System.out.println("The temperature is " + temperature + "degrees celsius");
}
//
else if (temperatureScale.equals("c"))
{
// code that converts from Celsius to Fahrenheit
temperature = 32.0 +(keyboard.nextDouble() * 1.8);
System.out.println("The temperature is " + temperature + "degrees fahrenheit");
// and prints the result to the screen
}
else
{
// code that outputs a message indicating that an incorrect
System.out.println("Error! A valid temperature was not chosen!");
// option was selected
}
}
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("What temeprature number are you trying to find out?");
double keyboardInput = keyboard.nextDouble();
System.out.println("Type f for Fahrenheit or c for Celsius.");
String keyboardTempLetter = keyboard.next();
}
}
//}

I would suggest instead of calling scanner in the convertTemp method, pass the character or string and the number in as an argument. then you'll just need to call the function in your main like this:
convertTemp(double keyboardInput, String keyboardTempLetter);

You need to send the user input to the method convertTemp so the method checks it then returns the result or prints it like you did .
Problem is you initialized temperatureScale and temperature in your method by adding
double temperature;
`String temperatureScale = " "; `
So the method used them instead of what the user inserted.
Second problem convertTemp method doesn't receive the userinput
convertTemp(NOTHING IS RECIVED HERE).
Third problem you didn't even send the input from main
So first your method should have:
convertTemp(String temperatureScale,double temperature)
Then remove the initialization of temperatureScale and temperature as I said above also remove
` Scanner keyboard = new Scanner(System.in);`
From convertTemp since you initialized it in main
Finally call the method in your main method this way :-
convertTemp(keyboardInputkeyboardInput,keyboardTempLetter);

Related

Is it possible to call a method using Scanner?

I am new to java, and I have just learned to use methods. I wrote a simple program to convert temperatures:
public class TempConversion {
double temperature;
public TempConversion() {
}
public double celsiusToKelvin(double celsiusTemp) {
temperature = celsiusTemp + 273.15;
System.out.println("Converted temperature: " + temperature);
return temperature;
}
public double celsiusToFahrenheit(double celsiusTemp) {
temperature = celsiusTemp * 9 / 5 + 32;
System.out.println("Converted temperature: " + temperature);
return temperature;
}
public double fahrenheitToCelsius(double fahrenheitTemp) {
temperature = (fahrenheitTemp - 32) * 5 / 9;
System.out.println("Converted temperature: " + temperature);
return temperature;
}
public double fahrenheitToKelvin(double fahrenheitTemp) {
temperature = (fahrenheitTemp + 459.67) * 5 / 9;
System.out.println("Converted temperature: " + temperature);
return temperature;
}
public double kelvinToCelsius(double kelvinTemp) {
temperature = kelvinTemp - 273.15;
System.out.println("Converted temperature: " + temperature);
return temperature;
}
public double kelvinToFahrenheit(double kelvinTemp) {
temperature = kelvinTemp * 9 / 5 - 459.67;
System.out.println("Converted temperature: " + temperature);
return temperature;
}
public static void main(String[] args) {
TempConversion temp = new TempConversion();
temp.celsiusToFahrenheit(38);
temp.celsiusToKelvin(0);
}
}
Right now, however, for the program to convert the temperatures, I have to call each method in the code itself. If I understood right, I can use a Scanner class to get user input, so how would I call one of methods while also using Scanner to get user input. I'm not sure if my question makes sense, but I can try clarifying if asked.
Perhaps It is not the best solution, but I think It is pretty graphic to explain the usefulness of the scanner function in Java.
Just copy and paste this into the main area of your code:
public static void main(String[] args) {
TempConversion temp = new TempConversion();
temp.celsiusToFahrenheit(38);
temp.celsiusToKelvin(0);
Double number;
String input;
String output;
Scanner sc = new Scanner(System.in);
System.out.println("Input a number, only double allowed");
number = sc.nextDouble();
sc.nextLine();
System.out
.println("Input the first letter of the source unit. c for celsius, f for fahrenheit or k for kelvin");
input = sc.nextLine();
System.out
.println("Input the first letter of the target unit. c for celsius, f for fahrenheit or k for kelvin");
output = sc.nextLine();
if (input.equals("c")) {
if (output.equals("k")) {
temp.celsiusToKelvin(number);
} else if (output.equals("f")) {
temp.celsiusToFahrenheit(number);
}
} else if (input.equals("f")) {
if (output.equals("c")) {
temp.fahrenheitToCelsius(number);
} else {
temp.fahrenheitToKelvin(number);
}
} else {
if (output.equals("c")) {
temp.kelvinToCelsius(number);
} else {
temp.kelvinToFahrenheit(number);
}
}
sc.close();
}
About how Scanner actually works It is very easy to find it out on the internet, but once you have declared a Scanner object there is no need to declare a new Scanner every time you want to save an input for something else, just as It has been done above, you can just re-use it many times you want.
Once you change from one object to another (in this problem is from keeping the double and now wwe want a String) you have to clear the buffer (there It is that sc.nextLine(); sentence).
And, after all this, remember to close the scanner. It is not mandatory, but if not, you will get a "warning" or something like that.

I need to make a celcius-fahrenheit converter with a tester class and allow the user user to choose whether to go from C to F or F to C

Could someone please explain to me how to make a program with a tester class with this code as its base that will help me do this?
//This program converts the user input from Celsius to Fahrenheit and vice versa
import java.io.*;
class Converter
{
// variables
String input;
double fahrenheit;
double celcius;
//constructor with 3 parameters to initialize the variables
Converter(String converterInput, double converterFahrenheit, double converterCelcius) throws IOException
{
InputStreamReader inStream = new InputStreamReader(System.in);
BufferedReader stdin = new BufferedReader(inStream);
input = converterInput;
fahrenheit = converterFahrenheit;
celcius = converterCelcius;
input = stdin.readLine();
fahrenheit = Double.parseDouble(input);
input = stdin.readLine();
celcius = Double.parseDouble(input);
}
// method
double fahrenheitConverter()
{
return fahrenheit = (9.0 / 5.0) * celcius + 32;
}
// method2
double celciusConverter()
{
return celcius = (5.0 / 9.0) * (fahrenheit - 32);
}
}
Sorry but this was a mess. :)
Or maybe I didnt had enough time to anticipate the way you wanted to do this.
Anyways I had to change the whole thing.I apologise for this.
Here is a code that works.
import java.io.*;
import java.util.Scanner;
final class Converter
{
// variables
double input;
double fahrenheit;
double celcius;
//constructor with 3 parameters to initialize the variables
Converter() throws IOException
{
//InputStreamReader inStream = new InputStreamReader(System.in);
String temp;
System.out.print("Please enter the temperature : ");
Scanner key=new Scanner(System.in);
input = key.nextDouble();
System.out.print("The number you gave is ");
fahrenheit=(fahrenheitConverter(input));
System.out.print(fahrenheit + " fahreneit degree , if u entered a celcious value.\n");
celcius=(celciusConverter(input));
System.out.print("Or it is "+ celcius + " celcius degree , if u entered a celcious value.\n");
}
// method
double fahrenheitConverter(double inp)
{
double iput=inp;
double fah;
fah = (iput*1.8)+ 32;
return fah;
}
// method2
double celciusConverter(double inp)
{
double iput=inp;
double cel;
cel=(iput-32)*0.5555;
return cel;
}
public static void main(String[] args) throws IOException {
Converter x=new Converter();
}
}
BUT this is only the code , in the proper (in my view) order.
Program needs to take two information items.Value and metric.
I mean that you have to ask user for the temperature (a double number) and
what is this number , celcius or fahre.
Also you will need some defence , throwing exceptions for ex. like input errors (ex user inputs like , 32,5 , a13 , 2')
Also , I used main() in order to use it compact and take the results easy.
You could have the class and call
public static void main(String[] args) throws IOException {
Converter x=new Converter();
}
from outside the class.
I will be happy to give any help beyond this.
You need to have the user specify which way they want to convert. The program doesn't do anything if the user tells the program what the Celsius and Fahrenheit temperatures already are, and you need to create methods to separately convert from Celsius to Fahrenheit and vice versa.

Create a program that prompt user fa a floating point(double) Fahrenheit and then return equal value in Celsius

import java.util.*;
class TempConver {
public static void main(String[] args) {
double temperature;
Scanner in = new Scanner(System.in);
System.out.printf("Enter Fahrenheit Temperature: ");
temperature = in.nextInt();
temperature = (temperature - 32) * 5 / 9;
System.out.printf("Censius Temperatre is = " + temperature);
}
}
I've to write program using information given below.
output formatting - "printf()" instead of print() or println()
Do While loops - repeat a question until a user gives you a valid response
Scanner.HasNextDouble() - method to ascertain whether or not the next item the scanner is about to read works as a double data type
Please help me how to write output in 2 place decimal using do while loop. !!
You have all the answers you need in the hints.
Do While loops - repeat a question until a user gives you a valid response And Scanner.hasNextDouble() - method to ascertain whether or not the next item the scanner is about to read works as a double data type
Here you are telling the user, while the input is not a double, then execute the code. Which will be asking the user for input until you get a double
while (!in.hasNextDouble()) {
// code here
}
To round to two decimals you can use Math.round() to round a value to the nearest integer, and multiply temperature by 100 then divide by 100.
int round = (int) Math.round(temperature*100);
temperature = round / 100.0;
Full code:
public static void main(String[] args) {
double temperature;
Scanner in = new Scanner(System.in);
System.out.printf("Enter Fahrenheit Temperature: ");
// As long as it is not a double ask for another input
while (!in.hasNextDouble()) {
System.out.printf("Please enter a valid number:");
in.next();
}
temperature = in.nextDouble();
temperature = (temperature - 32) * 5 / 9;
// Use only 2 decimals
int round = (int) Math.round(temperature*100);
temperature = round / 100.0;
System.out.printf("Censius Temperatre is = " + temperature);
}

Calling a method adding input

I'm having problems finding out how to get the output based on the user inputs for my Main class. I already have keyboard entry where the users can enter a value, which will be held. I'm guessing I will need to use that e.g. (input.input1());. However I also need to include the method which calculates the result e.g calculations.theAverageMassFfTheVehicle from the CalculatingRocketFlightProfile class, I'm just not sure how to combine the two to get the result.
//Calculations class
public class CalculatingRocketFlightProfile { //Calculation class
//Declaring fields
public double totalImpulse ;
public double averageImpulse;
public double timeEjectionChargeFires;
public double massEmptyVehicle;
public double engineMass;
public double fuelMass;
//Declaring variables for outputs
public double theAverageMassOfTheVehicle;
public double theVehiclesMaximumVelocity;
public CalculatingRocketFlightProfile(double totalImpulse, double averageImpulse, double timeEjectionChargeFires, double massEmptyVehicle,
double engineMass, double fuelMass) { //Constructor for this class
this.totalImpulse = totalImpulse;
this.averageImpulse = averageImpulse;
this.timeEjectionChargeFires = timeEjectionChargeFires;
this.massEmptyVehicle = massEmptyVehicle;
this.engineMass = engineMass;
this.fuelMass = fuelMass;
}
//Mutators and Accessors
//Accessors
//Methods for calculations - Calculating outputs, using inputs.
public double theAverageMassOfTheVehicle() {
return massEmptyVehicle + ((engineMass + (engineMass - fuelMass) )/ 2); //Formula to calculate Average mass
}//method
public double theVehiclesMaximumVelocity() { //Formula to calculate Maximum velocity
return totalImpulse / getTheAverageMassOfTheVehicle();
}//method
//Returns - GET
public double getTheAverageMassOfTheVehicle() {
return theAverageMassOfTheVehicle;
}//method
public double getTheVehiclesMaximumVelocity() {
return theVehiclesMaximumVelocity;
}//method
}//class
//Main class
public class Main { //Master class
public static void main( String args[] ) //Standard header for main method
{
kbentry input = new kbentry();
System.out.print("\nPlease enter a number for Total Impulse: " );
System.out.println("You have entered : " +input.input1());
System.out.print("\nPlease enter a number for Average Impulse: " );
System.out.println("You have entered : " +input.input2());
System.out.print("\nPlease enter a number for Time ejection charge fires: " );
System.out.println("You have entered : " +input.input3());
System.out.print("\nPlease enter a number for the Mass of the vehicle: " );
System.out.println("You have entered : " +input.input4());
System.out.print("\nPlease enter a number for the Mass of the engine: " );
System.out.println("You have entered : " +input.input5());
System.out.print("\nPlease enter a number for the Mass of the fuel: " );
System.out.println("You have entered : " +input.input6());
//Output
CalculatingRocketFlightProfile calculations = new CalculatingRocketFlightProfile();
System.out.println("\nThe average mass of the vehicle: " +calculations.theAverageMassOfTheVehicle() +
"\nThe vehicles maximum velocity: " + calculations.theVehiclesMaximumVelocity());
}
}
//kbentry
public class kbentry{
double input1(){
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
//Total Impulse entry
String strTotalImpulse = null; // These must be initialised
int intTotalImpulse = 0;
//System.out.print("Please enter a number for Total Impulse: ");
//System.out.flush();
// read string value from keyboard
try {
strTotalImpulse = in.readLine();
}
catch (IOException ioe) {
// ignore exception
}
// convert it to integer
try {
intTotalImpulse = Integer.parseInt(strTotalImpulse);
}
catch (NumberFormatException nfe) {
System.out.println("Error! Please enter a number!" + nfe.toString());
}
The problem is that you're CalcultingRocketFlightProfile class needs parameters, but you're creating calculations without passing any parameters to the new CalcultingRocketFlightProfile.
You should store those inputs in variables, then pass those variables to the constructor in your new CalcultingRocketFlightProfile that you declare.
Well, first off you are not actually passing any of your input to the Calculations class. I am not sure what input.input1() is or if you have an input class that you did not post. Either way you can do this a couple different ways.
First off give your input variables a meaningful name so you know which ones you are dealing with. Then pass all of your input.
CalculatingRocketFlightProfile calculations = new CalculatingRocketFlightProfile(input1, input2, etc..)
or
Place all your input variables into your calculations class. Then store user input as calculations.totalImpulse, etc... Then you call your calculation methods to display answers.
-EDIT-
Just have 2 classes, your main and calculations class. There is no need for another class just to handle keyboard input.
Example
Main class
public class Main {
public static void main( String args[] ) {
Scanner keyboard = new Scanner(System.in);
CalculatingRocketFlightProfile calculations = new CalculatingRocketFlightProfile();
System.out.print("\nPlease enter a number for Total Impulse: " );
calculations.totalImpulse = keyboard.nextDouble();
System.out.println("You have entered : " + calculations.totalImpulse);
}
}
public class CalculatingRocketFlightProfile { //Calculation class
//Declaring fields
public double totalImpulse ;
// Do all of your maths, and methods for answer return
}
You were not actually taking the keyboard input and assigning it to anything. Using a scanner object you can assign the input to a variable in your calculations class. If you do that for all of them, you dont actually need a constructor in your calculations class, you just use it to do all that math and return answers.

Problem with weight conversion program

import java.util.Scanner;
import java.text.DecimalFormat;
public class WeightConverter
{
private double numOfLbs2Conv, numOfKilos2Conv, converted2Pounds, converted2Kilograms;
private final double WEIGHT_CONVERSION_FACTOR = 2.20462262;
private int desiredDecimalPlaces;
private boolean toKilos, toPounds;
public void readPoundsAndConvert()
{
toKilos = true;
System.out.print("Enter the number of pounds to convert to "
+ "kilograms: ");
Scanner keyboard = new Scanner(System.in);
numOfLbs2Conv = keyboard.nextDouble();
converted2Pounds = numOfLbs2Conv / WEIGHT_CONVERSION_FACTOR;
}
public void readKilogramsAndConvert()
{
toPounds = true;
System.out.print("Enter the number of kilograms to convert to "
+ "pounds: ");
Scanner keyboard = new Scanner(System.in);
numOfKilos2Conv = keyboard.nextDouble();
converted2Kilograms = numOfKilos2Conv * WEIGHT_CONVERSION_FACTOR;
}
public void displayBothValues()
{
System.out.print("How many places after the decimal would you like? ");
Scanner keyboard = new Scanner(System.in);
desiredDecimalPlaces = keyboard.nextInt();
String decimalCounter = "0.";
for (int i = 0; i < desiredDecimalPlaces; i++)
{
decimalCounter = decimalCounter + "0";
}
DecimalFormat decimalsConverted = new DecimalFormat(decimalCounter);
if (toKilos)
{
System.out.println("The number of kilograms in "
+ decimalsConverted.format(numOfLbs2Conv) + " pounds is "
+ decimalsConverted.format(converted2Kilograms) + ".");
System.out.print("Press Enter to continue ... ");
System.out.println("");
keyboard.nextLine();
}
if (toPounds)
{
System.out.println("The number of pounds in "
+ decimalsConverted.format(numOfKilos2Conv) + " kilograms is "
+ decimalsConverted.format(converted2Pounds) + ".");
System.out.print("Press Enter to continue ... ");
System.out.println("");
keyboard.nextLine();
}
}
}
Hi all.I'm having trouble getting this together. The output is screwed. If the user converts to pounds (readPoundsAndConvert()) first, the output will say that the converted answer is 0. If the user convert kilograms first, the kilograms will convert properly and then for somereason the readPoundsAndConvert() method will be called an d behave properly. I have no clue why this is happening and have been spending hours on it. Can someone tell me how to get this to behave properly? If you need me to post the rest of the program, I will.
You're using your variables backwards... In readPoundsAndConvert() you're storing the converted value in converted2Pounds, but when you try to display it, you're reading from converted2Kilograms.
It looks like you're setting toKilos and toPounds to true in your two "convert" methods, but you aren't simultaneously setting the other to false. Thus, if you've called one of the convert methods before, when you call displayBothValues() both toKilos and toPounds will be true and both will be printed.

Categories

Resources