I'm getting weird loop behaviour after passing char instead int - java

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.

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

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.

Java: Missing return statement for a math quiz?

New to Java. The task is to Create a MathQuiz application that asks the user whether they would like a simple or difficult math quiz and the number of questions they would like to answer. The application then displays the questions, one at a time,prompting the user for the answer and confirming whether or not the answer is correct. The MathQuiz application should include separate methods for the simple and difficult math quiz.The simple() method should display addition problems. The difficult() method should display multiplication problems. Random numbers should be generated for the quiz questions. This is what I have so far:
import java.util.Scanner;
public class MathQuiz {
public static double simple() {
int randomNumber1 = (int)(20 * Math.random()) + 1;
int randomNumber2 = (int)(20 * Math.random()) + 1;
int randomNumberAdd = randomNumber1 + randomNumber2;
//user input
Scanner keyboard = new Scanner(System.in);
System.out.print(randomNumber1 + " + " + randomNumber2 + " = ");
int GuessRandomNumberAdd = keyboard.nextInt();
if (GuessRandomNumberAdd == randomNumber1 + randomNumber2) {
System.out.println("Correct!");
}else {
System.out.println("Wrong. The correct answer is " + randomNumberAdd);
}
}
public static double difficult() {
int randomNumber1 = (int)(20 * Math.random()) + 1;
int randomNumber2 = (int)(20 * Math.random()) + 1;
int randomNumberMul = randomNumber1 * randomNumber2;
int correct = 0;
//user input
Scanner keyboard = new Scanner(System.in);
System.out.print(randomNumber1 + " * " + randomNumber2 + " = ");
int GuessRandomNumberMul = keyboard.nextInt();
if (GuessRandomNumberMul == randomNumber1 * randomNumber2) {
System.out.println("Correct!");
}else{
System.out.println("Wrong. The correct answer is " + randomNumberMul);
}
}
//user options
public static void main(String[] args) {
int choice;
Scanner input = new Scanner(System.in);
System.out.println("There are two levels available:");
System.out.println("1. Simple");
System.out.println("2. Difficult");
System.out.print("Enter your choice: ");
choice = input.nextInt();
if (choice == 1) {
simple();
} else if (choice == 2) {
difficult();
}
input.close();
}
}
public static double simple() {}
public -> It specifies the access level of this function.
static -> It means this function is a behavior of your class and not specific to any instance of this class.
double -> It's what your function returns, a double typed value here, as an output at end of execution.
simple()-> It's your function name
In both of your functions simple() and difficult() you are not returning any value as output. So you have to change it to void.
Change your method simple() and difficult() return type from double to void and the error should go away
Change the return type of simple() and double() method to void, i.e.
public static void simple() and
public static void difficult()
The return type of these methods is currently double, so it is expected to return a double value. If they don't return a double value, the compiler will give you an error. So, if you don't plan to return a value in your methods, change the return type to void.
Removing the return type of double from your method's signature and setting it to void, the error should go away.
public static void simple() {
// your code
}
public static void difficult() {
// your code
}

Formatting java text with void method

I have looked and cant find the information I am looking for. My code is functioning as I expect it to but I have one bit of code that I would like to improve.
The problem is that I can not call a void method within a print statement like this:
System.out.print("Water is a " + printTemp(temperature) + " at" + temperature + " degrees.";
printTemp(temperature is a void method so this won't work, as a result I found a work-around but it is not ideal:
System.out.print("\nWater is a ");
printTemp(temperature);
System.out.print(" at");
System.out.printf(" %.0f", temperature);
System.out.print(" degrees.\n");
here is the full code:
import java.util.Scanner;
public class printTemp {
public static void main(String[]args) {
Scanner input = new Scanner(System.in);
System.out.print("Please enter the temperature: ");
Double temperature = input.nextDouble();
// takes the state of the water from the printTemp method and
// the temperature to return a formatted output to the user
System.out.print("\nWater is a ");
printTemp(temperature);
System.out.print(" at");
System.out.printf(" %.0f", temperature);
System.out.print(" degrees.\n");
}
public static void printTemp(double temperature) {
String returnMessage = "null" ;
if (temperature < 32 )
returnMessage = "solid";
else if (temperature > 212)
returnMessage = "gas";
else
returnMessage = "liquid";
System.out.printf(returnMessage);
}
}
This is for school thus there are conditions that must remain, printTemp MUST be a void method and the variable temp must remain a DOUBLE.
What about to put the following code snippet
...
System.out.print("Water is a " + returnMessage + " at" + temperature + " degrees.");
to the printTemp method as the last line? Then in the main outputs nothing and you just write:
...
printTemp(input.nextDouble());
Use a class variable to hold the Temperature String word and use the void method to set it.
public class PrintTemp {
private static String TempStr = "";
public static void main(String[]args) {
[...]
printTemp(temperature);
System.out.print("Water is a " + TempStr + " at" + temperature + " degrees.");
}
public static void printTemp(double temperature) {
if (temperature < 32 )
TempStr = "solid";
else if (temperature > 212)
TempStr = "gas";
else
TempStr = "liquid";
}
}
Sorry for the delay guys!
Here is the solution.
import java.util.Scanner;
public class printTemp {
public static void main(String[]args) {
//Read in the temperature from the user
Scanner input = new Scanner(System.in);
System.out.print("\nPlease enter the temperature: ");
//Call and insert the input into the printTemp method.
printTemp(input.nextDouble());
}
public static void printTemp(double temperature) {
//Decide whether the water is in a soild, liquid or gaseous sate.
String returnMessage = "null";
if (temperature < 32 )
returnMessage = "solid";
else if (temperature > 212)
returnMessage = "gas";
else
returnMessage = "liquid";
//Print to the user.
System.out.print("\nWater is a " + returnMessage);
System.out.printf(" at %.0f degrees.%n\n", temperature);
}
}
UPDATE
public class PrintTemp {
public static void main(String[] args) {
double temperature = 35;
StringBuilder returnMessage = new StringBuilder();
printTemp(temperature, returnMessage);
System.out.print("Water is a " + returnMessage + " at " + temperature + " degrees.");
}
public static void printTemp(double temperature, StringBuilder returnMessage) {
if (temperature < 32)
returnMessage.append("solid");
else if (temperature > 212)
returnMessage.append("gas");
else
returnMessage.append("liquid");
}
}
This is the easiest way to have printTemp modify the message without actually returning it and without using additional classes / beans.
But this does work only for objects (not primitive type) and amongst objects it does not work for Strings because in Java they are treated as a special case. (That is why I had to use a StringBuilder, StringBuffer would work too)

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

Categories

Resources