Ok,so I'm a complete novice at programming and I just started coding in Java. I tried to write a code for temperature conversion (Celsius to Fahrenheit) and for some reason it simply won't run! Please, help me find out errors in this code(however silly it may be).
Here's the code:
package tempConvert;
import java.util.Scanner;
public class StartCode {
Scanner in = new Scanner(System. in );
public double tempInFarenheit;
public double tempInCelcius;
{
System.out.println("enter the temp in celcius");
tempInCelcius = in .nextDouble();
tempInFarenheit = (9 / 5) * (tempInCelcius + 32);
System.out.println(tempInFarenheit);
}
}
You forgot to write the main method which is the start point for a program to run. Let me modify your code.
import java.util.Scanner;
public class StartCode
{
Scanner in = new Scanner (System.in);
public double tempInFarenheit;
public double tempInCelcius;
public static void main (String[] args)
{
System.out.println("enter the temp in celcius");
tempInCelcius = in.nextDouble() ;
tempInFarenheit = (9/5)*(tempInCelcius+32);
System.out.println(tempInFarenheit);
}
}
I think this is going to work better for you:
import java.util.Scanner;
public class StartCode
{
public static void main(String[] args) {
Scanner in = new Scanner (System.in);
double tempInFarenheit;
double tempInCelcius;
System.out.println("enter the temp in celcius");
tempInCelcius = in.nextDouble() ;
tempInFarenheit = 1.8*tempInCelcius+32;
System.out.println(tempInFarenheit);
}
}
You equation for Farenheit was incorrect. Integer division isn't for you, either.
You need a main method. I also suggest using an IDE such as Eclipse, which can generate the skeleton code for you (including the syntax of the main method).
import java.util.*;
public class DegreeToFahrenheit {
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("Enter a temperature: ");
double temperature = input.nextDouble();
System.out.println("Enter the letter of the temperature type. Ex: C or c for celsius, F or f for fahrenheit.: ");
String tempType = input.next();
String C = tempType;
String c = tempType;
String F = tempType;
String f = tempType;
double celsius = temperature;
double fahrenheit = temperature;
if(tempType.equals(C) || tempType.equals(c)) {
celsius = (5*(fahrenheit-32)/9);
System.out.print("The fahrenheit degree " + fahrenheit + " is " + celsius + " in celsius." );
}
else if(tempType.equals(F) || tempType.equals(f)) {
fahrenheit = (9*(celsius/5)+32);
System.out.print("The celsius degree " + celsius + " is " + fahrenheit + " in fahrenheit." );
}
else {
System.out.print("The temperature type is not recognized." );
}
}
}
Related
package tempconverter;
import java.util.*;
import java.util.Scanner;
public class TempConverter {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
double tem;
System.out.print("Enter number: ");
double temp = sc.nextDouble();
System.out.println("Convert to Celsius or Fahrenheit (C or F): ");
int input = sc.nextInt();
if (input == 'C'){
System.out.println("Fahrenheit to Celcius is: " + toCelsius(temp));
}else if(input == 'F'){
toFahrenheit(temp);
}
public static double toCelsius(double cels){
double far = 5/9.0*(cels-32);
return far;
}
public static void toFahrenheit(double fahr){
double tem = 9/5.0*fahr+32;
System.out.println("Celsius to Fahrenheit: " + toFahrenheit(tem));
}
}
I refactored your code. You were having a recursive call inside one of your methods and your method were not returning values.
public static void main(String[] args) {
String name = null;
float temperature;
Scanner in = new Scanner(System.in);
System.out.println("Enter temperature: " );
temperature = in.nextFloat();
System.out.println("Convert to Celsius or Fahrenheit (C or F): ");
name = in.next();
if (name.equals("C")) {
System.out.println("Fahrenheit to Celcius: " + toCelsius(temperature));
}else if (name.equals("F")){
System.out.println("Celsius to Fahrenheit: " + toFahrenheit(temperature));
}
}
public static double toCelsius(double cels){
double far = 5/9.0*(cels-32);
return far;
}
public static double toFahrenheit(double fahr){
double tem = 9/5.0*fahr+32;
return tem;
}
The main problem is that you have a cycle in your code. The method toFahrenheit calls toFahrenheit again inside the println. This leads to an infinite loop which will result in a stackoverflow at some point. Move the println outside of the method like in the toCelsius and return the converted value.
Apart from this you have a problem as 'C' and 'F'.
I am using the Java SDK to compile. Need I say, I am a beginner.
Here is the code I tried to use to "Ask user to input decimal and code should output an integer. (round to nearest integer)
import java.util.*;
public class readDecimal {
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
double decimalNumber;
long intNumber;
System.out.println(“Please enter a decimal number:“);
decimalNumber = input.nextDouble();
intNumber = Math.round(decimalNumber);
System.out.println(decimalNumber +
“ rounded to the nearest integer is “ + intNumber);
}
}
What am I doing wrong? I saw the other posts however they seem much to complicated for a beginner. Can you please help?
Thank you,
Diane
Your quotation marks are incorrect; they are unicode for some reason. Replace all the quotations by manual typing them in, in you System.out.println statements.
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
double decimalNumber;
long intNumber;
System.out.println("Please enter a decimal number:");
decimalNumber = input.nextDouble();
intNumber = Math.round(decimalNumber);
System.out.println(decimalNumber +
" rounded to the nearest integer is " + intNumber);
}
You can round double numbers using Math.round method.
import java.util.*;
public class RoundingDecimal {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
double num1;
double num2;
System.out.print("Please enter a decimal number: ");
num1 = sc.nextDouble();
num2 = Math.round(num1);
System.out.println(" Rounded to the nearest integer is " + num2);
}
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I looked and could not find anything like what I am wanting to do. I have a method with 3 parameters that I need to call from my main method. I've tried everything I have leaned in class so far, but I cannot fig this out. this is for my Programming in Java Course. Here is what I need to call from my main method:
import java.util.*;// for scanner
import java.text.DecimalFormat;
public class Grades {
//Homework, exam1, and exam2 weights
static double homeworkWeight;
static double examOneWeight;
static double examTwoWeight;
//Homework
static int homeworkNumberOfAssignments;
static int homeworkAssignment1Score;
static int homeworkAssignment1Max;
static int homeworkAssignment2Score;
static int homeworkAssignment2Max;
static int homeworkAssignment3Score;
static int homeworkAssignment3Max;
static int homeworkSectionsAttended;
static int homeworkSectionsAttendedTotal;
static int homeworkSectionsAttendedMax;
double homeworkTotalPoints;
double homeworkMaxPoints;
double homeworkWeightedScore;
//Exam1
static int examOneScore;
static int examOneCurve;
static double examOneMaxPointsAvailable;
double examOneWeightedScore;
//Exam2
static int examTwoScore;
static int examTwoCurve;
static double examTwoMaxPointsAvailable;
double examTwoWeightedScore;
//Grades
static double courseGrade;
static double grade;
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
showIntro();
System.out.println("");
System.out.print("Homework and Exam 1 weights? ");
homeworkWeight = console.nextInt();
examOneWeight = console.nextInt();
examTwoWeight = 100 - homeworkWeight + examOneWeight;
System.out.println("Using weights of " + homeworkWeight + " " + examOneWeight + " " + examTwoWeight);
homework();
System.out.println("");
exam1();
//System.out.println("");
//exam2();
//System.out.println("");
//courseGrade(courseGrade; double homeworkWeightedScore; double examOneWeightedScore; double examTwoWeightedScore;);
double d = courseGrade(homeworkWeightedScore, examTwoWeightedScore, examTwoWeightedScore);
System.out.println("");
}//
//Shows the intro to the program to the user.
public static void showIntro() {
System.out.println("This program accepts your homework scores and");
System.out.println("scores from two exams as input and computes");
System.out.println("your grades in the course.");
}
public static void homework() {
Scanner console = new Scanner(System.in);
System.out.println("");
System.out.println("Homework:");
System.out.print("Number of assignments? ");
homeworkNumberOfAssignments = console.nextInt();
System.out.print("Assignment 1 score and max? ");
homeworkAssignment1Score = console.nextInt();
homeworkAssignment1Max = console.nextInt();
System.out.print("Assignment 2 score and max? ");
homeworkAssignment2Score = console.nextInt();
homeworkAssignment2Max = console.nextInt();
System.out.print("Assignment 3 score and max? ");
homeworkAssignment3Score = console.nextInt();
homeworkAssignment3Max = console.nextInt();
System.out.print("Sections attended? ");
homeworkSectionsAttended = console.nextInt();
homeworkSectionsAttendedTotal = homeworkSectionsAttended * 4;
homeworkSectionsAttendedMax = 20;
//Calculating total points earned
double totalPoints = homeworkAssignment1Score + homeworkAssignment2Score + homeworkAssignment3Score + homeworkSectionsAttendedTotal;
//Calutaing the max points available to be earned
double maxPoints = homeworkAssignment1Max + homeworkAssignment2Max + homeworkAssignment3Max + homeworkSectionsAttendedMax;
//Formatting with DecimalFormat to remove the decimal and 0 when displaying
DecimalFormat df = new DecimalFormat("###.#");
System.out.println(("Total points = ") + df.format(totalPoints) + " / " + df.format(maxPoints));
//Calculating the weighted score by dividing totalPoints by maxPoints and then multiplying times homeworkWeight
double homeworkWeightedScore = ((totalPoints / maxPoints) * homeworkWeight);
//Printing out weighted score and rounding to the nearest hundreth with Math.round
System.out.println("Weighted score = " + Math.round(homeworkWeightedScore * 100.0) / 100.0);
}
public static void exam1() {
Scanner console = new Scanner(System.in);
System.out.println("Exam 1:");
System.out.print("Score? ");
examOneScore = console.nextInt();
System.out.print("Curve? ");
examOneCurve = console.nextInt();
System.out.println("Total points = " + examOneScore + " / " + examOneCurve);
examOneMaxPointsAvailable = 100;
double examOneWeightedScore = ((examOneScore / examOneMaxPointsAvailable) * examOneWeight);
System.out.println("weighted score = " + Math.round(examOneWeightedScore * 100.0) / 100.0);
}
public static void exam2() {
Scanner console = new Scanner(System.in);
System.out.print("Exam 2:");
System.out.print("Score? ");
examTwoScore = console.nextInt();
System.out.print("Curve? ");
examTwoCurve = console.nextInt();
System.out.print("Total points = ");
System.out.println("weighted score = ");
}
public double courseGrade(double homeworkWeightedScore, double examOneWeightedScore, double examTwoWeightedScore) {
return homeworkWeightedScore + examOneWeightedScore + examTwoWeightedScore;
}
}
There's a couple factors missing from your question that makes me unable to completely answer them, but:
Is the courseGrade method in a separate class or in the same class as your public static void main method?
Yes: Create a new instance of the separate class by doing: public SeparateClass instance = new SeparateClass(); inside of public static void main
After that, call this from your main method: double grade = instance.courseGrade(homeworkWeightedScore, examTwoWeightedScore, examTwoWeightedScore);
No: Make the courseGrade method static, you can't call a non-static method from a static method (replace public double courseGrade with public static double courseGrade). After that, inside of your main method, do this: double d = courseGrade(homeworkWeightedScore, examTwoWeightedScore, examTwoWeightedScore);
I hope this helps.
I'm trying to make a unit conversion program but I keep receiving value as infinity. I'm not sure where I need to fix since it's not giving me errors. I only tested oz to ml to make sure I'm doing it correctly but I'm receiving infinity as the answer.
UnitConverter.java:
public class UnitConverter {
final double oz_TO_ml = 29.5735;
final double gal_TO_g = 3.78541;
final double lb_TO_kg = 0.453592;
final double inc_TO_mm = 25.4;//Inc is inches
final double ft_TO_cm = 30.48;
final double mi_TO_km = 1.60934;
double factor;
public UnitConverter(String unit) {
if (unit.equals("oz")) {
factor = oz_TO_ml;
} else if (unit.equals("gal")) {
factor = gal_TO_g;
} else if (unit.equals("lb")) {
factor = lb_TO_kg;
}
}
public double toOz(double amount) {
return (amount * factor);
}
public double fromOz(double amount) {
return (amount / factor);
}
public double toMl(double amount) {
return (amount * factor);
}
public double fromMl(double amount) {
return (amount / factor);
}
}
Calculator.java:
import java.util.Scanner;
public class Calculator {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Convert from: ");
String fromUnit = in.nextLine();
System.out.print("Convert to: ");
String toUnit = in.nextLine();
UnitConverter from = new UnitConverter(fromUnit);
UnitConverter to = new UnitConverter(toUnit);
System.out.print("Value ");
double val = in.nextDouble();
double oz = from.toOz(val);
double converted = to.fromOz(oz);
System.out.println(val + " " + fromUnit + " = " + converted + " " + toUnit);
}
}
Sample input:
Convert from: oz
Convert to: ml
Value 12
Output:
12.0 oz = Infinity ml
Initialize the factor varible with one. A java with default give 0 to primitive double,
class UnitConvertor {
final double oz_TO_ml = 29.5735;
final double gal_TO_g = 3.78541;
final double lb_TO_kg = 0.453592;
final double inc_TO_mm = 25.4;//Inc is inches
final double ft_TO_cm = 30.48;
final double mi_TO_km = 1.60934;
double factor=1;//initialize with 1
But I am still not sure that what is the check you are using if the user input is 'ml'.
public UnitConverter(String unit)
{
if (unit.equals("oz"))
{
factor = oz_TO_ml;
} else if (unit.equals("gal"))
{
factor = gal_TO_g;
} else if (unit.equals("lb"))
{ factor = lb_TO_kg;
}
}
If you pass "ml" the factor will be zero
Your design currently needs two of these but you really only need one as "oz" has everything it needs to do the conversion.
Ignore the the toUnit in your line input code and just use fromUnit
Edit : I'll show you an alternative way to do things, it just supports one convert to show the rough design. Note the method calls are now static because you will only ever need one instance of them
UnitConverter.java
public class UnitConverter
{
private static final double oz_TO_ml = 29.5735;
public static double convert(String fromType, String toType,double amount) throws IllegalArgumentException
{
if (fromType.equals("oz") && toType.equals("ml"))
{
return (amount * oz_TO_ml);
}
else
{
throw new IllegalArgumentException("The combination of converting " + fromType + " to " + toType + " is not supported");
}
}
}
Calculator.java:
import java.util.Scanner;
public class Calculator {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Convert from: ");
String fromUnit = in.nextLine();
System.out.print("Convert to: ");
String toUnit = in.nextLine();
System.out.print("Value ");
double val = in.nextDouble();
System.out.println(val + " " + fromUnit + " = " + UnitConverter.convert(fromUnit,toUnit,val) + " " + toUnit);
}
}
Your UnitConverter class constructor only knows about 3 units: oz, gal, and lb. If you instantiate it with one of those, it will correctly assign the factor and be able to convert units, as seen below:
public UnitConverter(String unit) {
if (unit.equals("oz")) {
factor = oz_TO_ml;
} else if (unit.equals("gal")) {
factor = gal_TO_g;
} else if (unit.equals("lb")) {
factor = lb_TO_kg;
}
}
However, in your Calculator class, you have this line:
UnitConverter from = new UnitConverter(fromUnit);
UnitConverter to = new UnitConverter(toUnit);
If you run your program with your sample input, from is oz and to is ml. But if you instantiate UnitConverter with the unit ml, what does factor get set to? According to your constructor, it is never set, and so it retains its default value of 0.0.
Later, you call this line:
double converted = to.fromOz(oz);
This runs the fromOz method
public double fromOz(double amount) {
return (amount / factor);
}
Which divides by the factor, which is 0.0. This is the source of your Infinity output.
As the other answer says, you don't need to have two UnitConverter objects to perform this calculation. The factor is correct to convert between ounces and millilitres, so this Calculator code is sufficient.
import java.util.Scanner;
public class Calculator {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Convert from: ");
String fromUnit = in.nextLine();
UnitConverter from = new UnitConverter(fromUnit);
System.out.print("Value ");
double val = in.nextDouble();
double result = from.toMl(val);
System.out.println(val + " " + fromUnit + " = " + result + " ml.");
}
}
If you wanted to keep your current calculator code, you would need to add a condition in your UnitConverter constructor for a scalefactor for ml (1.0). However, I think this approach is flawed because what happens, for example, when you try to convert between oz and inches? The conversion makes no sense but your architecture would not prevent it.
I exported my Java file, and its kind of working proberly.. theres just a little problem, that when the scanner have calculated my inputs, it outputs the result, but the application closes 1 sec after i recieved my output. How do i prevent my application from close?? the code is:
best regards
Oliver
import java.util.Scanner;
import java.util.HashMap;
import java.util.*;
public class Valuta {
public static void main(String[] args){
double euro, usd, gpb, dkk, done;
Scanner input = new Scanner(System.in);
System.out.println("Convert from " +"USD,GPB, DKK or EURO?");
String temp = (input.nextLine()).toUpperCase();
System.out.println("to " + "USD,GPB, DKK or Euro?");
String tempp = (input.nextLine()).toUpperCase();
Map<String, Double> lookUpMap = new HashMap<String, Double>(){{
put("EURO", new Double(7.46));
put("USD", new Double(5.56));
put("GPB", new Double(8.84));
put("DKK", new Double (1.0));
}};
System.out.println("amount of " + (temp));
double amount = input.nextDouble();
done = (lookUpMap.get(temp) / lookUpMap.get(tempp)) * amount;
System.out.println(done);
}
}
try this..
public static void main(String[] args) {
double euro, usd, gpb, dkk, done;
Scanner input = new Scanner(System.in);
String ch = "";
do{
System.out.println("Convert from " + "USD,GPB, DKK or EURO?");
String temp = (input.nextLine()).toUpperCase();
System.out.println("to " + "USD,GPB, DKK or Euro?");
String tempp = (input.nextLine()).toUpperCase();
Map<String, Double> lookUpMap = new HashMap<String, Double>() {
{
put("EURO", new Double(7.46));
put("USD", new Double(5.56));
put("GPB", new Double(8.84));
put("DKK", new Double(1.0));
}
};
System.out.println("amount of " + (temp));
double amount = input.nextDouble();
done = (lookUpMap.get(temp) / lookUpMap.get(tempp)) * amount;
System.out.println(done);
System.out.println("Do you want continue ? Y/N");
ch = input.nextLine();
} while(ch.equals("Y"));
}