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");
}
}
Related
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 ;).
I'm new to Java. I am tasked with creating a menu program, one option is to generate a username in the form of first initial and surname.
The method is stringOperation(String f, String s)
Variables are fName and sName.
Here is the code. I have highlighted the areas I need help with. The rest of the code is OK, I think. This is a section of the pseudocode that explains what is required:
stringOperation(String f, String s)
3.1.1 Assign first character of first initial to variable using f.substring(start position, length of string).
3.1.2 Concatenate first initial with users surname.
3.1.3 print username to console.
import java.util.Scanner; // imports scanner class
public class Assessment {
public static void main(String[] args) { //main method
menu(); //call menu method
}
public static void menu() { //method to display menu options
int choice;
String fName;
String sName;
Scanner sc = new Scanner(System.in);
//displays menu options
System.out.println("Welcome");
System.out.println("1. Username");
System.out.println("2. Factorial");
System.out.println("3. Area of triangle");
System.out.println("4. Circumference of circle");
System.out.println("5. Exit");
//asks for user input
do {
System.out.println("Enter your first name");
fName = sc.next();
System.out.println("Enter your surname");
sName = sc.next();
System.out.println("Thank you. Now enter a selection (1-5):");
choice = sc.nextInt();
//menu loop
switch (choice) {
case 1:
**stringOperation(String fName, String sName);**
break;
case 2:
numberFactorial();
break;
case 3:
areaTriangle();
break;
case 4:
circumferenceCircle();
break;
}
}while (choice!=5);
}
**//stringOperation method
private static void stringOperation(String f, String s) {
String initial = f.substring(0,1);
String username = initial + s;
System.out.println("Your username is " + initial + s);
}**
public static void numberFactorial() { //method to calculate factorial of a number
//variables
int number;
int factorial = 1;
int i;
//input
Scanner sc = new Scanner(System.in);
System.out.println("Please enter a number: ");
number = sc.nextInt();
//for loop
for (i = 1; i <= number; i++) {
factorial = factorial * i;
}
System.out.println("Factorial of " + number + " is " + factorial);
}
public static void areaTriangle ()//method to calculate area of a triangle
{ //input
Scanner sc = new Scanner(System.in);
//variables
double width;
double height;
double area;
//input
System.out.println("Enter the width: ");
width = sc.nextInt();
System.out.println("Enter height: ");
height = sc.nextInt();
area = (height * width) / 2;
System.out.println("The area is :" + area);
}
public static void circumferenceCircle ()//method to calculate circumference of a circle
{ //variables
double radius;
double circumference;
Scanner sc = new Scanner(System.in);
System.out.println("Enter radius: ");
radius = sc.nextDouble();
circumference = Math.PI * 2 * radius;
System.out.println("The circumference is : " + circumference);
}
}
If you want to make the method cleaner you could do something like this
private static void stringOperation(String f, String s) {
System.out.println("Your username is " + f.substring(0,1) + s)
}
If you need to refer back to the new username then have a global variable that your method can set to refer to later like this.
private static void stringOperation(String f, String s) {
Assessment.username = f.substring(0,1) + s;
System.out.println("Your username is " + Assessment.username);
}
I'm working on a JavaRush Course problem - <Fahrenheit/Celsius Converter>:
Ask user direction of conversion
Ask user a temperature
Convert and print out result temperature
I'm trying to break program on a separate methods to understand how to work with methods and how to pass variables (I'm beginner in programing)
this is my code:
import java.util.Scanner;
public class FahrenheitCelsius {
private static final Scanner sc = new Scanner(System.in);
public static void main(String[] args) {
System.out.println("---< Fahrenheit / Celsius Converter >---");
String direction = getDirection();
int temperature = getTemperature(direction);
getResult(direction, temperature);
sc.close();
}
// let's get direction of conversion from user input
static String getDirection() {
String direction;
do {
System.out.print("Convert from F or C: ");
direction = sc.nextLine();
} while (!direction.equals("F") && !direction.equals("C"));
return direction;
}
// let's get temperature from user
static int getTemperature(String direction) {
int temperature;
System.out.print("temperature in " + direction + ": ");
while (!sc.hasNextInt()) {
System.out.print("temperature in " + direction + ": ");
sc.nextLine();
}
temperature = sc.nextInt();
return temperature;
}
// let's convert Fahrenheit to Celsius
static int fahrenheitToCelsius(int temperatureF) {
return (temperatureF - 32) * 5 / 9;
}
// let's convert Celsius to Fahrenheit
static int celsiusToFahrenheit(int temperatureC) {
return temperatureC * 9 / 5 + 32;
}
// let's get result using direction and temperature we got
static void getResult(String direction, int temperature) {
int result;
if (direction.equals("F")) {
result = fahrenheitToCelsius(temperature);
System.out.println("result temperature: " + result + "C");
} else {
result = celsiusToFahrenheit(temperature);
System.out.println("result temperature: " + result + "F");
}
}
}
But!!!
I'm trying to write getTemperature method using do while loop.
Like this:
static int getTemperature(String direction) {
int temperature;
do {
System.out.print("temperature in " + direction + ": ");
sc.nextInt();
} while (!sc.hasNextInt());
temperature = sc.nextInt();
return temperature;
}
At first I used separate instances of Scanner inside each method. And I got noSuchElementExeption - if user unput characters
Then I got the idea that I dont have to close scanner in getDirection method.
Then I red some advices in Stackoverflow and created separate static final instance of Scanner and passed it into methods
And right now I'm getting - infinite loop if user types characters instead integers
I know that is some weird behaviour with Scanner and this nextLine() thing.
But can't get an idea how to make getTemperature using do while loop without this bug.
Thanks in advance guys.)
Your main() method might contain:
System.out.println("---< Fahrenheit / Celsius Converter >---");
String direction = "";
// Use of the String#matches() method with a small Regular Expression.
// (?i) Ignore Letter Case
// [FC] Only allow the character q, or Q
while (!direction.matches("(?i)[q]")) {
direction = getDirection();
if (!direction.matches("(?i)[q]")) {
int temperature = getTemperature(direction);
printResult(direction, temperature);
}
System.out.println();
}
The getDirection() method might look like:
// let's get direction of conversion from user input
public static String getDirection() {
String direction = "";
while (direction.isEmpty()) {
System.out.println("Enter temperature scale to convert:");
System.out.println(" F) Fahrenheit");
System.out.println(" C) Celsius");
System.out.println(" Q) Quit");
System.out.print("Your choice: --> ");
direction = sc.nextLine();
if (direction.equalsIgnoreCase("q")) {
System.out.println("\nBye-Bye\n");
break;
}
// Use of the String#matches() method with a small Regular Expression.
// (?i) Ignore Letter Case
// [FC] Only allow the characters F, f, C, or c (q is handled ahead of time)
if (!direction.matches("(?i)[FC]")) {
System.err.println("Invalid Temperature Scale Type (" + direction
+ ")! Must be F or C! Try again...\n");
direction = "";
}
}
return direction;
}
The getTemperature() method might look like:
// let's get temperature from user
private static int getTemperature(String direction) {
String temp = "";
// 'Ternary Operators' used here
String directString = (direction.equalsIgnoreCase("f") ? "Fahrenheit" : "Celsius");
String otherDirectString = (direction.equalsIgnoreCase("f") ? "Celsius" : "Fahrenheit");
System.out.println();
System.out.println("Convert a Temperature in " + directString + " to " + otherDirectString + ":");
do {
System.out.print("Enter a temperature in " + directString + ": --> ");
temp = sc.nextLine().trim();
// Since you're working with integer for temperature...
// Use of the String#matches() method with a small Regular Expression.
// ("\\d+") Must be a string representation of an Integer numerical
// value with 1 (or possibly) more digits.
if (!temp.matches("\\d+")) {
System.err.println("Invalid Temperature Supplied (" + temp + ")! Try Again..." );
temp = "";
}
} while (temp.isEmpty());
return Integer.valueOf(temp);
}
The getResult() name is changed to printResult() because that is all it is essentially doing. It's not really getting anything:
// let's get result using direction and temperature we got
static void printResult(String direction, int temperature) {
// 'Ternary Operator' used here
System.out.println("Converted temperature is : "
+ (direction.toUpperCase().equals("F")
? fahrenheitToCelsius(temperature) + "C"
: celsiusToFahrenheit(temperature) + "F"));
}
Other misc. methods remain the same:
// let's convert Fahrenheit to Celsius
public static int fahrenheitToCelsius(int temperatureF) {
return (temperatureF - 32) * 5 / 9;
}
// let's convert Celsius to Fahrenheit
public static int celsiusToFahrenheit(int temperatureC) {
return temperatureC * 9 / 5 + 32;
}
Read the comments in code. You will of course notice that there is use of the String#matches() method for validation along with various small Regular Expressions which are explained in the comments.
You will also notice the use of Ternary Operators to reduce the display of IF/ELSE statements.
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.
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.