This question already has answers here:
Getting error "cannot find or load main class HelloWorld"
(3 answers)
Closed 6 years ago.
So I need to write a program in java that takes 2 user inputed temperatures in celsius and converts it to Fahrenheit and kelvin. i wrote the code and it works in eclipse but my teacher strictly said it has to work in cmd. it compiles fine but when i go to run it it states could not find or load main class temperatureTester (name of the class with my main). This is my first post so if you need more info please ask and i'm looking for any ideas why this is happening. below is my code for the question.
import java.util.Scanner;
public class temperatureTester{
public static void main (String[]args){
//create 2 objects connecting to temperatureC
temperatureC firstValue = new temperatureC();
temperatureC secondValue = new temperatureC();
// initialize scanner
Scanner stdin = new Scanner (System.in);
//initialize variables
double firstC = 0;
double secondC = 0;
//prompt user for both values
System.out.print("Please enter initial temperatures: ");
firstC = stdin.nextDouble();
secondC = stdin.nextDouble();
//call object set methods and pass entered values as arguments
firstValue.setC(firstC);
secondValue.setC(secondC);
//display the values for the values for different temp. units
System.out.println("1) The current temperature in Celcius is: " + firstValue.getC());
System.out.println("1) The current temperature in fahreinheit is: " + firstValue.getF());
System.out.println("1) The current temperature in kelvin is: " + firstValue.getK());
System.out.println("---------------------------------------------------------------");
System.out.println("2) The current temperature in Celcius is: " + secondValue.getC());
System.out.println("2) The current temperature in fahreinheit is: " + secondValue.getF());
System.out.println("2) The current temperature in kelvin is: " + secondValue.getK());
this is the second class
public class temperatureC{
private double C;
/**
The setC method stores the value in the C field
# param initialC the value stored in C
*/
public void setC(double initialC){
C = initialC;
}
/**
The getC returns the C value and also sets a lower limit,
if a number below is entered it sets it ti the limit.
#Return the value of the C
*/
public double getC(){
if(C < -273.15){
C = -273.15;
}
return C;
}
/**
the getF method calculates and returns a value for C in fahrenheit
#return the computed for C in fahrenheit
*/
public double getF(){
return C * 1.8 + 32;
}
/**
The getK method computes and returns a value for temperature C in kelvin
#return the computed Kelvin value
*/
public double getK(){
return C + 273.15;
}
}
The Best approach might b that you export your project as executable jar file to achieve this have a look on following official ecclipse link http://help.eclipse.org/neon/index.jsp?topic=%2Forg.eclipse.jdt.doc.user%2Ftasks%2Ftasks-37.htm
then next part you need to run it from Command line this is a fun part just change the directory to the path where your jar file is located and then here comes the following command
java -jar yourJar.jar
pause
and then it will b executing like a charm!
Simply compile your both files in cmd using javac
After successfully compiling simply run your main class i.e temperatureTester class using java. It successfully executed.
Related
This Question is from my programming class:
In the convertFToC method, change the second System.out.println statement so it produces a display such as
212.0 degrees Fahrenheit is 100.0 degrees Celsius
for an input of 212. If you are baffled by this instruction, here is a fuller description:
The first half of the output line ( 212 degrees Fahrenheit is ) is already written. The next item to be displayed is
the number of degrees celsius, which is being calculated and returned by the toCelsius method.
Remember (see Lecture 3 and preparation exercises) that the result of a return method can be used elsewhere in
a program by calling its name and providing the correct number and type of input parameters.
Call the toCelsius method within the System.out.println statement, sending it the data that it needs (the variable representing the degrees in fahrenheit).
Finish off the statement by concatenating the string " degrees Celsius" on the end.
This program should now compile. If you run it, it will convert one value from Fahrenheit to Celsius.
The code is below, can someone show me how to call the to toCelsius method. thanks
import java.util.Scanner;
/**Lab 4 COMP160 2020
* Starting code*/
public class FahrenheitToCelsius{
public static void main(String[]args){
convertFToC();
convertFToC();
convertFToC();
//Step 5;
}
/**gets input from user representing fahrenheit and displays celsius equivalent*/
public static void convertFToC(){
Scanner scan = new Scanner(System.in);
System.out.println("Enter Fahrenhei temperature: ");
double fahrenheit = scan.nextDouble(); //Step 2 - assign next double input from Scanner object
System.out.println(fahrenheit + " degrees Fahrenheit is " + + " degrees Celsius"); //Step 4
}
/**calculates and returns the celsius equivalent of a double input parameter called fahr*/
public static double toCelsius(double fahr){
int BASE = 32;
double CONVERSION_FACTOR = 9.0/ 5.0;
double celsius = CONVERSION_FACTOR + BASE / fahr;//Step 3
return celsius;
}
}// end class
Add toCelsius(fahrenheit) between those two consecutive +s. And also correct the conversion formula in the method
This program will calculate the amortization table for a user. The problem is my assignment requires use of subroutines. I totally forgot about that, any ideas on how to modify this to include subroutines?
public class Summ {
public static void main(String args[]){
double loanamount, monthlypay, annualinterest, monthlyinterest, loanlength; //initialize variables
Scanner stdin = new Scanner (System.in); //create scanner
System.out.println("Please enter your loan amount.");
loanamount = stdin.nextDouble(); // Stores the total loan amount to be payed off
System.out.println("Please enter your monthly payments towards the loan.");
monthlypay = stdin.nextDouble(); //Stores the amount the user pays towards the loan each month
System.out.println("Please enter your annual interest.");
annualinterest = stdin.nextDouble(); //Stores the annual interest
System.out.println("please enter the length of the loan, in months.");
loanlength = stdin.nextDouble(); //Stores the length of the loan in months
monthlyinterest = annualinterest/1200; //Calculates the monthly interest
System.out.println("Payment Number\t\tInterest\t\tPrincipal\t\tEnding Balance"); //Creates the header
double interest, principal; //initialize variables
int i;
/* for loop prints out the interest, principal, and ending
* balance for each month. Works by calculating each,
* printing out that month, then calculating the next month,
* and so on.
*/
for (i = 1; i <= loanlength; i++) {
interest = monthlyinterest * loanamount;
principal = monthlypay - interest;
loanamount = loanamount - principal;
System.out.println(i + "\t\t" + interest
+ "\t\t" + "$" + principal + "\t\t" + "$" + loanamount);
}
}
}
any ideas on how to modify this to include subroutines?
Well, you are better off doing it the other way around; i.e. working out what the methods need to be before you write the code.
What you are doing is a form or code refactoring. Here's an informal recipe for doing it.
Examine code to find a sections that perform a specific task and produces a single result. If you can think of a simple name that reflects what the task does, that it a good sign. If the task has few dependencies on the local variables where it currently "sits" that is also a good sign.
Write a method declaration with arguments to pass in the variable values, and a result type to return the result.
Copy the existing statements that do the task into the method.
Adjust the new method body so that references to local variables from the old context are replaced with references to the corresponding arguments.
Deal with the returned value.
Rewrite the original statements as a call to your new method.
Repeat.
An IDE like Eclipse can take care of much of the manual work of refactoring.
However, the real skill is in deciding the best way to separate a "lump" of code into discrete tasks; i.e. a way that will make sense to someone who has to read / understand your code. That comes with experience. And an IDE can't make those decisions for you.
(And did I say that it is easier to design / implement the methods from the start?)
I deleted my previous comment as I answered my own question by reading the associated tags :-)
As an example, define a method like this in your class:
public double CalculateInterest(double loanAmount, double interestRate) {
//do the calculation here ...
}
And then call the method by name elsewhere in your class code e.g.
double amount = CalculateInterest(5500, 4.7);
This question already has answers here:
How to get the user input in Java?
(29 answers)
Closed 6 years ago.
So I made a class that is supposed to calculate the number of beers needed to become intoxicated. My class receives User Input for the name of the beer, the alcohol content, and then the user's weight to make the calculation.
Here's my whole Beer class
public class Beer {
private String name;
private double alcoholContent;
//Default apple values (Constructors)
public Beer()
{
this.name = "";
this.alcoholContent = 0.0;
}
//Accessors
public String getName()
{
return this.name;
}
public double getAlcoholContent()
{
return this.alcoholContent;
}
//Mutators
public void setName (String aName)
{
this.name = aName;
}
public void setAlcoholContent (double aAlcoholContent)
{
if (aAlcoholContent < 0 || aAlcoholContent > 1)
{
System.out.println("That is an invalid alcohol content");
return;
}
this.alcoholContent = aAlcoholContent;
}
//Methods
public double Intoxicated (double aWeight)
{
double numberOfDrinks = (0.08 + 0.015) * aWeight / (12 * 7.5 * this.alcoholContent);
return numberOfDrinks;
}
This is specifically my intoxicatedmethod in the class (I think it's right):
public double Intoxicated (double aWeight)
{
double numberOfDrinks = (0.08 + 0.015) * aWeight / (12 * 7.5 * this.alcoholContent);
return numberOfDrinks;
}
This is what the output window is supposed to look like, receiving User Input for the weight and then performing the calculation to see how many beers it would take based on the user's input when previously defining two beers to be considered intoxicated:
What’s the weight of the person consuming said beverages?
185
It would take 3.166 "firstBeerName" beers to become intoxicated.
It would take 1.979 "secondBeerName" beers to become intoxicated.
The intoxicated formula was given to me, I don't know how to properly set up my class testing main method file which calls this class to reflect that output.
You need to write a testing class, that contains a main method. In the main method you can create several Beer-Objects.
By iterating over your Beers, you can get the wanted results.
Look here to get information about how to set up a main method.
Create an Array of Beer-Objects in that method with different alcohol content
Get the user input for the weight and then
Iterate over your Array, call intoxicated() and print the results
You are going to want to create a main method which does the following:
1) Prints the prompt for the beer values (name and % alcohol)
2) Takes in user input for those beer values
3) Prints the prompt for the user's weight
4) Takes in the user input for the weight
5) Calculates and prints the result
For printing prompts, you will most likely want to use System.out.println("Some prompt here!");
For taking input, you will most likely want to use a Scanner. You can search around on this website and others, as well as read the documentation, for how to take input with using that class.
Here is an example of a main method:
public static void main(String[] args) {
Beer blueMoon = new Beer("Blue Moon", 5.4);
Beer hoegaarden = new Beer("Hoegaarden", 4.9);
System.out.println("Enter your weight: ");
Scanner input = new Scanner();
Double weight = input.nextLine();
double value = beer1.Intoxicated(weight);
System.out.println("It would take " + value + " of " + blueMoon.getName() + " to become intoxicated.");
}
I would suggest renaming your Intoxicated method to intoxicated, as method names are generally camelCased in Java.
I am not going to give you the exact code because this seems like homework and I already graduated, but that should be enough to get you started. My advice would be to search around for any specific questions you come up with.
You can write a main method like this:
public static void main(String [ ] args)
{
Beer beer1 = new Beer().
beer1.setName("firstBeerName");
beer1.setAlcoholContent(3.166);
Scanner reader = new Scanner(System.in); // Reading from System.in
System.out.println("What’s the weight of the person consuming said beverages?");
double weight = reader.nextDouble();
double answer = beer1.Intoxicated(weight);
System.out.println("It would take "+answer+" "+beer1.getName()+" beers to become intoxicated.")
// similar for beer2
}
I would encourage you to throw IllegalArgumentException when checking condition in setter:
public void setAlcoholContent(double aAlcoholContent) {
if (aAlcoholContent < 0 || aAlcoholContent > 1) {
throw new IllegalArgumentException("Alcohol content can't be more than 1 or less than 0");
}
this.alcoholContent = aAlcoholContent;
}
And for your question you can test it like this:
public static void main(String[] args) {
List<Beer> beers = new ArrayList<>();
beers.add(new Beer("firstBeerName", 0.04));
beers.add(new Beer("secondBeerName", 0.06));
Scanner reader = new Scanner(System.in);
System.out.println("What’s the weight of the person consuming said beverages?");
double weight = reader.nextDouble();
DecimalFormat decimalFormat = new DecimalFormat("0.000");
for(Beer beer : beers){
System.out.println("It would take " + decimalFormat.format(beer.Intoxicated(weight)) + " " + beer.getName() +" beers to become intoxicated.");
}
}
Also you can use loop for creating new beers, just ask user for amount of beers that he can obtain result for, and then create for loop.
I am doing my first Java assignment and I'm struggling with an error here.
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package ctof;
/**
*
* #author Braydon
*/
import java.util.Scanner;
public class CtoF {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
System.out.println("Enter temperature in Celsius:");
Scanner temp = new Scanner(System.in);
String T = scan.nextLine();
T = (T - 32) * 5/9;
System.out.println("Temperature in Fahrenheit =" + T);
}
}
The error it gives me is as follows.
run:
Enter temperature in Celsius:
Exception in thread "main" java.lang.UnsupportedOperationException: Not supported yet.
at ctof.scan.nextLine(scan.java:19)
at ctof.CtoF.main(CtoF.java:21)
Java Result: 1
BUILD SUCCESSFUL (total time: 0 seconds)
The error is in the line where I perform the math, but I've tried everything and I can't seem to fix it. Please help!
You're calling the wrong function.
You need to call temp.nextLine() instead of scan.nextLine() in order to read the next line. (scan isn't even defined in the code you posted)
HOWEVER: You shouldn't use nextLine() when you need to read a number.
Therefore: Call temp.nextInt() or temp.nextDouble() instead.
I believe you are newbie to java. First of all, you will have to learn about the data types. Well, you can google basics about programming and learn from it.
The solution for your problem :
public class CtoF {
public static void main(String[] args) {
System.out.println("Enter temperature in Celsius:");
Scanner temp = new Scanner(System.in);
int T = temp.nextInt();
T = (T - 32) * 5 / 9;
System.out.println("Temperature in Fahrenheit =" + T);
}
}
Try to use good names for the variables (just a suggestion)
Now I have read and on this but i am just stuck. Any help appreciated. I am looking for hints. The code compiles and runs fine but I don't think the variables are being stored in the employee class and I am not sure I am understanding my use of the constructor right.
Requirements:
I have completed:
Values are checked to ensure they are
positive numbers.
Entering stop as the
employee name end program.
Having trouble on
Uses a class to store
name
hourly rate
hours worked
Use a constructor to initialize the employee information
and a method within that class to
calculate the weekly pay.
Here are a couple hints:
Use a constructor to initialize the
employee information
Looking at the provided code, there is a single constructor which takes no arguments and will initialize the fields of the object to zero.
Perhaps the "constructor to initialize the employee information" means that the constructor should be able to accept values which the Employee object should initlialize its fields to.
The Java Tutorials has a page on Providing Constructors for Your Classes with examples which should help in creating such constructor.
... and a method within that class to
calculate the weekly pay
This seems to say that there should be a method that is only visible to itself and not available from others in order to calculate the value for the weeklyPay field.
Again, from The Java Tutorials, Controlling Access to Members of a Class discusses show to change the visibility of methods.
Reading the contents of the assignment, it seems like taking a look at the Lesson: Classes and Objects of The Java Tutorials may be of use, as it provides some good examples and explanations on the concepts of object-oriented programming.
In addition to the fact that you haven't used the constructor to set your variables, as mentioned by others. The setter methods are performing no-ops. Which is why you aren't getting the results you expect. You are setting the local var to itself and not to the member var.
You need to either change your local var names, change the member var names, or change the setters to use the 'this' keyword
public void sethoursWorked(float hoursWorked)
{
this.hoursWorked = hoursWorked;
}
You'll notice that you are asked to make a class that stores the name, the hourly rate, and the hours worked, while you are asked to make a method that calculates the weekly pay. In other words, you should not have a weeklyPay instance variable. Whenever the user asks for the weekly pay (by means of your getWeeklyPay() method), you calculate and return it directly, without storing it in an instance variable.
Then, in order to actually use that result, you'll need to change this:
Employee.getweeklyPay();// Calculate weeklyPay ( hoursWorked * hourlyRate )
weeklyPay = ( hoursWorked * hourlyRate );
into something like this:
weeklyPay = employee.getWeeklyPay();
If you don't actually assign the result of your method to some variable, you can't use the result.
The final answer from the OP:
/** Payroll3.java | Due 8/09/09
** IT 2015 Java Programming | lazfsh | Axia College - University of Phoenix */
import java.util.Scanner;// Import and use scanner
public class Payroll3 {// main method begins
public static void main( String args[] ) {
// Initialize
boolean stop = false;// Variable for exit procedure
String endProgram = "";// Variable to explain exit procedures blank 1st time
int version = 3;// Version number
// Welcome message
System.out.printf(
"\nWelcome to the Payroll Program v.%d\n", version );//Welcome message
while ( stop == false) {// Run program until stop equals true
Scanner input = new Scanner( System.in );// new Scanner for CL input
Employee Employee = new Employee(); // new Employee constructor
// Prompt for and input name
System.out.printf( "\nEnter name of the employee%s:", endProgram );
Employee.setempName(input.nextLine());// Accept input & Store
if ( Employee.getempName().equals( "stop" )) {// If = end program w/message
System.out.printf( "\n%s\n%s\n\n", "....", "Thanks for using Payroll Program");
stop = true;}
else{// Continue retrieve hourlyRate, hoursWorked & Calculate
do {// Prompt for and input hourlyRate
System.out.printf( "\n%s", "Enter hourly rate: $" );
Employee.sethourlyRate(input.nextFloat());// Accept input & Store
if ( Employee.gethourlyRate() < 1 ) {// Show error for negative #
System.out.printf( "%s", "Enter a positive number.");}
else;{}// Continue
} while ( Employee.gethourlyRate() < 1 );// End loop if positive number recieved
do {// Prompt for and input hoursWorked
System.out.printf( "\n%s", "Enter number of hours worked:" );
Employee.sethoursWorked(input.nextFloat());// Accept input & Store
if ( Employee.gethoursWorked() < 1 ) {// Show error for negative #
System.out.printf( "%s", "Enter a positive number.");}
else;{}// Continue
} while ( Employee.gethoursWorked() < 1 );// End loop if positive number recieved
// Display formatted results
System.out.printf( "\n%s's weekly pay is $%,.2f\nHourly rate ($%,.2f) multiplied by hours worked (%.0f)\n\n...Ready for next employee.\n\n",
Employee.getempName(), Employee.getweeklyPay(), Employee.gethourlyRate(), Employee.gethoursWorked() );
// Debug Line Employee.showVariables();
}// end retrieve hourlyRate, hoursWorked & Calculate
endProgram = ( ", \n(Or type \"stop\" to end the program)" );//explain exit procedure on second empName prompt
}// ends program when stop equals true
}// end method main
}//end class Payroll3
Employee class
/** Employee Class | Initializes and storeds data for employee
Also provides method to calculate weekly pay.
*/
// Import statements
import java.util.Scanner;// Import and use scanner
public class Employee {//Begin Employee class
Scanner input = new Scanner( System.in );// new Scanner for CL input
// Declare instance variables
String empName; // Declare name as string
float hourlyRate; // Declare hourlyRate as float
float hoursWorked; // Declare hoursWorked as float
// constructor initializes employee information
public Employee() { // Initialize (clear) instance variables here
empName = "";
hourlyRate = 0;
hoursWorked = 0;
} // end constructor
// Begin methods
public void setempName(String empName) {// public method to set the employee name
this.empName = empName;}// end method setempName
public String getempName() {// public method to get the employee name
return empName;}// end method getempName
public void sethourlyRate(float hourlyRate) {// public method to set the hourly Rate
this.hourlyRate = hourlyRate;}// end method set hourly Rate
public float gethourlyRate() {// public method to retrieve the hourly Rate
return hourlyRate;} // end method get hourly Rate
public void sethoursWorked(float hoursWorked) {// public method to set the hours Worked
this.hoursWorked = hoursWorked;} // end method set hours Worked
public float gethoursWorked() {// public method to retrieve the hours Worked
return hoursWorked;} // end method get hours Worked
public float getweeklyPay() {// public method to retrieve weekly Pay
return ( hoursWorked * hourlyRate );}// end method get weeklyPay
/* Test line
public void showVariables(){
System.out.printf( "empName=%s, hourlyRate=%s, hoursWorked=%s", this.empName, this.hourlyRate, this.hoursWorked );} */
} // end class Employee