I'm very new to java (only been using it for 2 days now), and am trying to make a class that lets you input three numbers, and then outputs the average of all three. When the code is like this the output always equals 0 and I don't know why? I am able to get it to work if I change add "static" to all the public integers, but why do I have to do that? Is there another way I can do it without making them static?
import java.util.Scanner;
public class lettuce
{
public int num1;
public int num2;
public int num3;
public static void main(String args[])
{
lettuce lettuceObject = new lettuce();
int total = 0;
int average;
int array[] = {lettuceObject.num1,lettuceObject.num2,lettuceObject.num3};
lettuceObject.getNum1();
System.out.println(lettuceObject.num1);
System.out.println(array[0]);
lettuceObject.getNum2();
System.out.println(lettuceObject.num2);
System.out.println(array[1]);
lettuceObject.getNum3();
System.out.println(lettuceObject.num3);
System.out.println(array[2]);
for(int counter = 0; counter < array.length;counter++)
{
total = total + array[counter];
}
average = total/array.length;
System.out.println("The average of the three numbers is: " + average);
}
public int getNum1()
{
Scanner keyboard = new Scanner(System.in);
System.out.println("Please type your first number: ");
return num1 = keyboard.nextInt();
}
public int getNum2()
{
Scanner keyboard = new Scanner(System.in);
System.out.println("Please type your second number: ");
return num2 = keyboard.nextInt();
}
public int getNum3()
{
Scanner keyboard = new Scanner(System.in);
System.out.println("Please type your third number: ");
return num3 = keyboard.nextInt();
}
}
The output is 0 because you have never initialized your num(s), you're assigning to them on get(s) which you never call - and you're trying to set them in get(s) which isn't the customary approach.
public int num1 = 3;
public int num2 = 3;
public int num3 = 3;
And you should get 3. A getter should look like
public int getNum1()
{
return num1;
}
A setter should look like
public void setNum1(int num1) {
this.num1 = num1;
}
And then you would customarily name your class Lettuce and call it from main like
Lettuce lettuce = new Lettuce();
lettuce.setNum1(10);
System.out.println(lettuce.getNum1());
You would customarily also make your fields private and access them through your mutator and accessor methods (getters and setters)
private int num1;
private int num2;
private int num3;
You could choose to create a constructor
public Lettuce(int num1, int num2, int num3) {
this.num1 = num1;
this.num2 = num2;
this.num3 = num3;
}
You could also calculate the average from "lettuce" with something like
public double average() {
return (num1 + num2 + num3) / 3.0;
}
Edit
Please don't edit your question like that. Also, consider the order of your operations. Your get methods are what set the values. So call them before you create your array!
lettuceObject.getNum1();
lettuceObject.getNum2();
lettuceObject.getNum3();
// Each of those values is 0 until you call the previous three lines.
int array[] = {lettuceObject.num1,lettuceObject.num2,lettuceObject.num3};
System.out.println(array[0]);
System.out.println(array[1]);
System.out.println(array[2]);
As you are new I will give you some more tips they making this work.
1: The static modifier specifies that you don't need to instanciate a Class to use that attribute (variable or method ).
For example, if you have a class with one static variable:
public class Clazz {
static int variable=1;
}
You may call it without creating an instance of Clazz. System.out.println(Clazz.variable); would compile with no problems.
Otherwise, a non-staticattribute will need an Instance of Clazz to be accessed:
Clazz instanceOfClazz = new Clazz();
System.out.println(instanceOfClazz.variable);
2: The type intis native. So, when you create your array, you are passing no values, and after reading the output, your array is not updated.
3: a double variable would be more precise to store the result of an average.
4: last but not least, your getNum method could be merged into just 1 method receiving the message as parameter, so you hace a best and clear reuse of the code. That can be staticbecause it doesn't need to interact with any object of the class Lettuce (with receive as parameter all it needs to execute and return the integer sent by the user, you can assing the return outside the method)
Ps.: by notation, the class name should start with capital letter.
Your final class would look better this way:
import java.util.Scanner;
public class Lettuce
{
public int num1;
public int num2;
public int num3;
public static void main(String args[])
{
Lettuce lettuceObject = new Lettuce();
int total = 0;
double average;
lettuceObject.num1 = lettuceObject.getNum("Please type your first number: ");
System.out.println(lettuceObject.num1);
System.out.println(array[0]);
lettuceObject.num2 = lettuceObject.getNum("Please type your second number: ");
System.out.println(lettuceObject.num2);
System.out.println(array[1]);
lettuceObject.num2 = lettuceObject.getNum("Please type your third number: ");
System.out.println(lettuceObject.num3);
System.out.println(array[2]);
int array[] = {lettuceObject.num1,lettuceObject.num2,lettuceObject.num3};
for(int counter = 0; counter < array.length;counter++)
{
total = total + array[counter];
}
average = total/array.length;
System.out.println("The average of the three numbers is: " + average);
}
public int getNum(String message)
{
Scanner keyboard = new Scanner(System.in);
System.out.println(message);
return keyboard.nextInt();
}
}
Hope this helped.
Related
Trying to write a grade calculator program and am running into problems passing return variables from one method to another. I'm new to coding so I'm sure this isn't very pretty, but was hoping to get some help.
I have a method to calculate the Homework score, a method to calculate the midterm score, and a method to calculate the final score. I'm trying to call the return variables in the last method to calculate overall grade. The error is when calling the courseScore method, and displays as: The method courseScore(int, int, int) in the type GradeCalc is not applicable for the arguments (). Any help is appreciated!
import java.util.*;
public class GradeCalc {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int overAll;
int midtermScore;
int finalsScore;
hwpoints();
midTerm();
courseScore();
}
public static int hwpoints() {
int x;
int hwTotal = 0;
int pointsPossible = 0;
Scanner input = new Scanner(System.in);
System.out.println("Enter number of assignments:");
x = input.nextInt();
for(int i = 1; i <= x; i++) {
System.out.println("Enter assignment score:");
int hwScore = input.nextInt();
hwTotal += hwScore;
System.out.println("Enter total possible points:");
int points = input.nextInt();
pointsPossible += points;
}
int overAll = (hwTotal / x);
System.out.println("You got " + hwTotal + " out of " + pointsPossible + ". Your overall Homework grade is a: " + overAll);
return overAll;
}
public static int midTerm() {
int midtermPoints;
int midtermPossible;
int midtermScore;
Scanner input = new Scanner(System.in);
System.out.println("Enter Midterm Score:");
midtermPoints = input.nextInt();
System.out.println("Enter total possible Midterm Points:");
midtermPossible = input.nextInt();
midtermScore = (midtermPoints / midtermPossible);
System.out.println("Your Midterm score is " + midtermScore);
return midtermScore;
}
public static int finalScore() {
int finalsPoints;
int finalsPossible;
int finalsScore;
Scanner input = new Scanner(System.in);
System.out.println("Enter Finals Score:");
finalsPoints = input.nextInt();
System.out.println("Enter total possible Finals Points:");
finalsPossible = input.nextInt();
finalsScore = (finalsPoints / finalsPossible);
System.out.println("Your Finals score is " + finalsScore);
return finalsScore;
}
public static void courseScore(int finalsScore, int midtermScore, int overAll) {
Scanner input = new Scanner(System.in);
System.out.println("What percent of your grade is the final?");
int testWeight = input.nextInt();
System.out.println("What percent of your grade is the midterm?");
int midtermWeight = input.nextInt();
System.out.println("What percent of your grade is the homework?");
int hwWeight = input.nextInt();
int testWeighted = (finalsScore * (testWeight / 100));
int midtermWeighted = (midtermScore * (midtermWeight / 100));
int hwWeighted = (overAll * (hwWeight / 100));
int courseScore = ((hwWeighted + midtermWeighted + testWeighted) * 100);
System.out.println("Your total course grade is " + courseScore);
}
}
The methods hwpoints, midTerm and finalScore all return an int value which you are not keeping
You need to do some thing like
int hwp = hwpoints ();
int mt = midterm ();
int fs = finalScoare ();
then you can pass these variable into courseScore as
courseScore (fs, mt, hwp);
Note
In this code
int testWeighted = (finalsScore * (testWeight / 100));
you are going to be undertaking integer division.
See Int division: Why is the result of 1/3 == 0?
First thing is to understand the concept of a class and a static method.
Classes have fields and methods.
Fields (variables) hold data (state) that the Methods can operate on
Each instance of a class has its own values for these fields
Methods operate on the Fields
Methods can include call parameters
Methods can also return a value
Static instances (classes, fields, and methods) are singletons
There is only one copy of them (all instances of the class share the same one)
Static Methods cannot access (non-static) fields/methods
Using this, consider creating another class that has (most) of the content of your GradeCalc class and remove the statics from them and create an instance of that class in GradeCalc. That way each method in the class can access the fields you have defined.
Here is an example of the concept based on what you have already written.
Note: You code has other structural/implementation issue and I would never implement it as shown; but, I don't want to turn this into a Java course; so, I tried to show you something that could work within the context of what you had written.
public class GradeCalc {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
Calculator calc = new Calculator (calc);
calc.hwpoints();
calc.midTerm();
calc.courseScore();
int overAll = calc.OverAll;
int midtermScore = calc.MidtermScore;;
int overAll = calc.OverAll;
}
public class Calculator {
public void OverAll;
public void MidtermScore;
public void FinalsScore;
public void hwpoints()
{
...
OverAll = overAll
}
//Do the same for the methods below
//public void midTerm();
//public void courseScore();
}
The purpose of this code is to find the amount of items one wishes to buy, the price of those items, and what the sale currently is. For a buy three get one free sale, it would look something like
1 items at 5.0; discount is 0
2 items at 5.0; discount is 0
3 items at 5.0; discount is 5.0
4 items at 5.0; discount is 5.0
The class extends an abstract class whose abstract method is computeDiscount()
However, I have no idea how to make this method function, because it won't except it as static, but if the method isn't static then I can't use it in my code!
I have no idea what to do, and I desperately need help
package homeFolder;
import java.util.Scanner;
public class BuyNItemsGetOneFree extends DiscountPolicy{
static Scanner input = new Scanner(System.in);
static double itemCost;
static int count = count();
static int n = getN();
static double discount = 0;
public static void main(String[] args) {
itemCost = itemCost();
for(int i = 1; i <= count; i ++) {
discount = computeDiscount(i, itemCost);
System.out.println(i + " items at " + itemCost +
"; discount is " + discount);
}
}
public static double itemCost() {
System.out.print("Enter the cost of the item: ");
itemCost = input.nextDouble();
return itemCost;
}
public static int count() {
System.out.print("How many items are you going to buy: ");
count = input.nextInt();
return count;
}
public static int getN() {
System.out.print("How many items must you buy till you got one free? ");
n = input.nextInt();
return n;
}
public double computeDiscount(int count, double itemCost) {
double discount = 0;
if((count % n) == 0)
discount += itemCost;
return discount;
}
}
If you want to do anything with abstraction, you can't be using static methods. Here, it's best to use instance variables combined with a factory method to do all the initilization action.
package homeFolder;
import java.util.Scanner;
public class BuyNItemsGetOneFree extends DiscountPolicy {
// Below are your fields, or instance variables. Notice the lack of static.
final double itemCost;
final int count;
final int n;
public static void main(String[] args) {
// Now you have an instance to work with.
BuyNItemsGetOneFree sale = newInstance();
for(int i = 1; i <= sale.count; i ++) {
double discount = sale.computeDiscount(i, itemCost);
System.out.println(i + " items at " + sale.itemCost +
"; discount is " + discount);
}
}
// Only the factory method can access this.
private BuyNItemsGetOneFree (double itemCost, int count, int n) {
this.itemCost = itemCost;
this.count = count;
this.n = n;
}
public static BuyNItemsGetOneFree newInstance() {
// The scanner really only needs to be used here.
Scanner input = new Scanner(System.in);
// Initilizes itemCost
System.out.print("Enter the cost of the item: ");
double itemCost = input.nextDouble();
// Initilizes count
System.out.print("How many items are you going to buy: ");
int count = input.nextInt();
// Initilizes n
System.out.print("How many items must you buy till you got one free? ");
int n = input.nextInt();
// Constructs and returns
return new BuyNItemsGetOneFree(itemCost, count, n);
}
#Override // Always add this when overriding a method.
public double computeDiscount(int count, double itemCost) {
double discount = 0;
if((count % n) == 0)
discount += itemCost;
return discount;
}
}
If you want to go a step further, there is no need for the parameters in computeDiscount as they are (from what I see) just going to reference fields already able to be used.
Spencer make all your methods static and also your main method is missing static.
it should be something like this public static void main(String [] args)
I have a program that originally took two numbers passed the values to a method and returned the higher number. I got that so I decided to expand to the program and want the program to ask the user for the 2 numbers. I have 2 problems that I can not figure out. The first is that it is saying that my variables i and j are not initialized. The second is that the program loops 3 times. can someone offer me any assistance. I am coming from c# Thanks.
package javabook;
import java.util.Scanner;
public class Chapter5 {
public static void main(String[] args)
{
int i;
int j;
int k = max(num1(i),num2(j));
//Scanner input = new Scanner(System.in);
num1(i);
num2(j);
System.out.print("The maximum between " + num1(i) + " and " + num2(j) + " is " +k);
}
//Return the max between two numbers
public static int max(int num1, int num2)
{
int result;
if (num1>num2)
result = num1;
else
result = num2;
return result;
}//End Max Method
public static int num1(int i)
{
Scanner input = new Scanner(System.in);
System.out.print("Please enter the first number: ");
input.nextInt();
input.close();
return i;
}//End num1 method
public static int num2(int j)
{
Scanner input = new Scanner(System.in);
System.out.print("Please enter the second number: ");
input.nextInt();
input.close();
return j;
}//end num2 method
}
Local variable don't have same values as globally declared variable's thus you have to assign some value to use them. Global variable int has value 0 by default.
int i = 0;
int j = 0;
or
this.i = 0;
this.j = 0;
here:
int i;
int j; <---creates the var, but doesn't initialize it
int k = max(num1(i),num2(j));
^---using the var, without having initialized it
even a simple
j = 0;
would help.
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.
I'm learning java and was trying to create a simple program to help me find a way (if there is one) to access non-static methods inside the main method of the same class. This is what I have so far
import java.util.Scanner;
public class MethodVariables
{
public int num1;
public int num2;
public int add = (num1 + num2);
public int sub = (num1 - num2);
public static void main(String[] args)
{
Scanner input = new Scanner (System.in);
System.out.println("Please enter the first number: ");
String num1 = input.nextLine();
System.out.println("Please enter the second number: ");
String num2 = input.nextLine();
input.close();
// I know these wouldn't work this way but this is just to show what I am trying to accomplish
addition(add);
subtraction(sub);
}
public void addition(int add)
{
System.out.println("The sum of the two is: " +add);
}
public void subtraction(int sub)
{
System.out.println("The diference of the two is: "+sub);
}
}
If anyone knows what I am overlooking I'd appreciate the help.
Sure, just create an instance of the class in main:
MethodVariables instance = new MethodVariables();
instance.addition(num1);
instance.subtraction(num2);
Since addition and subtraction are instance methods, then you'll always need an instance of the class to call them on.
This is not related to the original question, but is worth pointing out:
public int add = (num1 + num2);
This will not work as you expect. If you want a function that adds two numbers, just make a function that adds two numbers.
public int add(int num1, int num2) {
return num1 + num2;
}
public int subtract(int num1, int num2) {
return num1 - num2;
}