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.
Related
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
so im still new to java programming and for this program i need to make a program that calculates change for a vending machine. It is based of a 5 cent increment between a value of 25 cents to a dollar. for this assignment if i use a loop to force the user to input a value in bounds i get extra credit, since i originally was going to scratch because i wasnt getting it but soon did im back to using it. only thing is for one of my conditions it creates an infinite loop of the output message and im not sure why. any advice would be appreciated
/** Carmine A
The purpose of this program is to calculate the change to be dispensed from
a vending machine */
//import scanner so user can input data
import java.util.Scanner;
public class lab2Test{
//declaration of variables to be used in program
float changeGiven;
public static void main(String args[]) {
//ties user input variable to class so scanner can use it
int userInput;
int itemCost;
//initiates the keyboard to be used
Scanner keyboard = new Scanner(System.in);
//print statement to tell user how to enter price
System.out.println("Enter price of item from 25 cents to a dollar in 5-cent increments \n"
+ "Do not enter a decimal point");
//user inputs value to be set to variable
userInput= keyboard.nextInt();
//System.out.println("You entered ." +userInput + " as the price");
//while loop to make sure input stays in bounds
while(userInput<25 || userInput>100){
System.out.println("Invalid amount entered! \n"
+ "Please enter an amount between 25 cents and 1 dollar");
while(userInput>25 && userInput<100){
System.out.println("Price is in bounds");
System.out.println("Please enter a valid amount between 25-100");
itemCost=keyboard.nextInt();
}
}
itemCost=userInput;
//print out item cost based off users input
System.out.println("You enetered: " + itemCost +" as the items cost");
}
}
update
ok took what you guys said and made this
//while loop to make sure input stays in bounds
while(userInput<25 || userInput>100){
System.out.println("Invalid amount entered! \n"
+ "Please enter an amount between 25 cents and 1 dollar");
userInput=keyboard.nextInt();
}
thanks for the help! knew it was something dumb, but this is why i ask for help so i can learn
so i believe it is frowned upon if i made another thread for the same program so i will add to this one.
i have completed just about everything i need but am having a few issues.
1. for some reason after i compile and run my code "Change Due:" prints twice, i am unsure why since i only have it once in a print statement but i can be missing it.
2.i need to print out in a money format and for some reason i have tried different formatting options and none will round (i have a feeling it is but it is not displaying because of the second "Change due:" printing) but can be wrong
3. on line 55 i am receiving this message and not sure why C:\Users\finst\Desktop\Intro to Java\Labs\Lab2\lab2Test.java:55: error: incompatible types: possible lossy conversion from double to int
changeRemainder= (changeDue*(double)100);
this is what i currently have:
/** Carmine
The purpose of this program is to calculate the change to be dispensed from
a vending machine */
//import scanner so user can input data
import java.util.Scanner;
public class lab2Test{
//declaration of variables to be used in program
public static void main(String args[]) {
//ties user input variable to class so scanner can use it
double userInput;
double itemCost;
//initiates the keyboard to be used
Scanner keyboard = new Scanner(System.in);
//print statement to tell user how to enter price
System.out.println("Enter price of item from 25 cents to a dollar in
5-cent increments");
//user inputs value to be set to variable
userInput= keyboard.nextDouble();
//while loop to make sure input stays in bounds
while(userInput<(.25) || userInput>(1.00)){
System.out.println("Invalid amount entered! \n"
+ "Please enter an amount between 25 cents and 1
dollar");
userInput=keyboard.nextDouble();
}
//print out item cost based off users input
System.out.println("You entered: " + userInput +" as the items cost");
System.out.println("You entered a dollar to pay with");
//algorithm to calculate change due
int quarters;
int nickels;
int dimes;
int pennies;
int changeRemainder;
double changeDue;
double dollar=1;
//calculates change due
changeDue= (dollar - userInput);
//System.out.printf("%.2f" + "\n" ,changeDue);
//System.out.println("Change due:" + changeDue);
//makes the remainder into a number that can be used
changeRemainder= (changeDue*(double)100);
//calculates the amount of each coin needed to make the change
quarters= (changeRemainder / 25);
changeRemainder= changeRemainder % 25;
dimes= (changeRemainder/10);
changeRemainder= changeRemainder%10;
nickels=(changeRemainder/5);
changeRemainder= changeRemainder%5;
pennies=(changeRemainder);
//output statement to print coin amounts
System.out.println("Quarters: " + quarters);
System.out.println("Dimes: " + dimes);
System.out.println("Nickels: " + nickels);
System.out.println("Pennies: " + pennies);
}
}
As userInput is never updated in the loop then its value does not change and it will potentially loop for ever.
Maybe you mean userInput=keyboard.nextInt(); but you do not need two loops anyway.
userInput=keyboard.nextInt();
while (userInput<25 || userInput>100) {
System.out.println("Invalid amount entered! \n"
+ "Please enter an amount between 25 cents and 1 dollar");
userInput=keyboard.nextInt();
}
You don't need 2 while loops; just one will do. In any case, your while loop checks the 'userInput' variable, but that never changes in the while loop; you are updating the itemCost variable instead.
I would use a Boolean for your while loop, and create an if else statement within this to check for valid entry and calculate the change. Hope this helps!
boolean end = true;
while (end) {
//retrieve user input of cost and assign value to variable
//create an if statement check if the value is valid
if(itemCost >=25 && itemCost <=100){
//retrieve user input for change entered
//calculate change for the user and display it
//end loop
end = false;
} else {
//invalid entry
end = false;
}
}
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.
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.
total in this case is 500. Trying to make a calculator, but not everything's adding up. It seems to skip the multiplication and just display total*amount. Is there something I'm doing wrong? EDIT: Discount: in the example, .92. I get 455000 if amount is 1000.
if (wShipping==true){
if (GroundShipping.isSelected()){
if (amount<=99) {
shipping=1.05;
output.setText(output.getText() + amount + "\t" + total*1.05*amount*discount + "\n");
}
else{
output.setText(output.getText() + amount + "\t" + total*amount*discount + "\n");
}
}
if (AirShipping.isSelected()){
shipping=1.1;
output.setText(output.getText() + amount + "\t" + total*amount*1.1*discount + "\n");
}
if (FedexShipping.isSelected()){
shipping=1.25;
output.setText(output.getText() + amount + "\t" + (total*amount*discount)*(1.25) + "\n");
}
}
You should consider the following things--
1) Why is the variable shipping needed if you are directly using the value in the set statement
2) Use else if statement since all the options are exclusive
3) You might want to check the initial values for variables and the formula for calculating the price. Taking the initial values as given, the lowest possible price is-
Price = 1000*500*0.92 = 460000 (total x amount x discount)
Hence there must be something amiss with your initial values
Maybe, just maybe is the first rule of currency calculations:
why not use double or float to represent currency