I'm trying to average 6 grades for two different people for school, I have all the grades for each student in different classes I was wondering
How can I import the numbers that I enter for each students object that I create?
//first class
public class GradesA {
int art;
int math;
int science;
int AddGrades(int a, int b, int c){
art = a;
math = b;
science = c;
return a+b+c;
}}
//second class
public class GradesB {
int english;
int carpentry;
int geography;
int AddGradesB(int a,int b,int c){
english = a;
carpentry = b;
geography = c;
return a+b+c;
}}
//final class
public class Classes {
public static void main(String[]args){
GradesA objGrades = new GradesA();
System.out.println(objGrades.AddGrades(100,85,95));
GradesB objGradesB = new GradesB();
System.out.println (objGradesB.AddGradesB(95,85,75));
}}
Hope I understood what you are looking for
Since
int addGrades(int a, int b, int c){
return and integer
why do not you just divide return number from this function by 3 and get your average that you are looking for.
If you want to have access to data fields art, math, and science values
you need getters and setters like follwing example for art data filed
setter function is
public void setArt(int art){
this.art = art;
}
getter function is
public int getArt(){
return this.art;
}
Read More About Setter and Getter
Related
Good afternoon.
I am stuck in helping my son in a Java program. Hope someone can help.
Here is the problem.
In Main i have, amoung other.... the read from scanner like this:
Scanner in = new Scanner(System.in);
Chord c1 = createChord(in); // este chama o private static Chord createChord(Scanner in)
Chord c2 = createChord(in);
Chord c3 = createChord(in);
Chord c4 = createChord(in);
executeCommand(in);
executeCommand(in);
executeCommand(in);
executeCommand(in);
in.close();
}
private static Chord createChord(Scanner in) {
int n1 = in.nextInt();
int n2 = in.nextInt();
int n3 = in.nextInt();
in.nextLine();
//System.out.print(n1);
//System.out.print(n2);
//System.out.print(n3);
return new Chord (n1, n2, n3);
}
Lets assume the method returns values 1,2 and 3 into the hash Chord.
The question is
How can i, in the program, retrieve the vaules from c1 to c4, for instance, the first or the third element from one of them?
I would greatly appreciate anny help.
Peter Rodrigues
If I understand you correctly your question is how to get the values you passed into Chord?
You passed those values via the constructor and than you can save them as members in the object of the class. Those members can be made accessible via "Getters".
Example:
public class Chord {
final int a;
final int b;
final int c;
public Chord(final int a, final int b, final int c) {
this.a = a;
this.b = b;
this.c = c;
}
public int getA() { return a; }
public int getB() { return b; }
public int getC() { return c; }
}
You can read up on that e.g. here.
I have got class like this
class Calculate {
int operation(int a, int b){
return Math.max(a,b);
}
int calc(int a, int b){
int x=100+a*b;
int y=a+a*b;
retun operation(x,y);
}
int calc1(int a, int b){
int x=100+a*b;
int y=b+a*b;
return operation(x,y);
}
}
Now I make two objects of this class as
Calculate obj1=new Calculate();
Calculate obj2=new Calculate();
I want function operation of Class calculate to act like returning maximum of two values for obj1, and return minimum of two values for obj2. Can this be done?
I could only think of creation two different classes Calculate1 and Calculate2 and defining operation as maximum in Calculate1 and minimum in Calculate2 and defining rest thing as same as it is. I hope some easier method also exist without defining two classes.
You can pass the operation to the constructor as an IntBinaryOperator, for example:
class Calculate {
private final IntBinaryOperator op;
public Calculate(IntBinaryOperator operator) {
this.op = operator;
}
int operation(int a, int b) {
return op.applyAsInt(a, b);
}
}
Now you can write:
Calculate c1 = new Calculate(Math::max);
Calculate c2 = new Calculate(Math::min);
And adding an operation is easy - say you want the sum instead of min or max:
Calculate c3 = new Calculate((x, y) -> x + y);
You can override the operation method.
If you don't want to create explicit sub-classes, you can do this with anonymous classes :
Calculate obj1=new Calculate();
Calculate obj2=new Calculate() {
int operation(int a, int b){
return Math.min(a,b);
}
};
obj1.operation(a,b) // calculates maximum
obj2.operation(a,b) // calculates minimum
You can use an OOP concept called Inheritance
public abstract class Calculate {
public abstract int operation(int a, int b);
int calc(int a, int b){
int x=100+a*b;
int y=a+a*b;
return operation(x,y);
}
int calc1(int a, int b){
int x=100+a*b;
int y=b+a*b;
return operation(x,y);
}
}
class Obj1 extends Calculate{
#Override
public int operation(int a, int b) {
return Math.min(a, b);
}
}
class Obj2 extends Calculate{
#Override
public int operation(int a, int b) {
return Math.max(a, b);
}
}
Each new class implements it own method of operation.
You can have something like this :
interface Operation
{
int operation(int a,int b);
}
class Calculate
{
Operation operation;
//rest of class
}
you use the class like this :
Calculate obj1=new Calculate();
obj1.operation=(a,b)->Math.max(a,b);
Calculate obj2=new Calculate();
obj2.operation=(a,b)->Math.max(a,b);
A couple of notes :
you can add a constructor that takes Operation to initialize operation variable.
you should probably have a call method in Calculate class and make operation private for better encapsulation
operation is probably better to be final
This solution may not be as straight forward as other languages but it's the best I can have.
Languages that supported functions as first class citizens from the beginning would make that easier because you can have a function variable which you assign,pass,return just like any variable.
In java we have to use interfaces and anonymous classes to support this, the lambda expressions above were added to java 8 so for java 7 we would write the above like this :
Calculate obj1=new Calculate();
obj1.operation=new Operation{
#Override
int operation(int a,int b)
{
return Math.max(a,b);
}
}
//code for obj2
Edit
You can replace Operation with functional interfaces introduced in java 8(specifically IntBinaryOperator).
You can use strategy pattern to achieve your goal.
Basically you want externalize operation to an interface and specify the object that implements the interface (with min or max) in constructor of Calculate.
This approach gives you most flexible solution that is proof to changes of requirements.
You can modify your class as follows:
class Calculate {
private boolean calcMax;
public Calculate(boolean calcMax){
this.calcMax = calcMax;
}
int operation(int a, int b){
return calcMax ? Math.max(a,b) : Math.min(a,b);
}
}
public class Calculate {
public int a=0;
public int b=0;
public int maxVal = 0;
public int minVal = 0;
public Calculate(int a, int b){
this.a=a;
this.b=b;
this.maxVal=Math.max(a,b);
this.minVal = Math.min(a, b);
}
}
Assuming you are finding the mins and max of the same variables...
I am learning Java and I am doing some C++ codes into java, I am following this webpage http://uva.onlinejudge.org and trying to do some of the problems in Java. Now I am doing this problem http://uva.onlinejudge.org/index.phpoption=com_onlinejudge&Itemid=8&page=show_problem&problem=1072 and after researching and figure out how to do it on paper I found this webpage where the problems seems easy to follow:
http://tausiq.wordpress.com/2010/04/26/uva-10131/
But now, and due to the fact I am new on Java, I want to learn how to do an array of struct in Java. I now I can do a class like a struct: if this is in C++
struct elephant {
int weight;
int iq;
int index;
} a [1000 + 10];
I can do this in Java:
public class Elephant {
private int _weight;
private int _iq;
private int _index;
public Elephant(int weight, int iq, int index) {
this._weight = weight;
this._iq = iq;
this._index = index;
}
public int getWeight() {
return this._weight;
}
public int getIQ() {
return this._iq;
}
public int getIndex() {
return this._index;
}
public void setWeigth(int w) {
this._weight = w;
}
public void setIQ(int iq) {
this._iq = iq;
}
public void setIndex(int i) {
this._iq = i;
}
}
But I don't know how I can turn this into the last part of the struct in c++:
a [1000 + 10];
I mean, having an array of a objects of the class Elephant in Java like having an array of elements elephants in c++
Could someone help me to understand it better..
Arrays of objects in Java are accomplished the same way as an array of primitives. The syntax for this would be
Elephant[] elephants = new Elephant[1000+10];
This will initialize the array, but it will not initialize the elements. Any index into the array will return null until you do something like:
elephants[0] = new Elephant();
This should be what you are loking for :
Elephant [] array = new Elephant[1010];
I want to implement a class which includes a student's name, their GPA, grade level, and their final score. We had to create a Tester along with the initial class creates 2 different students, prints their grade level, GPA, their name, and the calculated final test score.
Formula to calculate final test score = .60 * written + .40 * handsOn
Any help would be appreciated, I can't get this program down and I've been trying for quite a while now.
Here is my code:
Tester:
public class IntroToJavaTester
{
public static void main()
{
IntroToJava j1 = new IntroToJava("Joe", 11, 3.2);
System.out.println(j1.getName());
System.out.println(j1.getGradeLevel());
System.out.println(j1.getGPA());
System.out.println(j1.getFinalScore(written, handsOn));
IntroToJava j2 = new IntroToJava("Jim", 11, 3.2);
System.out.println(j2.getName());
System.out.println(j2.getGradeLevel());
System.out.println(j2.getGPA());
System.out.println(j2.getFinalScore( written,handsOn));
}
}
Here is the IntroToJava class:
public class IntroToJava
{
private String name;
private int glev;
private double gpa;
private double finalscore;
private double written = 80;
private double handsOn = 90;
public IntroToJava(String a, int b, double c, double d, double e)
{
name = a;
glev = b;
gpa = c;
written = d;
handsOn = e;
}
public String getName()
{
return name;
}
public int getGradeLevel()
{
return glev;
}
public double getGPA ()
{
return gpa;
}
public double getFinalScore(int written, int handsOn)
{
finalscore = .60*written+.40*handsOn;
return finalscore;
}
}
Your IntroToJava constructor is defined with 5 arguments and you're calling it with only 3 in IntroToJavaTester.
The two arguments you're omitting appear to correspond to the fields written and handsOn.
You've defined getFinalScore to take two arguments with the same names but a different type.
I suspect what you probably really want is for getFinalScore to take no arguments but use these two fields.
Or perhaps getFinalScore is supposed to just be a getter for the field finalScore which doesn't seem to be set or used anywhere, but has a suspiciously similar name.
I am writing a function and I want it two return two integers as results. However, I cannot get it to do this. Could someone help me? Here is my best shot
public static int calc (int s, int b, int c, int d, int g)
{
if (s==g)
return s;
else if (s+b==g)
return s && b;
else if (s + c==g)
return s && c;
else if (s+d==g)
return s && d;
else
System.out.println("No Answer");
}
You could have the method return an array of int:
public static int[] calc (int s, int b, int c, int d, int g)
Make a "pair" class and return it.
public class Pair<T,Y>
{
public T first;
public Y second;
public Pair(T f, Y s)
{
first = f;
second = s;
}
}
Make a small inner class that has two integers.
private static class TwoNumbers {
private Integer a;
private Integer b;
private TwoNumbers(Integer a, Integer b) {
this.a = a;
this.b = b;
}
}
You create a instance of the class and return that instead.
For this specific problem, since the answer always returns s:
....
return s;
....
return s && b;
....
return s && c;
....
return s && d;
....
you could just return the 2nd value. I use 0 to indicate "just s" since the first case (if (s==g)) could be thought of as if (s+0==g). Use a different sentinel value than 0 for this, if necessary.
public static int calc (int s, int b, int c, int d, int g)
{
if (s==g)
return 0;
else if (s+b==g)
return b;
else if (s+c==g)
return c;
else if (s+d==g)
return d;
else {
// System.out.println("No Answer");
// Probably better to throw or return a sentinel value of
// some type rather than print to screen. Which way
// probably depends on whether "no answer" is a normal
// possible condition.
throw new IndexOutOfBoundsException("No Answer");
}
}
If no exception is thrown, then s is always the first result:
try {
int result1 = s;
int result2 = calc(s, b, c, d, g);
} catch (IndexOutOfBoundsException ex) {
System.out.println("No Answer");
}
package calcultor;
import java.util.*;
import java.util.Scanner;
public class Calcultor{
public static void main(String args[]){
input();
}
public static void input(){
Scanner FirstNum = new Scanner(System.in);
System.out.print("Enter the First number: ");
int num01 = FirstNum.nextInt();
Scanner secondNum = new Scanner(System.in);
System.out.print("Enter the second number: ");
int num02 = secondNum.nextInt();
output(num01, num02);
}
public static void output(int x ,int y){
int sum = x + y;
System.out.println("Sum of Two Number: "+sum);
//return sum;
}
}
why do you want to do this? and if you have some need like this can't you change your return type to string, because in case of string you can have separator between two values which will help you in extracting values.... say 10&30 ,
I agree this is a wrong way of solving...i assumed that there is limitation of sticking to primitive datatype