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)
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 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'm writing a function to take a turn in Blackjack. It looks like this:
public void takeTurn(Deck deck) {
Scanner reader = new Scanner(System.in);
String response = "y";
while (response.toLowerCase().equals("y")) {
System.out.print("Would you like another card? (Y or N) ");
response = reader.nextLine();
if (response.toLowerCase().equals("y")) {
hand.getCards().add(deck.getTopCard());
System.out.println("Current hand: " + hand);
if (hand.getValue() > 21) {
System.out.println("You busted with " + hand.getValue());
break;
}
}
}
}
The weird thing is that when I enter "n", it doesn't draw another card but it does re-prompt me. So then I threw in a printLine statement, as follows:
public void takeTurn(Deck deck) {
Scanner reader = new Scanner(System.in);
String response = "y";
while (response.toLowerCase().equals("y")) {
System.out.println("response is " + response);
System.out.print("Would you like another card? (Y or N) ");
response = reader.nextLine();
if (response.toLowerCase().equals("y")) {
hand.getCards().add(deck.getTopCard());
System.out.println("Current hand: " + hand);
if (hand.getValue() > 21) {
System.out.println("You busted with " + hand.getValue());
break;
}
}
}
}
And here's a sample interaction:
response is y
Would you like another card? (Y or N) n
response is y
Would you like another card? (Y or N)
The first "response is y" makes sense. The second I can't explain.
Any ideas?
public static void main(String[] args) {
takeTurn(new Scanner(System.in)); // just an example how you share a single Scanner as a parameter when calling takeTurn function
}
public static void takeTurn(Scanner sc/*, Deck deck*/) { // static may be removed if you do not use the function within static main void
if (isYResponse(sc, "Would you like another card? (Y or N) ")) {
System.out.println("response is y");
/*
hand.getCards().add(deck.getTopCard());
System.out.println("Current hand: " + hand);
if (hand.getValue() > 21) {
System.out.println("You busted with " + hand.getValue());
}
*/
} else {
System.out.println("response is n");
}
takeTurn(sc/*, deck.next()*/); // be careful with this loop: define when it stops actually... when isGameOver(), for example?
}
private static boolean isYResponse(Scanner sc, String message) { // static may be removed if you do not use the function within static main void
System.out.print(message);
String response;
if ((response = sc.nextLine()).isEmpty()) {
response = sc.nextLine();
}
return ("y".compareToIgnoreCase(response) == 0)
? true
: (("n".compareToIgnoreCase(response) == 0)
? false
: isYResponse(sc, message));
}
P.S. I'm sorry: I don't know the structure of other classes, like Deck, for example. I just hope my answer can help you find the final concrete solution you need if you think that way.
I'm getting an error at the 2nd class c.getResponse
The method getResponse(String) is undefined for the type BotTest
If anyone wants to see what the assignment was heres the pdf:
http://www.cs.stonybrook.edu/~tashbook/fall2013/cse110/project-1.pdf
import java.util.*;
public class ChatBot {
public String getResponse(String input) {
int i = 0;
int found = input.indexOf("you", i);
if (found == -1)
return "I'm not important. Let's talk about you instead.";
int x = longestWord(input).length();
if (x <= 3) {
return "Maybe we should move on. Is there anything else you would like to talk about?";
}
if (x == 4) {
return "Tell me more about" + " " + longestWord(input);
}
if (x == 5) {
return "Why do you think" + " " + longestWord(input) + " "
+ "is important?";
} else if (x > 5) {
return "Now we are getting somewhere. How does" + " "
+ longestWord(input) + " " + "affect you the most";
}
else
return "I don't understand";
}
private String longestWord(String input) {
String word, longestWord = "";
Scanner turtles = new Scanner(input);
while (turtles.hasNext()) {
word = turtles.next();
if (word.length() > longestWord.length())
longestWord = word;
}
return longestWord;
}
}
Second Class to test the code
import java.util.*;
public class BotTest {
public static void main(String[] args) {
Scanner newturtles = new Scanner(System.in);
System.out.println("What would you like to talk about?");
String input = newturtles.nextLine();
BotTest c = new BotTest();
while (!input.toUpperCase().equals("GOODBYE")) {
System.out.println(c.getResponse(input));
input = newturtles.nextLine();
}
}
}
getResponse is defined for ChatBot not BotTest
ChatBot c = new ChatBot();
The Class BotTest indeed does NOT have the .getResponse(String) function. ChatBot does though.
import java.util.Scanner;
public class cat{
public static void main(String args[]){
System.out.print("Enter a command = ");
double balance = 0;
String a;
//scanner input
Scanner in = new Scanner(System.in);
String command = in.nextLine();
while (in.hasNext()){
if (command.equals("penny")){
balance = balance + 0.01;
System.out.println("balance = " + balance);
}
if (command.equals("nickel")){
balance = balance + 0.05;
System.out.println("balance = " + balance);
}
else {
System.out.println("return" + balance + "to customer");
break;
}
balance++;
}
}
}
I'm trying to create an infinite loop that keeps reading new commands for a vending machine , that may halt only under certain condition - when the input is "return", it prints the current balance in the string "return $XX to customer". (otherwise it keeps adding/subtracting cash to the current balance).
First, I cannot seem to get the if and else part integrated together since both the string commands ("return ~ to customer "& "balance =") appears when I write 'penny'.
Second problem is that my intended infinite command loops just becomes a flow of infinite numbers in my terminal and I can't seem to figure out why.
Don'y know if it's what you're searching to do, but this loops unitil you send the break command:
import java.util.Scanner;
public class cat {
public static void main(String args[]) {
System.out.print("Enter a command = ");
double balance = 0;
String a;
// scanner input
Scanner in = new Scanner(System.in);
while (in.hasNext()) {
String command = in.nextLine();
if (command.equals("penny")) {
balance = balance + 0.01;
System.out.println("balance = " + balance);
} else if (command.equals("nickel")) {
balance = balance + 0.05;
System.out.println("balance = " + balance);
} else if (command.equals("break")) {
break;
} else {
System.out.println("return " + balance + " to customer");
}
balance++;
}
}
}
To fix your broken 'if' add yet another else:
else if (command.equals("nickel")){
With java7 you can use switch:
switch(command) {
case "nickel":
....
break;
case "penny":
.....
break;
default:
.....;
}