Syntax error in Celsius-to-Fahrenheit converter program - java

I have to allow the user to choose which conversion to do, and what degree to start at, then print the conversion starting at that degree up to the next 9 (10 conversions). And I have to write this using a callback function. Also there is a menu in the beginning. I have an "else without if" at line . Also my callback function is not calculating numbers correctly. How do I resolve this error and fix my callback function?
import java.util.Scanner;
public class FahrToCel {
public static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
double choice = 0;
double fahrenheit = 0;
double celsius = 0;
double answer = 0;
//print the welcome message and the menu options for the user
System.out.printf("Welcome to Candace's Fahrenheit and Celsius "
+ "convertor. ");
System.out.printf("Please choose one of the following options: \n"
+ " Press 0 to exit \n Press 1 to to convert to Celsius \n"
+ " Press 2 to convert to Fahrenheit > ");
choice = input.nextInt();
//print what happens when the user hits a button
if (choice == 0){
// the user is going to exit the game
System.out.printf("Well hopefully you can play again soon! :) ");
} else {
//perform code for the operation
for ( double i = fahrenheit; i >-100; i-=10 ){
if (choice == 1) {
// it will convert from fahrenheit to celsius
System.out.printf("Please pick a number in Fahrenheit: > ");
fahrenheit = input.nextDouble();
celsius = FahrToCel();
System.out.printf("%f ", i);
}
}
for ( double i = celsius; i >-10; i-=10 ){
if (choice == 2){
// it will convert from celsius to fahrenheit
System.out.printf("Please pick a number in celsius: > ");
celsius = input.nextDouble();
fahrenheit = CelToFahr();
System.out.printf("%f ", i);
}
}
} else {
System.out.printf("I'm sorry, I did not ask you to enter that "
+ "number. ");
}
}
public static double CelToFahr(){
double celsius = 0;
double fahrenheit = 0;
celsius = (fahrenheit - 32) * (5.0/9.0);
return celsius;
}
public static double FahrToCel( ){
//perform the conversion for fahrenheit to celsius
double celsius = 0;
double fahrenheit = 0;
fahrenheit = ((9.0/5.0) + 32) * celsius;
return fahrenheit;
}
}

You are looking for a structure like this
if (choice == 0){
// ...
}
else if (choice == 1) {
for ( double i = fahrenheit; i >-100; i-=10 ){
// ...
}
}
else if (choice == 2) {
for ( double i = celsius; i >-10; i-=10 ){
// ...
}
}
else {
// ...
}
Right now you have some if statements inside of an else and your scope is getting confused. Your loops would then go inside those else if statements. Also note that you are doing the conversion many times, but printing the initial value entered each time, not the converted temperature.

Among other things, (EDIT) ONE OF your functions is not quite right. Since they involve math, I'm offering my revisions instead of hints.
I don't know if you want to pass in the value you're converting from, but doing so would make it better.
You definitely don't want to set both celsius and fahrenheit to zero in both functions.
public static double FahrToCel(double fahrenheit ){
double celsius;
celsius = (fahrenheit - 32) * (5.0/9.0);
return celsius;
}
public static double CelToFahr( double celsius){
//perform the conversion for fahrenheit to celsius
double fahrenheit;
fahrenheit = ((9.0/5.0) ) * celsius + 32;
return fahrenheit;
This would mean that inside your for loops, the calls to the functions would have to be something like:
celsius = input.nextDouble();
fahrenheit = CelToFahr(celsius);
But I'm not sure you should input the next value of celsius, if I'm reading the instructions and intent of the for loops correctly.
Maybe you want this instead of inputting:
celsius = i;

Related

Java throwing exception for "No line found" when attempting to gather input from Scanner object

I am fairly new to Java and am attempting to build a "Top 10 Java Projects for Beginners" project, more specifically, a temperature converter. My code throws the following error:
Exception in thread "main" java.util.NoSuchElementException: No line found
at java.base/java.util.Scanner.nextLine(Scanner.java:1651)
at TempConvert.convertToFar(TempConvert.java:78)
at TempConvert.main(TempConvert.java:15)
I was originally using the scanner "*.nextDouble()" method to grab the double but changed it to the "parseDouble" method as I thought this was perhaps the issue. Alas, this has not helped. Any help resolving this would be greatly appreciated!
public static double convertToFar()
{
Scanner in = new Scanner(System.in);
String userEntry;
double formula, userDouble;
System.out.print("Enter degrees in Celsius: ");
userEntry = in.nextLine();
userDouble = Double.parseDouble(userEntry);
in.close();
formula = (userDouble - 32) * (5/9);
return formula;
}
I think that the in.nextLine() in the methods you wrote eventually collided with the string that was inputted by the user before the input stream had been closed.
I created one Scanner object and sent it to the methods so that they will be able to use that same object. I close it only when the program ends once the user enters 'E'. It worked for me:
import java.util.*;
public class TempConvert {
public static void main(String[] args)
{
double far, cel;
char userChoice;
Scanner in = new Scanner(System.in); // I added this line
userChoice = displayMenu(in);
while (userChoice != 'E')
{
if (userChoice == 'F')
{
far = convertToFar(in);
System.out.println("Converted: " + far + "\u00B0");
userChoice = displayMenu(in);
}
else if (userChoice == 'C')
{
cel = convertToCel(in);
System.out.println("Converted: " + cel + "\u00B0");
userChoice = displayMenu(in);
}
else
{
System.out.println("Invalid Entry");
userChoice = displayMenu(in);
}
}
in.close(); // closing the input stream when the program ends
}
public static void displayTitle()
{
String title = "||---- TEMPERATURE CONVERTER ----||";
String one = "-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-";
String two = "|| ** Auth: Arranic ||";
String three = "|| ||";
System.out.println(one + "\n" + three + "\n" + title + "\n" + three + "\n" + two + "\n" + three + "\n" + one);
}
public static char displayMenu(Scanner input)
{
ClearScreen();
displayTitle();
System.out.println("\n");
String choiceString;
char choice;
System.out.println("F - FARENHEIGHT C - CELSIUS E - EXIT");
System.out.print("CONVERT TO: ");
choiceString = input.nextLine();
// input.close() --> removed this line
choice = Character.toUpperCase(choiceString.charAt(0));
return choice;
}
public static void ClearScreen()
{
System.out.print("\033[H\033[2J");
System.out.flush();
}
public static double convertToCel(Scanner in)
{
String userEntry;
double formula, userDouble;
System.out.print("Enter degrees in Fahrenheit: ");
userEntry = in.nextLine();
// in.close() --> removed this line
userDouble = Double.parseDouble(userEntry);
formula = (userDouble - 32) * (5.0/9);
return formula;
}
public static double convertToFar(Scanner in)
{
String userEntry;
double userDouble, formula;
System.out.print("Enter degrees in Celsius: ");
userEntry = in.nextLine();
// in.close() --> removed this line
userDouble = Double.parseDouble(userEntry);
formula = (userDouble * (9.0/5)) + 32;
return formula;
}
}
BTW your calculations are not precise. You should remember that integer/integer = integer. That said, writing 5/9 or 9/5 is not accurate, since the result is an integer type number, and not a double type number, as I assume you wanted to get. (5/9 = 0, 9/5 = 1) So you should have added a 5.0 or 9.0 to the calculations so that Java would understand that you want to get a double type result (double/int = double).
And one more thing, your calculations where misplaced (fahrenheit to celsius gave me the opposite result and vice versa) so I switched them up ;).

How do I add an working if to my code? - Java

I'm building this weird BMI/BMR calculator for school and right now the code does what I want it to do. But I need to add an if (I think) that makes sure that the user doesn't type in values that are too small or too big. The user is only allowed to type in "vikt" between 0.5 and 2.2. If the user types in a faulty value I need the program to execute an else that prints out a "nope you did it wrong".
My problem is that I do not know where to put the if so that the code still works.
So my question is, where and how do I add an if to my code?
public static void main(String[] args) {
Scanner input = new Scanner (System.in);
// Ledtext
System.out.println("Beräkna ditt BMI");
System.out.print("Tryck j för att starta: " );
char fortsätt = input.next().charAt(0);
System.out.println(" ");
do
{
//Användaren matar in sin data
System.out.print("Ange personens vikt (kg): ");
double vikt = input.nextDouble();
System.out.print("Ange personens längd (m): ");
double längd = input.nextDouble();
System.out.print("Ange personens ålder: ");
double ålder = input.nextDouble();
System.out.println(" ");
System.out.println("Beräknat BMI för både män och kvinnor är " + bmi(vikt, längd));
System.out.println("Beräknat BMR för män är: " + kalorier_Män(vikt, längd, ålder));
System.out.println("Beräknat BMR för kvinnor är: "+ kalorier_Kvinnor(vikt, längd, ålder));
System.out.println(" ");
System.out.print("Fortsätta? (j/n): ");
fortsätt = input.next().charAt(0);
}
while (fortsätt != 'n');
}
static double bmi(double vikt, double längd){
double bmiMänochKvinnor;
bmiMänochKvinnor = (1.3 * vikt) / Math.pow(längd, 2.5);
return bmiMänochKvinnor;
}
static double kalorier_Män (double vikt,double längd,double ålder){
double manBmr;
manBmr = (9.99 * vikt) + (6.25 * längd) - (4.92 * ålder) + 5;
return manBmr;
}
static double kalorier_Kvinnor (double vikt,double längd,double ålder){
double kvinnaBmr;
kvinnaBmr = (9.99 * vikt) + (6.25 * längd) - (4.92 * ålder) - 161;
return kvinnaBmr;
}
}
From my understanding you want to constrain the values the user can use as an input for this line:
double vikt = input.nextDouble();
You can simply do this by adding an if statement right after that where you check the entered value. If the value doesn't match the condition, you can send a message and continue the loop.
if (vikt < 0.5 || vikt > 2.2) {
// send some message
continue;
}
You can check the values directly after they are read, with an if else statement like this:
if(vikt > 2.2 || vikt < 0.5){
System.out.println("nope you did it wrong");
return; // this will stop the code
}
A better way of handling this problem would be the following function:
private static double retrieveValue(Scanner input, double min, double max, String requestMessage){
while(true){
System.out.println(requestMessage);
double measure = input.nextDouble();
if (measure >= min && measure <= max){
return measure;
} else{
System.out.println("This values is not allowed, please try again:");
}
}
}
You can call it like this:
double vikt = retrieveValue(input, 0.5, 2.2, "Ange personens vikt (kg):");

For loop calculates the Celsius equivalent to Fahrenheit Temperatures Java

I have a problem with this program. I get no compile errors, but when I run it didn’t display the decimal point for Celsius output.
Here is my code:
public class TempLoops {
public static void main(String args[]) {
int fahrenheit = 0;
System.out.println("Fahrenheit Celsius");
for ( fahrenheit = 0; fahrenheit <= 300; fahrenheit+= 20) {
System.out.printf("%5d ",fahrenheit);
double Celsius = (fahrenheit-32.0) * (5.0/9.0); // formula for celsius to fahrenheit conversion
System.out.printf("%5d", (int)Celsius );
System.out.println();
}
}
}
How do I get digits behind the decimal point for Celsius output?
Here is the sample output for what it suppose to look like
sample out
Change this
System.out.printf("%5d", (int)Celsius );
to this
System.out.printf("%0.2f", Celsius );
This will print centigrades with 2 decimal places.
The main reason why you are getting integer output is because you are casting float(ing point number like x.abcd) into integer number, cutting of what is left as fracture part (resulting in x alone).
Use DecimalFormat to solve your problem.
Working Code :
import java.text.DecimalFormat;
public class TempLoops {
public static void main(String args[]) {
DecimalFormat f = new DecimalFormat("##.00"); // this will helps you to always keeps in two decimal places
int fahrenheit = 0;
System.out.println("Fahrenheit Celsius");
for ( fahrenheit = 0; fahrenheit <= 300; fahrenheit+= 20) {
System.out.printf(" "+fahrenheit);
double Celsius = (fahrenheit-32.0) * (5.0/9.0); // formula for celsius to fahrenheit conversion
System.out.printf("\t\t"+f.format(Celsius));
System.out.println();
}
}
}
Kindly refer to Java Docs for more information about DecimalFormat

Temperature Calculator for Java

I am receiving errors during compilation. It's expecting a .class. I don't think it should require one. I'm pretty new at coding so forgive my ignorance. I also would like some guidance on how to nullify Case when the user inputs C or F so they can put c or f and not get an error messages.
This is my code:
import java.util.Scanner;
import java.util.InputMismatchException;
public class TempCALC
{
public static void main(String[] args)
{
System.out.println("This Program will allow the user to calculate temperature.");
calculateTemp();
}
private static void calculateTemp() {
int F;
int C;
F=0;
C=1;
Scanner input = new Scanner (System.in);
System.out.println("Please enter a F to convert Fahrenheit to Celsius.");
System.out.println("Please enter a C to convert Celsius to Fahrenheit.");
int option = input.nextInt();
if (int=0) {
System.out.println("Please enter a temperature in degrees Fahrenheit.");
ftoc();
} else if (int= 1) {
System.out.println("Please enter a temperature in degrees Celsius.");
ctof();
} else {
System.out.println("ERROR PLEASE ENTER A F OR A C TO PROCEED!");
}
}
private static void ftoc() {
Scanner input = new Scanner(System.in);
Double celsius = input.nextDouble();
System.out.println(celsius + "celsius is" + ((celsius * 9 / 5.0) + 32) + "Fahrenheite");
calculatetemp();
}
private static void ctof() {
Scanner input = new Scanner(System.in);
Double Fahrenheit = input.nextDouble();
System.out.println(Fahrenheit + "Fahrenheit is" + ((Fahrenheit - 32) * (5 / 9.0)) + "Celsius");
calculatetemp();
}
private static void print(String string); {
System.out.println("\n" + string);
}
}
if (int=0)
This is not valid Java syntax. int is a type not a variable. You meant to write:
if(option == 0)
Notice the == (comparison) instead of = (assignment).
This is the flow you meant to implement:
if (option == 0) {
System.out.println("Please enter a temperature in degrees Fahrenheit.");
ftoc();
} else if (option == 1) {
System.out.println("Please enter a temperature in degrees Celsius.");
ctof();
} else {
System.out.println("ERROR PLEASE ENTER A F OR A C TO PROCEED!");
}
If you wish for the user to enter f or c instead to mention the degrees, you will need to use:
String option = input.next();
To get a String instead of an Integer.
And then:
if (option.equals('F') { ... }
else if(option.equals('C') { ... }
else { ... }
If you want your input to be case-insensitive take a look at toLowerCase or toUpperCase and apply it to your needs (there is an answer here that shows its use).
int is reserved key word in java you can not used it with expression to compare,you should use his value like this:
int option = input.nextInt();
if (option ==0) {
Not if (int=0) { and = is used to assign but == is used to check equality.
You first have to check the validation in your ifs statements, as the previous answers mentioned.
Also, I think that your actual conversion formulas are swapped.
Then, in order to receive either 'C' or 'c':
Read a String, instead of an int:
String option = input.next();
And then convert all the input to lowercase:
if (option.toLowerCase().equals("f"))
Here is the complete example:
public class TempCALC {
public static void main(String[] args) {
System.out.println("This Program will allow the user to calculate temperature.");
calculateTemp();
}
private static void calculateTemp() {
Scanner input = new Scanner(System.in);
System.out.println("Please enter a F to convert Fahrenheit to Celsius.");
System.out.println("Please enter a C to convert Celsius to Fahrenheit.");
String option = input.next();
if (option.toLowerCase().equals("f")){
System.out.println("Please enter a temperature in degrees Fahrenheit.");
ftoc();
}else if (option.toLowerCase().equals("c")){
System.out.println("Please enter a temperature in degrees Celsius.");
ctof();
}else{
System.out.println("ERROR PLEASE ENTER A F OR A C TO PROCEED!");
}
}
private static void ftoc() {
Scanner input = new Scanner(System.in);
Double celsius = input.nextDouble();
System.out.println(celsius + "celsius is" + ((celsius * 9 / 5.0) + 32) + "Fahrenheite");
calculatetemp();
}
private static void ctof() {
Scanner input = new Scanner(System.in);
Double Fahrenheit = input.nextDouble();
System.out.println(Fahrenheit + "Fahrenheit is" + ((Fahrenheit - 32) * (5 / 9.0)) + "Celsius");
calculatetemp();
}
private static void print(String string){
System.out.println("\n" + string);
}
private static void calculatetemp(){
System.out.println("\nInside calculateTemp");
}
}

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);
}

Categories

Resources