This is my code as of right now: http://ideone.com/PfXNQc
import java.util.Scanner;
public class Temperature
{
public static double convertFtoC(double F)
{
return (F-32)*5/9;
}
public static void main(String[] args)
{
double F; //Stores Farenheit
double C; //Stores Celsius
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter a temperature in Fahrenheit: "); //Enter in Farenheit
F = keyboard.nextDouble(); //Stores Farenheit
System.out.println("The temperature in Celsius is: " + convertFtoC(F)); //Displays Celsius (call convertFtoC(F) where celcuis conversion needed)
F = 0;
System.out.println("Fahrenheit\t Celsius");
while (F <= 100)
{
// Display the F and C in increments of 10.
System.out.println(F + "\t\t" + convertFtoC(F));
// Increment for the next day.
F++;
}
}
}
I would like the loop for conversions to go up in increments of 10 rather than by 1.
Right now it is outputting this:
But I would like it to be
0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100
what if you write as follows.
while (F <= 90) //Last number before 100 is 90
{
// Display the F and C in increments of 10.
System.out.println(F + "\t\t" + convertFtoC(F));
// Increment for the next day.
F=F+10;
}
Additionally,why you use capitals for variables, per conventions you should start variable names with lower case letters, objects names are started with capitals.
Modern Idiomatic Professional Approach
Q32835243.java
package com.stackoverflow;
import java.util.Scanner;
public class Q32835243
{
private static double farhenheitToCelsius(final double fahrenheit) {return (fahrenheit - 32) * 5 / 9;}
public static void main(final String[] args)
{
final Scanner keyboard = new Scanner(System.in);
System.out.print("Enter a temperature in Fahrenheit: ");
if (keyboard.hasNextDouble())
{
final double fahrenheit = keyboard.nextDouble();
final double celsius = farhenheitToCelsius(fahrenheit);
System.out.format("The temperature in Celsius is: %8.4f%n", celsius);
System.out.format("Fahrenheit\t Celsius%n");
for (int i=0; i < 100; i+=10)
{
System.out.format("%8.4f\t%8.4f%n", fahrenheit + i, farhenheitToCelsius(fahrenheit + i));
}
}
else
{
System.err.format("%s is not a double!%nPlease enter a double value.", keyboard.next());
System.exit(1);
}
}
}
Link to this solution as a fork of what you did.
I put this working code on ideone.com so you could easily see the differences and how to make this trival code bullet proof as possible.
Things to take note of in this solution:
Always make as many things final as possible. It eliminates two of the most common classes of program errors NullPointerException and side effects.
Always limit the scope of variable references and visibility of methods as much as possible. You want to define variables when you use them and make as many things private as you can.
Always name your variables in the context that you are using them so that you do not need to put comments explaining what they are.
Comments should only be in clean code when you are deviating from the expected. All your comments were useless tautology and violate the DRY principle as well. If things change now you have to update the code and the comments. More to maintain, easier to just name things that are self explanatory.
Using single letter variable names in short functions is fine. In the context of the block f and c would be acceptable names for fahrenheit and celsius if they were object references. But in the case of homework explicit is always better for communicating exactly what you are thinking.
Always follow the style guide when using lowerCamelCase and UpperCamelCase. Know when to use each in the correct context.
Always check your inputs and handle invalid data. Never try and fix it, if it is wrong stop the program, explain to the user where they went wrong and end the program. Defensive programming is terrible.
Always use the features of the different objects to your advantage. Use the String.format() and PrintStream.format() to eliminate formatting issues and making things more maintainable.
Learn to use the Scanner class correctly. the .hasNextXxx() methods are there for a reason, use them!
The scanner class has a terrible API and is the source of more frustration to use programmers than just about anything else.
For enhanced readability:
Don't use Capitalized identifiers for the variables as they are meant for the constants in Java.
Use meaningful identifier names.
Here is the code:
import java.util.Scanner;
public class Temperature
{
public static double convertFarenheitToCelsius(double farenheit)
{
return (farenheit-32)*5/9;
}
public static void main(String[] args)
{
double farenheit; //Stores Farenheit
double celsius; //Stores Celsius
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter a temperature in Fahrenheit: "); //Enter in Farenheit
if (keyboard.hasNextDouble()){
F = keyboard.nextDouble(); //Stores Farenheit
System.out.println("The temperature in Celsius is: " + convertFarenheitToCelsius(farenheit)); //Displays Celsius (call convertFarenheitToCelsius(farenheit) where celcius conversion needed)
farenheit = 0;
System.out.println("Fahrenheit\t Celsius");
while (farenheit <= 100){
System.out.println(farenheit + "\t\t" + convertFarenheitToCelsius(farenheit));
farenheit += 10;
}
} else {
System.err.format("%s is not a double!%nPlease enter a double value.", keyboard.next());
System.exit(1);
}
}
}
Set F+=10 instead of F++ in the loop.
I think in your case use FOR is a better choice.
public static void main(String[] args) {
double fahrenheit = 50;
double increment = 10;
for(;fahrenheit <= 100; fahrenheit += increment){
System.out.println(fahrenheit);
}
}
Related
Got this code here and I was wondering if it were possible to make the output that comes from either calculation systems be without a decimal/stop the value at the point before the decimal point. Or even convert a double to an int without any errors.
Please ignore the pointless do while loop at the start, I am aware.
Thank You for any help.
class Main{
public static void main(String[] args)
{
calculation(getSystemChoice());
}
public static int getSystemChoice()
{
Scanner input = new Scanner(System.in); //create scanner
int systemChoice;
do{
System.out.println("If you are using the Metric system, please enter a 1.");
System.out.println("If you are using the Imperial system, please enter a 2.");
System.out.println("To quit the program, please enter a 3.");
systemChoice = input.nextInt();
//Switch start
switch(systemChoice){
case 1:
systemChoice=1;
return systemChoice;
case 2:
systemChoice=2;
return systemChoice;
default: //Currently no working input correction system, likely due to no case for 3. !!!!
System.exit(0);
}
//Switch End
}
while(systemChoice != 1 || systemChoice != 2 || systemChoice != 3);
return systemChoice;
}
//This method takes an int as a parameter(1 or 2) and runs if statements based on the metric or imperial systems.
public static void calculation(int systemChoice)
{
double inches, centimeters, meters, feet;
Scanner input = new Scanner(System.in); //create scanner
//if the user entered one, the result will be in meters and centimeters
if(systemChoice == 1){
System.out.print("Enter amount of meters: ");
meters = input.nextDouble();
System.out.print("Enter amount of centimeters: ");
centimeters = input.nextDouble();
feet = meters * 3.28084;
inches = centimeters / 2.54;
System.out.printf("Feet: %.2f\t " , feet);
System.out.printf("Inches: %.2f\t " , inches);
rerun(systemChoice);
}
// if the user entered 2 then the result will be in feet and inches
else if(systemChoice == 2){
System.out.print("Enter amount of feet: ");
feet = input.nextDouble();
System.out.print("Enter amount of inches: ");
inches = input.nextDouble();
meters = feet / 3.28084;
centimeters = inches * 2.54;
System.out.printf("Meters: %.2f\t " , meters);
System.out.printf("Centimeters: %.2f\t\n " , centimeters);
rerun(systemChoice);
}
}
public static void rerun(int systemChoice)
{
Scanner in = new Scanner(System.in);
System.out.println("\nIf you would like to make another measurement, enter 4.");
System.out.println("Otherwise, you may quit by entering any other number.");
systemChoice = in.nextInt();
if(systemChoice == 4)
{
getSystemChoice();
calculation(systemChoice);
}
else
{
System.exit(0);
}
}
}
You can use casting just before you print it and print it as an integer.
System.out.printf("Inches: %d " , (int)inches)
I do not recommend simply casting to int. Here is an example:
double myValue = 8.65;
System.out.println((int) myValue); // will output 8 as java will always round to the next lower integer
System.out.println(Math.round(myValue)); // will output 9 which obviously is correct (mathematically speaking)
There are a number of potential solutions depending on your exact requirements. Other posters have already mentioned a couple. It's worth bearing in mind the pros and cons of each:
Simply casting to an int or long is the simplest method, but will always round down. It's probably fine for your training example. But in real-world applications, this can cause subtle bugs with values that a double can represent but an int or long can't (e.g. a double can represent the result of 1.0/0 as "infinity", but casting to an int or long will turn this into a large positive integer value-- that can lead to subtle bugs in real-world applications);
You can use Math.round() to use the convention of rounding to up or down to the 'nearest' integer; but this doesn't solve the issue of values that can't be represented;
For other rounding modes, you can use the BigDecimal class: see the BigDecimal.round() method-- many applications won't require this, but some specialist cases might;
To truncate to zero decimal places for output while also dealing with 'special' values, you can use String.format() and specify zero decimal places.
The code for the latter option would look as follows:
double val = ...
System.out.printf("Truncated value is: %.0f", val);
You've probably already seen the 'simple casting' option, but it would look like this:
double val = ...
long truncatedVal = (long) val;
System.out.println("Truncated value = " + truncatedVal);
import java.util.*;
public class Project3{
public static void main(String[] args)
{
Scanner key = new Scanner (System.in);
double rate = 0.05;
double annually, monthly, daily;
double balance;
int year = 10 ;
System.out.println("Enter the amount you will like to deposit or type exit to end.");
int deposit = key.nextInt();
annually = deposit * Math.pow((1 + rate/1),year);
monthly = deposit * Math.pow((1 + rate/12),year);
daily = deposit * Math.pow((1 + rate/365),year);
while (deposit)
{
}
System.out.println(annually);
System.out.println(monthly);
System.out.println(daily);
}
}
This is what I currently have. What I am trying to accomplish is to make a loop to add the first outcome with the next one. Also make one formula instead of having three to find the annually, monthly and daily.
First and foremost, asking someone to write out your homework is really unethical, and not helpful for you in the long run. If you don't care about the long run, consider taking a different class. In a career scenario, you're expected to write code on your own.
Secondly, to actually answer your question, here are some tips:
It seems like you want to gather a value (deposit) from the user, and then calculate the Compound Interest for said value. Your program also needs to not exit until the user says to exit. i.e. they want to calculate the CI for a set of numbers.
First step is to check the value from the user. If it is a number, then do calculations on it. If it is a String, then check if it is "exit". In Java, this amounts to writing out an if-statement, and making use of the very helpful "instanceof" keyword. If you haven't learned about that, give this a read, or ask your teacher.
For the calculations part, you simply do calculations on the user's input while the input is not a string set to "exit".
Finally, print out your calculations.
That's it. Your code already has the calculation formulas down, so you just need to code the logic for handling user input.
import java.util.Scanner;
import java.lang.Math;
public class HelloWorld {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("How much money you want to deposit?");
int principle = sc.nextInt();
System.out.println("what is the rate you want?");
float rate = sc.nextFloat();
System.out.println("After how many years, you want to see your money?");
int year = sc.nextInt();
System.out.println("How many compounds in a year?");
int partialTime = sc.nextInt();
double b = year * partialTime;
double a = 1 + (rate/(partialTime*100));
double x = principle * (Math.pow(a,b));
System.out.println("Your interest in given time would be " + x);
}
}
A couple of suggestions - since you want to check user input against both String and int types, you could define a String type variable to hold the user input, and then do a try/catch to parse it as an Integer, if it's not an Integer check if the input equals "exit" (using the String.equals() method).
import java.util.*;
public class Project3{
public static void main(String[] args)
{
Scanner key = new Scanner (System.in);
double rate = 0.05;
double annually = 0, monthly = 0, daily = 0;
double balance;
int year = 10, deposit = 0 ;
String userinput = "";
do {
try {
System.out.println("Enter the amount you will like to deposit or type exit to end.");
userinput = key.nextLine();
deposit = Integer.parseInt(userinput);
}
catch (Exception e){
if (!userinput.equals("exit")){
System.out.println("Didn't recognize that input, please try again...");
}
else{
break;
}
}
} while (!userinput.equals("exit"));
annually += deposit * Math.pow((1 + rate/1),year);
monthly += deposit * Math.pow((1 + rate/12),year);
daily += deposit * Math.pow((1 + rate/365),year);
System.out.println(annually);
System.out.println(monthly);
System.out.println(daily);
}
}
Depending on how you want the output, you can easily adjust the scope of the loop to display the amounts after each valid deposit input, or just once at the end, after the user enters "exit".
Hope this helps.
Could someone please explain to me how to make a program with a tester class with this code as its base that will help me do this?
//This program converts the user input from Celsius to Fahrenheit and vice versa
import java.io.*;
class Converter
{
// variables
String input;
double fahrenheit;
double celcius;
//constructor with 3 parameters to initialize the variables
Converter(String converterInput, double converterFahrenheit, double converterCelcius) throws IOException
{
InputStreamReader inStream = new InputStreamReader(System.in);
BufferedReader stdin = new BufferedReader(inStream);
input = converterInput;
fahrenheit = converterFahrenheit;
celcius = converterCelcius;
input = stdin.readLine();
fahrenheit = Double.parseDouble(input);
input = stdin.readLine();
celcius = Double.parseDouble(input);
}
// method
double fahrenheitConverter()
{
return fahrenheit = (9.0 / 5.0) * celcius + 32;
}
// method2
double celciusConverter()
{
return celcius = (5.0 / 9.0) * (fahrenheit - 32);
}
}
Sorry but this was a mess. :)
Or maybe I didnt had enough time to anticipate the way you wanted to do this.
Anyways I had to change the whole thing.I apologise for this.
Here is a code that works.
import java.io.*;
import java.util.Scanner;
final class Converter
{
// variables
double input;
double fahrenheit;
double celcius;
//constructor with 3 parameters to initialize the variables
Converter() throws IOException
{
//InputStreamReader inStream = new InputStreamReader(System.in);
String temp;
System.out.print("Please enter the temperature : ");
Scanner key=new Scanner(System.in);
input = key.nextDouble();
System.out.print("The number you gave is ");
fahrenheit=(fahrenheitConverter(input));
System.out.print(fahrenheit + " fahreneit degree , if u entered a celcious value.\n");
celcius=(celciusConverter(input));
System.out.print("Or it is "+ celcius + " celcius degree , if u entered a celcious value.\n");
}
// method
double fahrenheitConverter(double inp)
{
double iput=inp;
double fah;
fah = (iput*1.8)+ 32;
return fah;
}
// method2
double celciusConverter(double inp)
{
double iput=inp;
double cel;
cel=(iput-32)*0.5555;
return cel;
}
public static void main(String[] args) throws IOException {
Converter x=new Converter();
}
}
BUT this is only the code , in the proper (in my view) order.
Program needs to take two information items.Value and metric.
I mean that you have to ask user for the temperature (a double number) and
what is this number , celcius or fahre.
Also you will need some defence , throwing exceptions for ex. like input errors (ex user inputs like , 32,5 , a13 , 2')
Also , I used main() in order to use it compact and take the results easy.
You could have the class and call
public static void main(String[] args) throws IOException {
Converter x=new Converter();
}
from outside the class.
I will be happy to give any help beyond this.
You need to have the user specify which way they want to convert. The program doesn't do anything if the user tells the program what the Celsius and Fahrenheit temperatures already are, and you need to create methods to separately convert from Celsius to Fahrenheit and vice versa.
I hope I'm posting in the right place.
I'm pretty new to Java (meaning this is only my third program besides 'hello world').
I have a tip calculator I'm working on for an assignment. I'm not getting an 'error' as such,
but the method for splitting the bill always seems to think each customer pays 'infinity'.
I have my program set up in two classes: tipCalc1 and tipCalc2 (no points for originality of course).
The program appears to run without issue besides the 'infinity' issue.
Here's what I have so far. Any assistance appreciated, thanks.
***TipCalc1 Class:***
import java.util.Scanner;
public class Tipcalc1
{
public static void main(String[] args)
{
System.out.println("Welcome to Tip Calculator! ");
TipCalc2 Calculator = new TipCalc2();
System.out.println("Please enter the bill amount: ");
TipCalc2.calBill();
System.out.println("What percentage would you like to tip?: ");
Calculator.percTip();
}
}
***And the tipCalc2 class which does the dirty work:***
import java.util.Scanner;
public class TipCalc2
{
static double bill;
double tip;
double total;
double split;
double splitPrompt;
double Y;
double N;
double billPerPerson;
static Scanner scan = new Scanner(System.in);
public static void calBill()
{
bill = scan.nextDouble();
}
public void percTip()
{
tip = scan.nextDouble();
if(tip<1)
{
total = bill * tip;
}
else total = bill * (tip/100);
System.out.println("Your total is: " + total);
Split();
}
public void Split()
{
System.out.println("Would you like to split the bill? ");
System.out.println("Enter 1 for YES or 0 for NO: ");
splitPrompt = scan.nextDouble();
if(splitPrompt == 0)
{
System.out.println("Your total is: " + total);
System.out.println("Thankyou. Goodbye.");
System.out.println("End Program");
}
if(splitPrompt == 1)
{
System.out.println("How many ways would you like to split the bill? ");
splitPrompt = scan.nextDouble();
billPerPerson = total / split;
System.out.println("Each person pays: " + billPerPerson);
System.out.println("Thankyou. Goodbye.");
System.out.println("End Program.");
}
else System.out.println("Invalid Entry");
}
}
The default value for split (because you have not initialized it with another value) is 0.0, therefore, when you do
billPerPerson = total / split;
you divide by 0.0, so you will get Infinity.
Notes:
Since your variable splitPrompt is double and computers doesn't store real values with a 100% accuracy, you shouldn't compare it with 0.0. Since this variable will store 0 or 1 for input, you can declare it as int, which will be accurate.
Try to follow Java naming conventions. Use mixedCase for methods/variables and use CamelCase for classes/interfaces.
In the method split(), you should use an if-else if-else structure:
if(splitPrompt == 0) {
...
}
else if(splitPrompt == 1) {
...
}
else {
...
}
Silly mistake.
Change
System.out.println("How many ways would you like to split the bill?
splitPrompt = scan.nextDouble();
to
System.out.println("How many ways would you like to split the bill?
split = scan.nextDouble();
since you never change split which, like all double variables, is initialized to 0.0.
Also, you should use ints where appropriate as not all of the numbers should be doubles. Or even better, use 'y' and 'n' chars.
Class TipCalc2
//Total = **bill** * (gets percentage in decimal 15 = 0.15) + **bill**
Line 18 needs to be:
total = bill * (tip / 100) + bill;
Line 36/37 needs to be:
split = splitPrompt = scan.nextInt();
billPerPerson = total / split;
//You're dividing billPerPerson = total by ZERO (split);
Line 36/37 original:
billPerPerson = total / split;
I have a main method and 4 other function type methods which include calculations, however, How would I call each one up into the main and proceed to print out the calculations. Also I am currently getting a lot of syntax errors.
I've tried placing brackets and braces when needed, however, that has just resulted into more errors. Also, I tried initializing Strings and integers elsewhere, which still seems to fail to work. Any help would be much appreciated!
Some syntax errors include: ';' expected on line 60
insert ';' to complete localVariableDelcartion on line 60
these errors are repeated for every line
import java.io.*;
//create the class
public class CirclemethodsFixedagain
{
//main method
public static void main(String[] args) throws IOException
{
BufferedReader myInput = new BufferedReader(new InputStreamReader(System.in));
String numInput;
String reqInput;
String amountStr;
double numInt = 0;
double num = 0;
System.out.println("This program will ask for a given user radius, then proceed to calculate the user input");
System.out.println("The program will use four methods to achieve this, all calling back to the main method");
System.out.println("Press any key to continue");
numInput = myInput.readLine();
// more user questions
System.out.println("First, what would you like to calculate?");
System.out.println("Enter '1' for Circumference, '2' for area, '3' for volume, or '4' for surface area");
System.out.println("*NOTE* Pressing a key outside of this range or a regular character will re-prompt the original message");
reqInput = myInput.readLine();
numInt = Double.parseDouble(reqInput);
// more user questions
System.out.println("Now enter the radius of the required shape(Half of diameter)");
System.out.println("*NOTE* Pressing a regular character will re-prompt the original message");
numInput = myInput.readLine();
num = Double.parseDouble(numInput);
}
//user created method, with each
public static int circlemethods(double circumference) throws IOException {
{
if (numInt == 1)
{
System.out.println("You chose to calculate circumference, given the radius :" + num);
circumference = (Math.PI) * (2) * (num);
System.out.print("The circumference of that sphere is :");
return circumference;
}
public static double circlemethods2 (double area) throws IOException
{
if (numInt == 2)
{
System.out.println("You chose to calculate area, given the radius :" + num);
area = (Math.PI * num * num);
System.out.print("The area of the circle is :");
return area;
}
}
public static double circlemethods3 (double volume) throws IOException
{
if (numInput == 3)
{
System.out.println("You chose to calculate volume, given the radius :" + num);
volume = (4 * Math.PI * num * num * num) / 3 ;
System.out.print("The volume of that sphere is : cm³");
return volume;
}
}
public static double circlemethods4 (double surfaceArea) throws IOException
if (numInput == 4)
{
System.out.println("You chose to calculate surface area, given the radius :" + num);
surfaceArea = 4 * Math.PI * num * num;
System.out.print("The Surface area of that sphere is :");
return surfaceArea;
}
}
}
}
Your braces - the { and } characters - don't match up. I have fixed the indentation of the code in the question so that you can better see where the problem gets started - in the method circlemethods. Also, circlemethods4 is missing its braces.
Keeping consistent indentation levels throughout the program makes these kinds of errors a lot more obvious to spot.
Compilation errors are caused by:
You can not place methods inside other method, move circlemethods 2,3,4 outside the circlemethod1.
Your circlemethods don't see numInt local variable. It is declared in main method and it is visible only in that one.
I believe you don't need if statements at the begining of each circlemethods. You rather need something like that:
if (numInt == 1)
{
circlemethod1(radius);
} else if (numInt == 2) {
circlemethod2(radius);
}
etc. in your main method.
You can also change argument's name of each circlemethod, as I understood it is always radius. Current name of arguments is a good candidate for method name.
Following are the inputs that will fix the problem :
You can't declare method inside a method, It's not JAVA syntax. Just check the bracing correctly. Use any IDE for doing the same.
Make numInt, num as static (Class) variables. As you are using those in static method.
Use proper names and camelCasing nomenclature to name any method.
|e.g calculateCircleArea(), calculateCircleVolume(), etc..
Hope this solves your problem.