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.
Related
I wanted to write a program that records bar inventory as I'm a bartender. I can't figure out how to pass the liquorCost and liquorCount data to the GetCostTotal() method below the main() method. I'm absolutely sure it's something fairly straightforward that I'm doing incorrectly but I just can't figure it out. Any help is appreciated.
My Liquor class is separate and I can post that if necessary but I don't think it's the class that's giving me the problem, it's retrieving the data input from the array to the separate method.
package inventory;
import java.util.Scanner;
public class Inventory {
public static void main(String[] args) {
System.out.println("How many bottles are you taking inventory of?: ");
Scanner keyboard = new Scanner(System.in);
int size = keyboard.nextInt();
Liquor[] inv = new Liquor[size];
for (int i = 0; i < inv.length; i++) {
inv[i] = new Liquor();
System.out.println("Enter product name: ");
inv[i].setLiquorName(keyboard.next());
System.out.println("Enter the count for the product: ");
inv[i].setLiquorCount(keyboard.nextDouble());
System.out.println("Enter the cost for the product: ");
inv[i].setLiquorCost(keyboard.nextDouble());
}
System.out.println("The sitting inventory cost of these products is: ");
//double totalCost = 0
for (Liquor inv1 : inv) {
System.out.println(inv1.getLiquorName() + ": $" + inv1.getLiquorCost() * inv1.getLiquorCount());
}
double costTotal = GetCostTotal(Liquor[] inv, double liquorCost, double liquorCount);
System.out.println("The total cost of the inventory is: "
+ costTotal);
System.exit(0);
}
public static double GetCostTotal(Liquor[] inv, double liquorCost, double liquorCount) {
double costTotal = 0;
for ( int i = 0; i < inv.length; i++) {
costTotal += (liquorCost * liquorCount);
}
return costTotal;
}
}
try this
public static void main(String[] args) {
System.out.println("How many bottles are you taking inventory of?: ");
Scanner keyboard = new Scanner(System.in);
int size = keyboard.nextInt();
Liquor[] inv = new Liquor[size];
for (int i = 0; i < inv.length; i++) {
inv[i] = new Liquor();
System.out.println("Enter product name: ");
inv[i].setLiquorName(keyboard.next());
System.out.println("Enter the count for the product: ");
inv[i].setLiquorCount(keyboard.nextDouble());
System.out.println("Enter the cost for the product: ");
inv[i].setLiquorCost(keyboard.nextDouble());
}
System.out.println("The sitting inventory cost of these products is: ");
//double totalCost = 0
for (Liquor inv1 : inv) {
System.out.println(inv1.getLiquorName() + ": $" + inv1.getLiquorCost() * inv1.getLiquorCount());
}
double costTotal = GetCostTotal(inv);
System.out.println("The total cost of the inventory is: "
+ costTotal);
System.exit(0);
}
public static double GetCostTotal(Liquor[] inv) {
double costTotal = 0;
for ( int i = 0; i < inv.length; i++) {
costTotal += (inv[i].getLiquorCost() * inv[i].getLiquorCount());
}
return costTotal;
}
Lets understand what went wrong here.Take a look at how you are trying to call the GetCostTotal() method.
double costTotal = GetCostTotal(Liquor[] inv, double liquorCost, double liquorCount);
This is incorrect. The syntax/way you are calling the method is actually used when we what to define a method. Like you did:
public static double GetCostTotal(Liquor[] inv, double liquorCost, double liquorCount) {}
Your call should be like:
double costTotal = GetCostTotal(inv);
Here, we are passing only inv because the data for liquorCost and liquorCount is available inside "each" element of array inv.
Now you can accept this argument in GetCostTotal method. Here as you are iterating using a for loop, you can read the data you needed as inv[i].getLiquorCost() and inv[i].getLiquorCount().
I suggest you can read more on defining a method and calling a method in java.
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;
}
This question already has answers here:
Division of integers in Java [duplicate]
(7 answers)
Closed 7 years ago.
I am trying to find the average number of students per class but when I test my program, it only prints 1 or 0 everytime. Any help would be appreciated.
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
System.out.println("Please enter the number of Students: ");
int s = reader.nextInt();
System.out.println("Please enter the number of classes: ");
int c = reader.nextInt();
int numbStud1 = 0;
int numbClass1 = 0;
double averages =calcAverage (numbStud1 + c,numbClass1 + s) ;
System.out.println("The average is: " + averages);
}
public static double calcAverage(int numbStud, int numbClass){
double average1;
average1 = numbStud / numbClass;
return average1;
}
}
The issue is this:
double averages =calcAverage (numbStud1 + c,numbClass1 + s) ;
Replace it with exchanging c with s:
double averages =calcAverage (numbStud1 + s,numbClass1 + c) ;
And if you want avrage more precision use :
average1 = (numbStud*1.0 / numbClass*1.0);
Write a class called Average that can be used to calculate average of several integers. It should contain the following methods:
A method that accepts two integer parameters and returns their average.
A method that accepts three integer parameters and returns their average.
A method that accepts two integer parameters that represent a range. Issue an error message and return zero if the second parameter is less than the first one. Otherwise, the method should return the average of the integers in that range (inclusive).
I am totally new to Java and programming, this has me completely lost! Here's what I've tried.
import java.util.Scanner;
public class Average {
public static void main(String[] args) {
double numb1, numb2, numb3;
System.out.println("Enter two numbers you'd like to be averaged.");
Scanner keyboard = new Scanner(System.in);
numb1 = keyboard.nextInt();
numb2 = keyboard.nextInt();
}
public double average (int num1, int num2) {
return (num1 + num2) / 2.0;
}
public double average (int num1, int num2, int num3)
{
return (num1 + num2 + num3) / 3.0;
}
}
The program doesn't go past getting the values from the user. Please help!
You have to actually call your methods.
Just place
Average avg = new Average();
System.out.println("The average is: " + avg.average(numb1, numb2));
at the end of your main method.
Alternatively you can make the methods static:
public static double average (int num1, int num2) {
return (num1 + num2) / 2.0;
}
More info on constructors and static.
It looks like your not actually printing out the results. Try the following.
System.out.print(average(numb1, numb2));
Let's detail what you did there.
public static void main(String[] args) {
//Create variables numb1, numb2 & numb3
double numb1, numb2, numb3;
System.out.println("Enter two numbers you'd like to be averaged.");
//Read standard input (keyboard)
Scanner keyboard = new Scanner(System.in);
//Retrieve first input as an int
numb1 = keyboard.nextInt();
//Retrieve second input as an int
numb2 = keyboard.nextInt();
}
Then your two next methods compute for two or three given integers their average.
The main method is the first method called during your program execution. The jvm will execute everything inside. So it will declare the three doubles, read two values from keyboard and then end.
If you want to compute the average of numb1 & numb2 using your method, you have to create an object Average and call your average method like this
public static void main(String[] args) {
//Create variables numb1, numb2 & numb3
double numb1, numb2, numb3;
System.out.println("Enter two numbers you'd like to be averaged.");
//Read standard input (keyboard)
Scanner keyboard = new Scanner(System.in);
//Retrieve first input as an int
numb1 = keyboard.nextInt();
//Retrieve second input as an int
numb2 = keyboard.nextInt();
//Declare the average value
double average;
//Create an average instance of the class average
Average averageObject = new Average();
//Call your average method
average = averageObject.average(numb1,numb2);
//Print the result
System.out.println("Average is : " + average);
}
Everything in Java is object (read about Object Oriented Programming).
Writing your class "Average" defines how your object is structured. It has attributes (characteristics) and methods (actions). Your Average object has no attributes. However it has two methods (average with two and three numbers) acting on integers.
However your class is just the skeleton of your object. You need to create an object from this skeleton using the keyword new as :
Average averageObject = new Average();
Sincerely
public class Marks {
int roll_no;
int subject1;
int subject2;
int subject3;
public int getRoll_no() {
return roll_no;
}
public void setRoll_no(int roll_no) {
this.roll_no = roll_no;
}
public int getSubject1() {
return subject1;
}
public void setSubject1(int subject1) {
this.subject1 = subject1;
}
public int getSubject2() {
return subject2;
}
public void setSubject2(int subject2) {
this.subject2 = subject2;
}
public int getSubject3() {
return subject3;
}
public void setSubject3(int subject3) {
this.subject3 = subject3;
}
public void getDetails(){
Scanner sc = new Scanner(System.in);
System.out.println("Enter the marks of subject1");
this.subject1 = sc.nextInt();
System.out.println("Enter the marks of subject2");
this.subject2 = sc.nextInt();
System.out.println("Enter the marks of subject3");
this.subject3 = sc.nextInt();
System.out.println("Enter the roll number");
this.roll_no = sc.nextInt();
}
public int getAverage(){
int avg = (getSubject1() + getSubject2() + getSubject3()) / 3;
return avg;
}
public void printAverage(){
System.out.println("The average is : " + getAverage());
}
public void printRollNum(){
System.out.println("The roll number of the student is: " + getRoll_no());
}
public static void main(String[] args){
Marks[] e1 = new Marks[8];
for(int i=0; i<2; i++) {
System.out.println("Enter the data of student with id:");
e1[i] = new Marks();
e1[i].getDetails();
e1[i].printAverage();
}
System.out.println("Roll number details");
for(int i=0; i<2; i++){
e1[i].printRollNum();
}
}
}
If you'd like your program to find the average you need to include a call to that method in your main method.
numb1 = keyboard.nextInt();
numb2 = keyboard.nextInt();
System.out.println("The average of " + numb1 + " and " + numb2 + " is " + average(numb1,numb2);
}
you need to call the methods that you have written after you accept the input.
...
System.out.println("Enter two numbers you'd like to be averaged.");
Scanner keyboard = new Scanner(System.in);
numb1 = keyboard.nextInt();
numb2 = keyboard.nextInt();
System.out.println(average (int numb1 , int numb2 ))
...
You probably want to provide a menu of options for the user to select to determine which method to call
System.out.println("Select one option");
System.out.println("1. Enter two numbers you'd like to be averaged.");
System.out.println("2. Enter the 3 numbers you want averaged.");
System.out.println("3. Enter the number Range you want averaged.");
and based on that answer you can determine which method to call
After the access specifier (public) and before the return type (double) place the Java keyword static. You shouldn't worry about what this means right now.
You have to use bitwise operators.
average of int a and b can be calculated as
avg= (a >> 1) + (b >> 1) + (((a & 1) + (b & 1)) >> 1);
The main method will only execute what it is asked to. If you want the average methods to be executed, you will have to create an object, pass the required variable and call the methods from the main method. Write the following lines in the main method after accepting the input.
Average avrg = new Average();
System.out.println("The average is: " + avrg.average(numb1, numb2, numb3));
Write only numb1 and numb2 if you want to average only two numbers.