Calling toCelsius method in java - java

This Question is from my programming class:
In the convertFToC method, change the second System.out.println statement so it produces a display such as
212.0 degrees Fahrenheit is 100.0 degrees Celsius
for an input of 212. If you are baffled by this instruction, here is a fuller description:
The first half of the output line ( 212 degrees Fahrenheit is ) is already written. The next item to be displayed is
the number of degrees celsius, which is being calculated and returned by the toCelsius method.
Remember (see Lecture 3 and preparation exercises) that the result of a return method can be used elsewhere in
a program by calling its name and providing the correct number and type of input parameters.
Call the toCelsius method within the System.out.println statement, sending it the data that it needs (the variable representing the degrees in fahrenheit).
Finish off the statement by concatenating the string " degrees Celsius" on the end.
This program should now compile. If you run it, it will convert one value from Fahrenheit to Celsius.
The code is below, can someone show me how to call the to toCelsius method. thanks
import java.util.Scanner;
/**Lab 4 COMP160 2020
* Starting code*/
public class FahrenheitToCelsius{
public static void main(String[]args){
convertFToC();
convertFToC();
convertFToC();
//Step 5;
}
/**gets input from user representing fahrenheit and displays celsius equivalent*/
public static void convertFToC(){
Scanner scan = new Scanner(System.in);
System.out.println("Enter Fahrenhei temperature: ");
double fahrenheit = scan.nextDouble(); //Step 2 - assign next double input from Scanner object
System.out.println(fahrenheit + " degrees Fahrenheit is " + + " degrees Celsius"); //Step 4
}
/**calculates and returns the celsius equivalent of a double input parameter called fahr*/
public static double toCelsius(double fahr){
int BASE = 32;
double CONVERSION_FACTOR = 9.0/ 5.0;
double celsius = CONVERSION_FACTOR + BASE / fahr;//Step 3
return celsius;
}
}// end class

Add toCelsius(fahrenheit) between those two consecutive +s. And also correct the conversion formula in the method

Related

how to run 2 connected classes in java on cmd? [duplicate]

This question already has answers here:
Getting error "cannot find or load main class HelloWorld"
(3 answers)
Closed 6 years ago.
So I need to write a program in java that takes 2 user inputed temperatures in celsius and converts it to Fahrenheit and kelvin. i wrote the code and it works in eclipse but my teacher strictly said it has to work in cmd. it compiles fine but when i go to run it it states could not find or load main class temperatureTester (name of the class with my main). This is my first post so if you need more info please ask and i'm looking for any ideas why this is happening. below is my code for the question.
import java.util.Scanner;
public class temperatureTester{
public static void main (String[]args){
//create 2 objects connecting to temperatureC
temperatureC firstValue = new temperatureC();
temperatureC secondValue = new temperatureC();
// initialize scanner
Scanner stdin = new Scanner (System.in);
//initialize variables
double firstC = 0;
double secondC = 0;
//prompt user for both values
System.out.print("Please enter initial temperatures: ");
firstC = stdin.nextDouble();
secondC = stdin.nextDouble();
//call object set methods and pass entered values as arguments
firstValue.setC(firstC);
secondValue.setC(secondC);
//display the values for the values for different temp. units
System.out.println("1) The current temperature in Celcius is: " + firstValue.getC());
System.out.println("1) The current temperature in fahreinheit is: " + firstValue.getF());
System.out.println("1) The current temperature in kelvin is: " + firstValue.getK());
System.out.println("---------------------------------------------------------------");
System.out.println("2) The current temperature in Celcius is: " + secondValue.getC());
System.out.println("2) The current temperature in fahreinheit is: " + secondValue.getF());
System.out.println("2) The current temperature in kelvin is: " + secondValue.getK());
this is the second class
public class temperatureC{
private double C;
/**
The setC method stores the value in the C field
# param initialC the value stored in C
*/
public void setC(double initialC){
C = initialC;
}
/**
The getC returns the C value and also sets a lower limit,
if a number below is entered it sets it ti the limit.
#Return the value of the C
*/
public double getC(){
if(C < -273.15){
C = -273.15;
}
return C;
}
/**
the getF method calculates and returns a value for C in fahrenheit
#return the computed for C in fahrenheit
*/
public double getF(){
return C * 1.8 + 32;
}
/**
The getK method computes and returns a value for temperature C in kelvin
#return the computed Kelvin value
*/
public double getK(){
return C + 273.15;
}
}
The Best approach might b that you export your project as executable jar file to achieve this have a look on following official ecclipse link http://help.eclipse.org/neon/index.jsp?topic=%2Forg.eclipse.jdt.doc.user%2Ftasks%2Ftasks-37.htm
then next part you need to run it from Command line this is a fun part just change the directory to the path where your jar file is located and then here comes the following command
java -jar yourJar.jar
pause
and then it will b executing like a charm!
Simply compile your both files in cmd using javac
After successfully compiling simply run your main class i.e temperatureTester class using java. It successfully executed.

Rounding a number with printf in java?

i am trying to use System.out.printf to round a very large number to 2 decimal places. This is the code i am using:
System.out.printf(" %1.2f = overpayment:$" + overpayment);
I am getting this error:
Exception in thread "main" java.util.MissingFormatArgumentException: Format specifier '%1.2f'
at java.util.Formatter.format(Unknown Source)
at java.io.PrintStream.format(Unknown Source)
I am under the impression that %f is the format specifier and %1.2f is used for a floating point number with 2 digits after the decimal.
I am trying to round 4.4260494195128784E-4 to 4.43. Thank you
Since I am getting under a cent for my overpayment, I think i have the wrong formula to calculate it. Does anyone have an idea on how to attain overpayment of a loan? The overpayment value should be 4.43. Here is my code:
import java.util.Scanner;
public class CreditCardPayoff {
public static void main(String[] args) {
// TODO Auto-generated method stub
double principle;
double annualInterestRate;
double monthlyPayment;
double numerator;
double denominator;
double monthsToPayOff;
double monthsToPayOffCeiled;
double totalAmountPaid;
double totalInterestPaid;
double overpayment;
Scanner keyboard = new Scanner(System.in);
principle = keyboard.nextDouble();
annualInterestRate = keyboard.nextDouble();
monthlyPayment = keyboard.nextDouble();
numerator = Math.log(monthlyPayment) - Math.log(monthlyPayment-
(annualInterestRate / 1200.00) * principle);
denominator = Math.log((annualInterestRate/1200.00) + 1.0);
monthsToPayOff = numerator/denominator;
monthsToPayOffCeiled = Math.ceil(monthsToPayOff);
totalAmountPaid = monthsToPayOffCeiled * monthlyPayment;
totalInterestPaid = totalAmountPaid - principle;
overpayment = (monthsToPayOffCeiled - monthsToPayOff)/monthlyPayment;
System.out.println("Principle:" + principle);
System.out.println("Annual Interest Rate:" + annualInterestRate);
System.out.println("Monthly Payment:" + monthlyPayment);
System.out.println("Months Needed To Pay Off:" + (int)monthsToPayOffCeiled);
System.out.println("Total Amount Paid: $" + totalAmountPaid);
System.out.println("Total Interest Paid: $" + totalInterestPaid);
System.out.printf("overpayment: $%1.2f ", overpayment);
}
}
My method to calculate overpayment, obtain difference between monthsToPayOff and monthsToPayOffCeil (ceiling) then divide by monthly payment. This got me 4.4260494195128784E-4.
In order to use String.format you do not concatenate the values for the placeholders with the format string, but rather pass them as parameters:
System.out.printf("overpayment: $%1.2f", overpayment);
printf takes one argument for every format specifier (see documentation). In Java arguments are separated by commas (,).
So, in your example, instead of a + that concatenate two strings (a string and a number into a string, to be precise), you should use a comma:
System.out.printf(" %1.2f = overpayment:$", overpayment);
That is not how you use printf.
System.out.printf("%1.2f and %d", 1.25f, 1000);
Knowing this, you can also add extra formatting:
printf( "$%.2f", overpayed );
Inside of the format string you can specify your data types, and then each one is passed as an argument thereafter.

Invalid Character Constant in Java?

Here is my code:
import java.util.Scanner;
import javax.swing.JOptionPane;
import java.text.DecimalFormat;
/*
Medium Speed
Air 1100 feet per second
Water 4900 feet per second
Steel 16,400 feet per second
Write a program that asks the user to enter "air", "water", or "steel", and the distance that a sound wave will
travel in the medium. The program should then display the amount of time it will take.
You can calculate the amount of time it takes sound to travel in air with the following formula:
Time = Distance / 1100
You can calculate the amount of time it takes sound to travel in water with the following formula:
Time = Distance / 4900
You can calculate the amount of time it takes sound to travel in steel with the following formula:
Time = Distance / 16400
*/
public class SpeedOfSound
{
public static void main(String[] args)
{
String input;
char timeTraveled;
Scanner keyboard = new Scanner(System.in);
double distance;
double time;
double time2;
double time3;
time = (distance/ 1100);
time2 = (distance/ 4900);
time3 = (distance/ 16400);
DecimalFormat formatter = new DecimalFormat("#0.00");
System.out.println("Enter air, water, or steel: ");
input = keyboard.nextLine();
System.out.print("Enter distance: ");
distance = keyboard.nextDouble();
switch(timeTraveled)
{
case 'air':
System.out.printf("The total time traveled is " + formatter.format(time) + ".");
break;
case "water":
System.out.printf("The total time traveled is " + formatter.format(time2) + ".");
break;
case "steel":
System.out.printf("The total time traveled is " + formatter.format(time3) + "seconds.");
timeTraveled = input.charAt(0);
break;
keyboard.close();
}
} // main()
} // class SpeedOfSound
Why is case 'air': giving me the error invalid character constant twice? My professor has a different example for a different program and it's almost the same as what I'm doing but he doesn't get the error. Why do I get this error?
You've got several problems here.
First, single quotes are reserved for single characters, like 'a'. Whole strings need to be placed in double quotes.
Second, timeTraveled is never assigned anything anyway by the time you use it, so it "might" not have been initialized by the time you try to run it (and get things to compile). You probably want to use input instead.
This is to say, as long as you're using Java 7 or newer, you should write this as your switch argument:
switch(input) {
// statements to follow
}
I'm not sure what that assignment at the end of your "steel" case is meant to do, but you may want to move its logic out of the switch statement entirely.
In some programming languages, single quotes (') and double quotes (") are interchangeable. In Java (and also in C and C++), they are not.
If you want to specify a multi-character string literal, use double quotes: "air".
Additionally, it is not clear what do expect to happen when you compare a char (timeTraveled) to a string ("air").
I dont understand the logic of this program. If U need to enter the word and then do something depending on it try to make something like
String timeTraveled;
if (timeTraveled.equals("air")){
//do something
} else if (timeTraveled.equals("water")) {
//do something
} ...
I found multiple issue in your code:
It should be "air" not 'air' (solution for your op).
Datatype of timeTraveled is char but you are trying to match it with String (like "air", "water", etc.).
timeTraveled is not initialized.
distance is not initialized while doing calculation for time, time1 & time2.
keyboard.close(); is unreachable code. Move it outside the switch block or add it in default case.
Ideally, you should be using chars in your switch case or create enum for better clarity.
#justaregularguy - You are getting this error because you have taken air as a character.
mention air as String and you will be fine.
This will help you to - in case you will try non permitted values.
"Cannot switch on a value of type Float. Only convertible int values, strings or enum variables are permitted"
'air' is using single quotes. Single quotes denote a character constant. What you're looking for is "air", a String constant.
You seem to be a new programmer. I made some improvements to your program, and I'll show you them here:
import java.util.Scanner;
import javax.swing.JOptionPane;
import java.text.DecimalFormat;
/*
Medium Speed
Air 1100 feet per second
Water 4900 feet per second
Steel 16,400 feet per second
Write a program that asks the user to enter "air", "water", or "steel", and the distance that a sound wave will
travel in the medium. The program should then display the amount of time it will take.
You can calculate the amount of time it takes sound to travel in air with the following formula:
Time = Distance / 1100
You can calculate the amount of time it takes sound to travel in water with the following formula:
Time = Distance / 4900
You can calculate the amount of time it takes sound to travel in steel with the following formula:
Time = Distance / 16400
*/
public class SpeedOfSound {
public static void main(String[] args) {
char timeTraveled; //what is this even doing here?
Scanner scanner = new Scanner(System.in);
double time = (distance/ 1100);
double time2 = (distance/ 4900);
double time3 = (distance/ 16400);
DecimalFormat formatter = new DecimalFormat("#0.00");
System.out.println("Enter air, water, or steel: ");
String material = scanner.nextLine();
System.out.print("Enter distance: ");
double distance = scanner.nextDouble();
switch (material) {
case "air":
System.out.printf("The total time traveled is " + formatter.format(time) + ".");
break;
case "water":
System.out.printf("The total time traveled is " + formatter.format(time2) + ".");
break;
case "steel":
System.out.printf("The total time traveled is " + formatter.format(time3) + "seconds.");
timeTraveled = material.charAt(0); //what is this even doing here?
break;
}
scanner.close();
} // main()
} // class SpeedOfSound
Made the spacing and indenting more consistent
Renamed your Scanner object. "keyboard" is not an appropriate name for a Scanner object, since scanner works with not only keyboard input, but also string and file input.
I combined the declaration of your "time" variables and the definition
E.g.
double time; //a declaration of "time"
time = (distance/ 1100); //a definition of "time"
//becomes:
double time = (distance/ 1100); //a declaration AND definition of "time"
changed 'air' to "air"", also, changed the switch case variable to "material" (which used to be called "input", and is the string that holds the user's input), rather than it using timeTraveled (some miscellaneous character?)
Since your program is only going to be displaying one time of the three possibilities, why calculate all 3? I suggest you rework your algorithm as follows:
Ask the user for the material and distance they want. Set a variable "speed" equal to 1100, 4900, or 16400 depending on the user's choice of air, water or steel. Then, calculate time as distance / speed.
This saves you from repeating 3 identical System.out.println() statements, saves you from having 3 time variables (when you only need 1),

(double,int) cannot be applied to (double)

Been wracking my brain for hours trying to figure this out.
i have the main method which is:
public static void main(String [] args)
{
double payRate;
double grossPay;
double netPay;
int hours;
Scanner input = new Scanner(System.in);
System.out.println("Welcome to the Pay Roll Program");
printDescription();
System.out.print("Please input the pay per hour: ");
payRate = input.nextDouble();
System.out.println("\nPlease input the pay per hour: ");
hours = input.nextInt();
System.out.println("\n");
netPay = computePaycheck(netPay);
System.out.println("The net pay is $" + (netPay));
System.out.println("We hope you enjoyed this program");
System.exit(0);
and the method that calculated the netPay
public static double computePaycheck(double payRate, int hours)
{
double grossPay = computePaycheck(payRate*hours);
double netPay = (grossPay - (grossPay *.15));
return netPay;
}
But I'm getting the error "computePaycheck(double,int) in PayCheck cannot be applied to (double)"
I sort of understand this, but I can't for the life of me figure out a remedy.
1) You are calling a function with 2 parameters while only passing 1. That will cause a compilation error.
2) When you call computePaycheck from within itself that will loop and cause a stack overflow.
netPay = computePaycheck(netPay);
public static double computePaycheck(double payRate, int hours)
"computePaycheck(double,int) in PayCheck cannot be applied to (double)"
Your method takes two parameters, a double and an int.
You can only call it with those two (you are missing the number of hours in the call).
netPay = computePaycheck(payRate, hours);
double grossPay = payRate*hours;
In your computePaycheck method, you have the following line:
double grossPay = computePaycheck(payRate*hours);
This is passing one parameter (the product of payRate and hours) to the computePaycheck function, which requires two parameters. It looks like you meant to say:
double grossPay = computePaycheck(payRate, hours);
But you will need to be careful! This will cause your program to recur infinitely! You will need to determine how to calculate the gross pay without calling this function, since if you do call it recursively within itself, there is no condition from which it will return.
Your method takes two parameters -- double payRate and int hours, but you are only specifying a double when you call computePaycheck in your main method.
It's not clear what you intend to happen, but the mismatched parameters should let you know what is wrong with your program.
The first statement of your computePaycheck method calls computePaycheck with a single parameter (a double) whereas the computePaycheck takes 2 parameters (a double and an int). That is why your code fails to compile.
If you "fix" this by using double grossPay = computePaycheck(payRate, hours); instead, this will compile BUT you will get infinite recursion! Don't you simply want to do double grossPay = payRate*hours; ?
It's clear that you set 2 parameters but from the main class you are only calling just one parameter. You should find a way to call the 2 parameters at the same time.

Error: celsius cannot be resolved to a variable

Getting error with the following code:
import java.util.Scanner;
public class FahrenheitToCelsius{
public static void main(String[]args){
convertFToC();
}
/*gets input representing fahrenheit and displays celsius equivalent*/
public static void convertFToC(){
Scanner scan = new Scanner(System.in);
System.out.println("Enter Fahrenheit temperature");
double fahrenheit = scan.nextInt();
System.out.println(fahrenheit + " degrees Fahrenheit is " +
fMethod(celsius) + " degrees Celsius");
}
/* calculates and returns the celsius equivalent */
public static double toCelsius(double fahr){
int BASE = 32;
double CONVERSION_FACTOR = 9.0/ 5.0;
double celsius = ((fahr-BASE)/(CONVERSION_FACTOR));
return celsius;
}
}
I get the following:
Error: celsius cannot be resolved to a variable
I need to use fMethod to call the toCelsius in the System.out.println however i keep getting this error.
You haven't shown fMethod at all, but it looks like you just want:
System.out.println(fahrenheit + " degrees Fahrenheit is " + toCelsius(fahrenheit)
+ " degrees Celsius");
You can't use celsius in main because it's a local variable in the toCelsius method. Instead, you need to call that method and use the return value.
System.out.println(fahrenheit + " degrees Fahrenheit is " + fMethod(celsius) + " degrees Celsius"); //Step 4
should probably read
System.out.println(fahrenheit + " degrees Fahrenheit is " + toCelsius(fahrenheit) + " degrees Celsius"); //Step 4
You call fMethod which doesn't exist and pass the value of celsius when I think you meant fahrenheit.
The variable celsius is local to toCelsius() and is therefore not resolvable inside convertFToC().
You need to call your toCelsius(double fahr) method, like this:
System.out.println(fahrenheit + " degrees Fahrenheit is " + toCelsius(fahrenheit) + " degrees Celsius"); // Step 4
in the method convertFToC()
You get the fahrenheit from the user and call fMethod(celsius)
You were supposed to call fMethod(farenheit)
More important:
If you read the compiler error message, you get not just the error, but the file name and the line number. If you go to the line number, you see a celcius variable out of nowhere.
This is easy. I know asking on SO is easier, but you will never learn to read error messages and solve problems this way.
Learn to read and understand error messages. They are there for a reason.
On a line marked step4 you have an undeclared variable named celsius. Should be fahrenheit perhaps?
You are using celsius here:
System.out.println(fahrenheit + " degrees Fahrenheit is " + fMethod(celsius) + " degrees Celsius");
However, you did declare celsius only in toCelsius and that's out of scope.

Categories