In my code below double getAirSpeed double calcPatternwidth and double calcPatternLength are not being initialized properly, why?
/**
* holding patterns
* assignment 1
* question 2
**/
import java.util.Scanner;
public class StockiColeA1Q2 {
public static void main(String []args) {
Scanner keyboard = new Scanner(System.in);
double getAirSpeed ;
double calcPatternWidth;
double calcPatternLength;
System.out.println("That speed is " + getAirSpeed +
"\nHolding pattern width: " + calcPatternWidth +
"kms\nHolding pattern length: " + calcPatternLength + "kms");
}//main
public static double getAirSpeed() {
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter the speed in Knots: ");
double knots = keyboard.nextDouble(); //knots given by user
return knots*1.852;
}//get air speed
public static double calcPatternWidth(double knots) {
return (knots/60*Math.PI)*2;
}//patern width
public static double calcPatternLength(double knots) {
return knots/60 + (knots/60*Math.PI)*2;
}//pattern width
}//class
You aren't properly initializing the variables in main. You show call the functions and assign them up front and then display them. I think what you were looking for was a main that looked liked this:
public static void main(String[] args) {
double getAirSpeed = getAirSpeed();
double calcPatternWidth = calcPatternWidth(getAirSpeed);
double calcPatternLength = calcPatternLength(getAirSpeed);
System.out.println("That speed is " + getAirSpeed + "\nHolding pattern width: " + calcPatternWidth
+ "kms\nHolding pattern length: " + calcPatternLength + "kms");
}// main
The code above uses the getAirSpeed as a parameter to calcPatternWidth and calcPatternLength. I am guessing that was what you intended to accomplish.
You really should close the Scanner object when finished so I'd amend getAirSpeed() to call keyboard.close() before returning.
public static double getAirSpeed() {
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter the speed in Knots: ");
double knots = keyboard.nextDouble(); // knots given by user
keyboard.close();
return knots * 1.852;
}// get air speed
Here I am not able to see where you are initializing the given variables. As all three vairables are local to main method so compiler will not assign the default value to them. just creating getter of those variable will not assign the value. If you create the variable out side the main method in class the compiler will assign the defaut value but you have to make them static as main method is static and you cannot use non-static variable inside the static block.
Related
I am trying to make an area calculator in Java that will calculate the area of a triangle based on given dimensions by the user. I can get the user to select the triangle option from a menu and enter their dimensions but when I try to use a method to calculate the area, it only prints out 0.0.
{
Scanner tbaseChoice = new Scanner(System.in);
System.out.println("What is the base?");
double selectionb = tbaseChoice.nextDouble();
tbaseChoice.equals(Tbase);
Scanner theightChoice = new Scanner(System.in);
System.out.println("What is the height?");
double selectionh = theightChoice.nextDouble();
theightChoice.equals(Theight);
System.out.println("BASE:" + selectionb + " " + "HEIGHT:" + selectionh);
//tbaseChoice.equals(Tbase);
//theightChoice.equals(Theight);
}
public static void calculateArea() {
double triangleArea = Theight * Tbase;
System.out.print("Area=" + triangleArea);
}
The problem is that you shouldn't be using the equals method of the Scannerclass to assign values to the Theight and Tbase variables. You should instead be using the = assignment operator to do so instead. So replace theightChoice.equals(Theight); with
Theight = selectionh;
and tbaseChoice.equals(Tbase); with
Tbase = selectionb;
Why your code wasn't working before can be seen from this link, https://docs.oracle.com/javase/7/docs/api/java/lang/Object.html#equals(java.lang.Object)
The equals method in the Scanner class is inherited from Java's Object class, which simply just returns a boolean. In your code before, you were checking to see if a Scanner object was equal to another object, but nothing was being done with the boolean value returned. Therefore, your Tbase and Theight variables weren't changing.
You can try with these code. Maybe this will help you
public class AreaCalculator {
static double base=0.0;
static double height=0.0;
public static void main(String args[]){
//Scanner object for input
Scanner scanner=new Scanner(System.in);
System.out.println("What is the base?");
base=scanner.nextDouble();
System.out.println("What is the height?");
height=scanner.nextDouble();
System.out.println("BASE:" + base + " " + "HEIGHT:" + height);
System.out.println("Area is: "+triangleArea());
}
public static double triangleArea(){
return (.5*base*height);
}
}
I'm beginning to learn more about Java and I'm trying to code a Gratuity calculator that takes user Input, and shows how much a tip would be at %10 and %20 of the total. I'm getting a single "Cannot make a static reference to the non-static method" error that I can't resolve.
Gratuity class:
public class Gratuity{
//variables
private double total = 0;
private double grat1 = 0;
private double grat2 = 0;
public Gratuity(float value){
total = value;
}
start getters and setters
public double getTotal() {
return total;
}
//method to do the calculations
public void calcGrat(){
grat1 = total * .10;
grat2 = total * .20;
}
public double getGrat1(){
return grat1;
}
}
And the class with the main method:
import java.util.InputMismatchException;
import java.util.Scanner; //import package to use the scanner input function
//TestGrat main class contains method
public class TestGrat {
Scanner keyboard = new Scanner(System.in);
//method to prompt user for total, double is total
public void askForInput(){
try{
System.out.println("Enter the total amount of your bill");
total = keyboard.nextDouble();
}
catch(InputMismatchException e){
System.err.printf("Error, please try again. Program will now close");
System.exit(0);
}
}
public Scanner getKeyboard() {
return keyboard;
}
public void setKeyboard(Scanner keyboard) {
this.keyboard = keyboard;
}
//main method
public static void main(String[] args){
// asks for input in float form
float value = askForInput();
//Creating the gratCalc object and storing value as a float (total)
Gratuity gratCalc = new Gratuity(value);
// get the total value and set as float
float tot = (float)gratCalc.getTotal();
// converting the float value into string
System.out.println("You have entered: " + Float.toString(tot));
gratCalc.calcGrat(); //sets grat
// Displaying the options to user
System.out.println("Below are the tips for %10 as well as %20 ");
//getting the value and then displaying to user with toString
float getNum = (float) gratCalc.getGrat1();
float getNum1 = (float) gratCalc.getGrat2();
// using the value of getNum as float to put into toString
System.out.println( "For %10: " + Float.toString(getNum));
System.out.println(" For %20: " + Float.toString(getNum1));
}
}
Any help would be appreciated. Thanks!
askForInput() is inside your class TestGrat. However, in main() you are calling it directly, as if it was static. You probably meant:
TestGrat test = new TestGrat();
float value = test.askForInput();
askForInput() is also returning void, so you probably want to fix that too.
I'm kinda new to to java and stumbled on a problem that needs me to do currency conversion declaring different methods for:
getting amount, getting conversion rate, doing the actual conversion and printing the outcome of the conversion
import java.util.*;
public class Conver {
public static void main(String[] args){
amountToConvert();
exchangeRate();
convert();
}
public static double amountToConvert() {
Scanner input = new Scanner(System.in);
System.out.println("Enter the amount you wish to convert...");
double amount = input.nextDouble();
return amount;
}
public static double exchangeRate(){
Scanner input = new Scanner(System.in);
System.out.println("Enter the currency you wish to convert from... ");
String initialCurrency = input.next();
System.out.println("Enter the currency you wish to convert from... ");
String finalCurrency = input.next();
System.out.println("How many " + initialCurrency + " makes one " + finalCurrency + "?");
double rate = input.nextDouble();
return rate;
}
public static double convert(){
int x = amount*rate;
return x;
}
public void printResult(){
System.out.println(x);
}
}
Learn to use parameters in the methods. Change the convert() method so that it looks like this:
public static double convert(double amount, double rate){
int x = amount*rate;
return x;
}
In the method above, double amount and double rate are the parameters. Use variables to help pass in parameters to convert() in the main method:
public static void main(String[] args){
double amount1 = amountToConvert();
double rate1 = exchangeRate();
double result = convert(amount1, rate1);
printResult(result);
}
Hope this helps!
Pass returned values to the method convert:
import java.util.*;
public class Conver {
public static void main(String[] args){
double amount = amountToConvert();
double rate = exchangeRate();
double result = convert(amount, rate);
printResult(result);
}
public static double amountToConvert() {
Scanner input = new Scanner(System.in);
System.out.println("Enter the amount you wish to convert...");
double amount = input.nextDouble();
return amount;
}
public static double exchangeRate(){
Scanner input = new Scanner(System.in);
System.out.println("Enter the currency you wish to convert from... ");
String initialCurrency = input.next();
System.out.println("Enter the currency you wish to convert from... ");
String finalCurrency = input.next();
System.out.println("How many " + initialCurrency + " makes one " + finalCurrency + "?");
double rate = input.nextDouble();
return rate;
}
public static double convert(double amount, double rate){
double x = amount * rate;
return x;
}
public void printResult(double x){
System.out.println(x);
}
}
Also, don't use double for money!
First off, you need to change the "receiving method" so that it takes an argument. A method like:
public static double convert() {}
that needs to take in a value for amount and rate, needs to have those added to the method signature:
public static double convert (double amount, double rate) {}
Putting the two comma separated values inside of the parens means that this method takes two values, doubles, as arguments. This makes those values available to use inside of that method.
Now that you have a method that can take the required arguments, you need to actually use that method in your code. When calling this method, you start out the same as with others:
convert(
but then you need to add in the arguments you are using:
double amount = amountToConvert();
double rate = exchangeRate();
convert(rate, amount);
If you want to avoid creating those two additional variables in main(), you can actually call those methods inside of your new method:
convert(amountToConvert(), exchangeRate());
I am currently learning about methods and using methods. It sometimes confuses my mind when deciding what to put inside the parameters. I have some code where I created three methods and all correspond. What I must do for this program is to display some services and prices and ask the user if he/she would like it. If they say yes, the prices add up until the end of the array. The part I am having trouble with is how to take in the price from main in my third method. I know that I should use a void method because I am not returning anything, just printing out the prices to the user.
Heres my piece of code for this program:
static Scanner keyboard = new Scanner(System.in);
public static void main(String[] args) {
System.out.println("What automobile make do you own?");
Scanner keyboard = new Scanner(System.in);
String name = keyboard.nextLine();
make(name);
double price = carMaintenance(name);
finalPrice(price);
}
// First Method
public static void make(String name) {
System.out.println("Hello! We will be happy to service your " + name
+ " automobile today!");
}
// Second Method
public static double carMaintenance(String name) {
String[] services = { "Oil Change", "Tire Rotation", "Air Filter",
"Check Fluids" };
double[] prices = { 39.99, 49.99, 19.99, 10.99 };
double Total = 0;
for (int i = 0; i < services.length; i++) {
System.out.println("Do you want a " + services[i] + " for your "
+ name + " " + prices[i] + "? (y/n)");
String answer;
answer = keyboard.nextLine();
if (answer.equals("y"))
{
Total = Total + prices[i];
}
// Third method
public static void finalPrice ( ? )
Specifically this the part I am having trouble with:
// Third method
public static void finalPrice (double price )
The problem is finalPrice is an invalid type for the variabl which is pretty confusing about.
You have to change finalPrice() to accept a double parameter:
public static void finalPrice(double price) { ... }
And pass the value returned by carMaintenance() to finalPrice():
double price = carMaintenance(name);
finalPrice(price);
Note I am assuming you just forgot to paste the rest of the carMaintenance() method. In the end, of course, it should have the return Total statement.
Your second method is lacking a return statement. You can return the total to main and then send it to your third method, as such:
public static void main(String[] args) {
System.out.println("What automobile make do you own?");
Scanner keyboard = new Scanner(System.in);
String name = keyboard.nextLine();
make(name);
double finalPrice = carMaintenance(name);
printFinalPrice(finalPrice);
}
//first method code here
public static double carMaintenance(String name) {
//second method code here, plus:
return total;
}
// Third method
public static void printFinalPrice(double finalprice) {
System.out.println("Your final price is " + finalprice);
}
Pass double from carMaintance to finalPrice
double finalPriceDbl = carMaintenance(name);
finalprice(finalPriceDbl);
and accept double as parameter in finalPrice
public static void finalPrice ( double finalPrice );
also you should return value from carMaintenance with return statemenet
return Total;
I'm making an BMI calculator for a diet programming I'm making for a piece of coursework. Originally I was making a a couple variables public static to get variables from another class. My BMI calculator worked fine this way.
I then figured out that I could use a get method (for more marks). So I changed by the previous variables to private and used a get method. But when I run this program I get NaN when the program prints out the the variable that holds the BMI, this never happened before!
Can anyone help?
import java.util.Scanner;
public class Weight {
private Scanner input;
private String readInput;
private String userWeightIsPounds;
private String userWeightIsStones;
private Scanner input2;
public static double userWeight;
public Weight(){
userWeightIsPounds = ("Pounds");
userWeightIsStones = ("Stones");
}
public void findOutUserWeightMessage(){
System.out.println("Firstly Do you weigh yourself in pounds or stones?");
}
public void findOutUserWeight(){
input = new Scanner (System.in);
readInput = input.nextLine();
if(readInput.equals(userWeightIsPounds)){
System.out.println("Ok then, enter your weight in pounds please.");
}
if(readInput.equals(userWeightIsStones)){
System.out.println("Ok enter your weight in stones please.");
}
input2 = new Scanner (System.in);
userWeight = input2.nextFloat();
if (userWeight > 20){
System.out.println("You've enetered your weight as " + userWeight + " lbs. I'll save that information for later.");
}else{
userWeight = userWeight * 14;
System.out.println("I've converted your weight into pounds for you. You weigh " + userWeight + " lbs. I'll save that information for later.");
}
}
public double static getUserWeight(){
return userWeight;
}
}
And there is come code the the class that does the calculations. Ignore some of the println's I was trying to find out what was happening with my variables.
public class BMI {
private double userHeightSqaured;
private double bmiMutiplier;
private double weightDivideHeight;
private double userBmi;
private double userWeightBmi;
private double userHeightBmi;
BMI(){
bmiMutiplier = 703;
userWeightBmi = Weight.getUserWeight();
userHeightBmi = Height.getUserHeight();
}
public void startUpBmiMessage(){
System.out.print("Lets start with your BMI then shall we? ");
}
public void calculateUserBmi(){
System.out.println("userWeightBmi is " + userWeightBmi);
System.out.println("userWeightBmi is " + userHeightSqaured);
userHeightSqaured = userHeightBmi * userHeightBmi;
System.out.println("userHeightSqaured is " + userHeightSqaured);
weightDivideHeight = userWeightBmi/userHeightSqaured;
System.out.println("weightDivideHeight is " + weightDivideHeight);
userBmi = weightDivideHeight * bmiMutiplier;
System.out.println("weightDivideHeight is " + weightDivideHeight);
System.out.println("bmiMutiplier is " + bmiMutiplier);
}
public void calculateUserBmiMessage(){
System.out.println("Your bmi is " + userBmi);
}
}
It sounds like you're trying to write a Java program that performs some calculations, and the result of your calculation is NaN - you can refer to the question In Java, what does NaN mean? for some info on NaN.
As for resolving your problem without seeing any code, and assuming your calculation worked fine with the same input before, it sounds like your switch from public static variables to private ones with getters has probably left some of your variables uninitialized, so their value defaults to 0 - Division by 0 is a common cause of NaN.
The reason for the NaN is that this statement:
weightDivideHeight = userWeightBmi/userHeightSqaured;
divided zero by zero. In other words userWeightBmi and userHeightSqaured were both zero at that point.
The root problem seems to be that you haven't got your head around the difference between static and instance variables. And when you should / should not use the two kinds of variable.