I am a complete beginner with java and coding altogether and am trying to make a program that solves two equations based on what a user has inputted into the program. I've tried changing the variable types to long, int, double, but nothing changes. The result is always 0 or 0.0 Any help would be much appreciated.
package pa2;
import java.util.Scanner;
public class GravitationalForce
{
public static void main(String[] args)
{
System.out.println("Please enter the name of the planet and its weight in quintillion kilograms");
Scanner myScanner = new Scanner (System.in);
String planetName = myScanner.next();
int planetWeight = myScanner.nextInt();
System.out.println("Enter the weight of the person in kilograms");
double personWeight = myScanner.nextDouble();
System.out.println("Please enter the radius of the planet Alderaan in million meters");
double planetRadius = myScanner.nextDouble();
Long gravitationalConstant = (long) (6.673*Math.pow(10,-11));
Double force = gravitationalConstant*(planetWeight*Math.pow(10, 18)*personWeight)/planetRadius*Math.pow(10, 6)*planetRadius*Math.pow(10, 6);
Double gravity = gravitationalConstant*(planetWeight*Math.pow(10, 18)/planetRadius*Math.pow(10, 6)*planetRadius*Math.pow(10, 6));
System.out.println("The gravitational force of planet " + planetName + " on the person is " + force + " Newtons");
System.out.println("The gravity of the planet " + planetName + " is " + gravity + " meters per second squared");
}
}
6.673*Math.pow(10,-11) is < 1, so if you cast it to long, it becomes 0.
change
Long gravitationalConstant = (long) (6.673*Math.pow(10,-11));
to
double gravitationalConstant = 6.673*Math.pow(10,-11);
Related
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 2 years ago.
Improve this question
I am new to java and cannot figure out how to work the copy constructors. Please bear with me.
I am trying to get information for shipping packages. I am trying to use the copy constructor to repeat the enter shipping details section.
I honestly have no idea what to do with it. The code works fine for one package and there are no errors - I just need to figure out how to prompt a user for a second package.
import java.util.Scanner;
public class Package {
private static double length = 1.0;
private static double width = 1.0;
private static double height = 1.0;
private static double sum1 = length+width+height;
public Package(Package p) {
this.height = p.height;
this.length = p.length;
this.width = p.width;
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter package dimensions.\nEnter Length: ");
length = input.nextDouble();
System.out.println("\nEnter Width: ");
width = input.nextDouble();
System.out.println("\nEnter Height: ");
height = input.nextDouble();
System.out.println("Package 1: " + length + " X " + width + " X " + height + ", Volume = " + sum1);
}
}
I think your misunderstanding is in this line:
private static double sum1 = length+width+height;
This computation will be executed at the moment the runtime executes this line so when the class is loaded (so length=1.0, width=1.0, height=1.0).
If you want the sum to be calculated after you have set the length, width and height, you have to put the calculation in a method:
public static double sum() {
return length+width+height;
}
And in your last line call this method:
System.out.println("Package 1: " + length + " X " + width + " X " + height + ", Volume = " + sum())
Also notice that all your variables are static so you don't really use the Package as an object. For simplicity you can remove the constructor except if you want to learn about java objects but then you have to adapt more code.
UPDATE: this works but to be able to use the copy constructor I each time have to create 2 objects. Speaking of overhead.
Mathimatics: it is not sum but product for volumes.
import java.util.Scanner;
public class Package {
double length=1.0;
double height=1.0;
double width=1.0;
double sum;
public Package() {
}
public Package (Package p)
{
this.length = p.length;
this.height = p.height;
this.width = p.width;
// to calculate the volume it's more like a product then a sum
sum=length*height*width;
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
for (int i=0;i<5;i++)
{
Package pack=new Package();
System.out.println("Enter package dimensions.\nEnter Length: ");
pack.length = input.nextDouble();
System.out.println("\nEnter Width: ");
pack.width = input.nextDouble();
System.out.println("\nEnter Height: ");
pack.height = input.nextDouble();
Package p=new Package(pack);
System.out.println("Package 1: " + p.length + " X " + p.width + " X " + p.height + ", Volume = " + p.sum);
}
}
}
You can use do-while for this .. something like below
Scanner input = new Scanner(System.in);
int i=0;
do{
Package package =new Package();
System.out.println("Enter package dimensions.\nEnter Length: ");
package.length = input.nextDouble();
System.out.println("\nEnter Width: ");
package.width = input.nextDouble();
System.out.println("\nEnter Height: ");
package.height = input.nextDouble();
System.out.println("Package : " + package.length + " X " + package.width + " X " + package.height + ", package.Volume = " + sum1);
i++;
}while ( i<=5);
I'm trying to Make two calls to a second return method which takes in one parameter ( my value in inches) and prints the value in centimeters but its not working! What did I do wrong?`
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
// prompt the user and get the value
System.out.print("Exactly how many inches are you? ");
int uHeight = in.nextInt();
// converting and outputing the result
System.out.print("How many inches is your mother? ");
int mHeight = in.nextInt();
InchesToCm(mHeight,uHeight);
}
public static double InchesToCm() {
Scanner in = new Scanner(System.in);
System.out.print("Exactly how many inches are you? ");
int inHeight = in.nextInt();
double cmHeight = inHeight * 2.54;
System.out.println("He's " + uHeight + " inches or " + mHeight + " cm.");
return
You should to pass your mHeight and uHeight, in your method because you call it in your main method like this InchesToCm(mHeight,uHeight); so your method should look like this:
public static double InchesToCm(int mHeight, int uHeight) {//pass your values in method
Second you have to return the result in the end :
return cmHeight;//return the result
Note
For the good practice your methods should start with a lowercase letter like #Timothy Truckle said in comment and your class names should start with an upper letter
EDIT
For the good practice your have to use :
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Exactly how many inches are you? ");
int uHeight = in.nextInt();
System.out.println("He's " + uHeight + " inches or " + inchesToCm(uHeight) + " cm.");
System.out.print("How many inches is your mother? ");
int mHeight = in.nextInt();
System.out.println("He's " + mHeight + " inches or " + inchesToCm(mHeight) + " cm.");
//------------------------------^^-------------------------------^^------------------
in.close();//close your Scanner
}
//Your function should take inches and return cm
public static double inchesToCm(int height) {
return height * 2.54;
}
I have been trying to make a simple program in eclipse for a school project, but I keep getting this after I enter my interest rate. I am relatively new to coding and programming in general, and java is new to me as of this month so any help is appreciated. The code is this:
import java.util.Calendar;
import java.util.Locale;
import java.util.Scanner;
public class Interest {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner in = new Scanner(System.in);
//Input ============================
System.out.println("Initial loan total:"); //cost
String cost;
cost = in.nextLine();
System.out.println("Down payment:"); //down
String down;
down = in.nextLine();
System.out.println("Length of term:"); //term
String term;
term = in.nextLine();
System.out.println("Interest rate (decimal form):"); //rate
String rate;
rate = in.nextLine();
int principle1 = Integer.parseInt(cost) - Integer.parseInt(down);
String hundred;
hundred = "100";
int interest = Integer.parseInt(rate) * Integer.parseInt(hundred);
//Output ===========================
Calendar c = Calendar.getInstance();
System.out.format("%tB %td, %tY", c,c,c);
System.out.println("");
System.out.println("The initial cost of the loan is $" + cost);
System.out.println("The down payment is $" + down);
System.out.println("The principle is $" + principle1);
System.out.println("The term is " + term + " months");
System.out.println("The interest rate is " + interest + "%");
System.out.println("The monthly patments are $");
in.close();
}
}
When I run the program it lets me put in the initial loan, down payment and length of term but as soon as I put in 0.06 for the interest rate it gives me the error message. I would also like to point out that I have a limited understanding of how the math in my code works.
the problem is that you are trying to parse 0.06 to Integer and 0.06 is float.
use Float.parseFloat(rate); and your interest should be a float too float interest
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 have the following code (I'm not very computer literate so be gentle) that the user is supposed to be able to enter individual coin amounts and the program will tell the user how much money they have in said coin amounts.
import java.util.*;
public class Coins {
public static final Scanner CONSOLE = new Scanner(System.in);
public static void main(String[] args) {
System.out.println ("Lab 2 by Maria T Williams\n");
quarterAmount( );
dimeAmount( );
nickelAmount( );
pennyAmount( );
}
public static void quarterAmount( ) {
System.out.print("Enter the number of quarters: ");
int quarterNumber = CONSOLE.nextInt( );
double amount = quarterNumber * 0.25;
System.out.print(quarterNumber + " You have $" + amount);
System.out.println(" worth of quarters.");
}
public static void dimeAmount( ) {
System.out.print("Enter the number of dimes: ");
int dimeNumber = CONSOLE.nextInt( );
double amount = dimeNumber * .10;
System.out.print(dimeNumber + " You have $" + amount);
System.out.println(" worth of dimes.");
}
public static void nickelAmount( ) {
System.out.print("Enter the number of nickels: ");
int nickelNumber = CONSOLE.nextInt( );
double amount = nickelNumber * 0.05;
System.out.print(nickelNumber + " You have $" + amount);
System.out.println(" worth of nickels.");
}
public static void pennyAmount( ) {
System.out.print("Enter the number of pennies: ");
int pennyNumber = CONSOLE.nextInt( );
double amount = pennyNumber * 0.01;
System.out.print(pennyNumber + " You have $" + amount);
System.out.println(" worth of pennies.");
}
}
If I enter an amount that has a number in the 100s place that isn't "0" I'm fine. But if I enter, say, two quarters I get back "$0.5" instead of "$0.50".
You could use a DecimalFormat to force the number to be formatted as you'd like it. E.g.:
DecimalFormat df = new DecimalFormat("#.00");
double amount = dimeNumber * .10;
System.out.print(dimeNumber + " You have $" + df.format(amount) + " worth of dimes.");
When outputting the result of your calculation, you can use a DecimalFormat like this:
DecimalFormat f = new DecimalFormat("#0.00");
System.out.println(f.format(dimeNumber));