I can't get the exact method calling for this code - java

I'm trying to write a simple code in Java but I keep getting error for the method calling.
package tutorialproject2;
import java.util.Scanner;
public class Tutorialproject2 {
static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
InputTest();
Calculate();
}
public static void InputTest(){
String message = input.nextLine();
System.out.println(Hello(message));
}
public static String Hello(String message){
if (message.equals("Hi")){
return "Hello";
}else{
return "Goodbye";
}
}
public int Calculate(int a,int b){
a = input.nextInt();
b = input.nextInt();
int answer = a * b;
return answer;
}

You have the method Calculate(int a,int b) with 2 parameters but call the method without parameters Calculate().
I suppose you should change the method Calculate(int a,int b) to
public static int Calculate(){
int a = input.nextInt();
int b = input.nextInt();
int answer = a * b;
return answer;
}
and as #Visme mentioned, to add static keyword.
or you can leave your method as
public int Calculate(){
int a = input.nextInt();
int b = input.nextInt();
int answer = a * b;
return answer;
}
In this case in the main function, you should call the method this way:
new Tutorialproject2().Calculate();

Non static method calculate is called from static function (main)

should be in this way, int var = Calculate(3,5); , can't be calculate() alone as it has a return type and arguments.
You could call methods with return type void alone like InputTest();
as you return integer from this method and the method has parameters so you should pass the required parameters here (of integer type),
public static int Calculate(int a,int b){
. . .
return answer;
}

Related

How can use a variable of a object which is created by the user ?(Java)

I created a class and left it on the user to make an instance. The instance has a constructor that requires the user to input values to the instance :-
public class perfo2{
public int c;
public int p;
public int b;
public String n;
perfo2(int c,int p,int b,String n){ //constructor
this.c=c;
this.p=p;
this.b=b;
this.n=n;
}
Now i have a few methods that requires variable from the instance like:-
public int calculate(int c,int p,int b){
int per= (int)((c+p+b/60*100));
return per;
}
public void dis(int c,int p,int b,String n,int per){
System.out.println("Name:"+n);
System.out.println("Chemistry:"+c);
System.out.println("Physics:"+p);
System.out.println("Biology:"+b);
System.out.println("Percentage:"+per+"%");
} }
now i want these methods to actually access the object for it various variables and use them.
I know what arguments i have given to the methods wont be able to that but what will? and also
if i make an object in the code itself i can easily access the variables by
michael.dis(michael.c,michael.p,michael.b,michael.n,michael.calculate(michael.c,michael.p,michael.b));
Just create a object and use it
perfo2 michael = new perfo2(c,p,b,n);
michael.dis(michael.c,michael.p,michael.b,michael.n,michael.calculate(michael.c,michael.p,michael.b));
A bit extra code to my comment, you could use your class like this example. You could probably add the percentage to your class variables but i did not want to mess with your logic
public class Perfo2 {
private int c;
private int p;
private int b;
private String n;
Perfo2(int c, int p, int b, String n) { // constructor
this.c = c;
this.p = p;
this.b = b;
this.n = n;
}
public int calculate(Perfo2 perfo2) {
return (perfo2.c + perfo2.p + perfo2.b / 60 * 100);
}
public void dis(Perfo2 perfo2,int per) {
System.out.println(perfo2);
System.out.println("Percentage:" + per + "%");
}
#Override
public String toString() {
return String.format("Name: %s%nChemistry: %s%nPhysics: %s%nBiology: %s", this.n ,this.c,this.p,this.b);
}
public static void main(String[] args) {
Perfo2 p = new Perfo2(10,6,5,"Mark");
p.dis(p, 70);;
}
}
If I understand you correctly; you want to be able to access the varaibles set in the consructor c, p, b, n. You should be able to do this by creating getters on each of the variables as such:
public class perfo2 {
public int c; // consider making the access modifier for c,p,b & n private
public int p;
public int b;
public String n;
perfo2(int c, int p, int b, String n) { //constructor
this.c = c;
this.p = p;
this.b = b;
this.n = n;
}
public int getC() {
return c;
}
public int getP() {
return p;
}
public int getB() {
return b;
}
public String getN() {
return n;
}
}
// Create the object as such
perfo2 person1 = new perfo2(1,2,3,"my String");
int c = person1.getC();
int p = person1.getP();
int b = person1.getB();
String n = person1.getN();
You may also want to consider making the access modifier for c,p,b & n private; therefore this cannot be accessed direclty from the object. Depedning on use case you could also use person1.c etc

Accesor method is not recieving var from mutator method

I am making a basic calculator on eclipse, java. But I have a problem with one of the methods as it doesn't accept the right variable.
I know that the problem is in the calculateDifference() and setCurrentValue() method.
public class Dollar {
static int startingValue = 2650;
static int currentValue;
static int dollars;
static int differenceValue = calculateDifference();
static void setDollarQuantity (int dollarValue) {
dollars = dollarValue;
}
static void setCurrentValue(int currentDollar) {
currentValue = currentDollar;
}
static int calculateDifference() {
return ( currentValue - startingValue) * dollars;
}
public static void main(String[] args) {
setCurrentValue(2780);
setDollarQuantity(111);
calculateDifference();
}
}
The expected result from the calculateDifference method was 14,430 but the actual is 0. I have found the problem which was the calculateDifference method is not accepting the currentValue as 2780, but 0. Anyone can help me and modify my code?
Change
static int diffrenceValue = calculateDifference();
to
static int differenceValue;
and in main()
calculateDifference();
to
differenceValue = calculateDifference();
System.out.println(differenceValue);
This way you will set the differenceValue after the other variables are initialized with correct value, not before.

How to grab data from other class Java

I have to create two classes, let's call them A and B .
public class A {
double Number1;
double Number2;
A(double Number1, Number2){
this.Number1=Number1;
this.Number2=Number2;
}
}
Now i have a void main class where someone enter their Number 1 and Number 2
public static void main(String[] args) {
A game=new A(555, 999);
}
Now, i Want to Create another Class Called B, and i want the Numbers 555, and 999 to be transferd/to use the same values into class B
like
public class B{
///double a= 555;
///double c= 777;
}
I need these operators a, and c to fetch data from public static void main class
Can someone explain me how to do this?
Thanks.
One way to do this is to add some get methods into A:
public double getNumber1() {
return Number1;
}
public double getNumber2() {
return Number2;
}
And add set methods into B:
public void setA(double a) {
this.a = a;
}
public void setC(double c) {
this.c = c;
}
Then instantiate B in your main class:
B b = new B();
And set the values then:
b.setA(game.getNumber1());
b.setC(game.getNumber2());
Now the values of a and c of your instance of B are 555 and 999.
Or perhaps:
public B(double a, double c) {
this.a = a;
this.c = c;
}
and pass the values into the constructor:
B b = new B(game.getNumber1(), game.getNumber2());
One basic principal of OOP is that we have certain objects with certain properties build upon classes. These classes 'act as blueprints' for objects which should use their behaviour.
As I mentioned in a comment you could create a constructor who takes an object of class A as a parameter:
public class B
{
private double value1;
private double value2;
public B( A aObject )
{
value1 = aObject.getVal1();
value2 = aObject.getVal2();
}
// rest of the class...
}
with a class A:
public class A
{
private double val1;
private double val2;
public A( double val1, double val2 )
{
this.val1 = val1;
this.val2 = val2;
}
public double getVal1()
{
return val1;
}
public double getVal2()
{
return val2;
}
}
and a main method:
public static void main( String[] args )
{
A aObject = new A( 100, 100 );
B bObject = new B( aObject );
}
Doing so would alow objects of class A to exist on their own but objects of class B always need a 'foundation' in form of another object from which they can copy their values.
Also take a small read on encapsulation
You can extend A class on B. The code bellow will help you out.
public class ClassA {
double number1;
double number2;
public ClassA(double number1, double number2) {
this.number1 = number1;
this.number2 = number2;
}
}
public class ClassB extends ClassA {
public ClassB(double number1, double number2) {
super(number1, number2);
}
public double getNumber1() {
return number1;
}
public double getNumber2() {
return number2;
}
}
If you access the classB.getNumber1() method you will get your results.
You need getter methods in you classes to query the values. In your case for the member variables Number1 and Number2.
Here is an example for you, consider the change of upper-/lowercase names:
public class A {
// value of number 1
// member variables should start lowercase
// they should be private so they are not modified from the outside
private double number1;
// value of number 2
private double number2;
// constructor:
public A(double number1, double number2) {
// in a custom constructor you should
// alwas run the superconstructor at first:
super();
setNumber1(number1);
setNumber2(number2);
}
// setter/getter for number 1:
// search the internet for "camelcase" description
// (lower/upper cases in method/member names)
public void setNumber1(double theNumber) {
this.number1 = theNumber;
}
public void getNumber1() {
return this.number1;
}
// do the same for number 2
}
Now, you can use these getters to retrieve the data. Build class B the same way and you go like this:
public static void main (String[] args) {
A a = new A(555, 666);
B b = new B(a.getNumber1(), a.getNumber2());
}
Useless to say that in this example class A and class B don't differ, so class B is nonsense. But if your classes are going have different signatures (member variables, methods and so an), this is a proper way.

How can I invoke a method and print its result?

How can I invoke a method and print its result?
public class Test {
public static int main (String args[]){
System.out.println(total);
}
public int numbers (int a, int b){
int total;
total = a + b;
return = total;
}
}
Try this instead:
public class Test {
public static void main (String args[]){
System.out.println(numbers(1, 2));
}
public static int numbers(int a, int b){
int total;
total = a + b;
return total;
}
}
Variables are scoped to the method or class in which they are defined, therefore the 'total' variable is accessible only in the 'numbers' method
public class Test {
public static void main (String args[]){
System.out.println(numbers(anumber,bnumber));
}
public static int numbers (int a, int b){
int total;
total = a + b;
return total;
}

Java consecutive method calls

So I've seen, in many places, calling methods of a class like:
SomeClass obj = new SomeClass();
obj.addX(3).addY(4).setSomething("something").execute();
I don't think I completely understand how that works. Is each method independent of each other, so the above is equal to:
obj.addX(3);
obj.addY(4);
obj.addSomething("something");
obj.execute();
Or are they designing their class structure in some other fashion that allows for this. If they are how are they designing their classes to support this?
Also, does that have a specific name? Or is this just calling methods on a class?
That would be method chaining. It can do one of two things.
Each call to a method returns this which allows you to continue to call methods on the original instance.
public class SomeClass
{
private int _x = 0;
private int _y = 0;
private String _something = "";
public SomeClass addX(int n)
{
_x += n;
return this;
}
public SomeClass addY(int n)
{
_y += n;
return this;
}
public SomeClass setSomething(String something)
{
_something = something;
return this;
}
// And so on, and so on, and so on...
}
Each method call returns a new instance of the class with everything copied/updated appropriately. This makes the class immutable (so you don't accidentally modify something that you didn't mean to).
public class SomeClass
{
private int _x = 0;
private int _y = 0;
private String _something = "";
public SomeClass(int x, int y, String something)
{
_x = x;
_y = y;
_something = something;
}
public SomeClass addX(int n)
{
return new SomeClass(_x + n, _y, _something);
}
public SomeClass addY(int n)
{
return new SomeClass(_x, _y + n, _something);
}
public SomeClass setSomething(String something)
{
return new SomeClass(_x, _y, something);
}
// And so on, and so on, and so on...
}
Some people have also mentioned Fluent Interfaces. Fluent Interfaces utilize method chaining to create an API that provides something along the lines of a Domain Specific Language which can make code read much more clearly. In this case, your example doesn't quite qualify.
they modify object's state and return the same object back mostly
class Number{
int num;
public Number add(int number){
num+=number;
return this;
}
}
you can call it like
new Number().add(1).add(2);
most of the time the use case is to return new Object to support immutability
Each of those methods return an instance. For example, the call to
obj.addX(3)
will return the same instance obj, so the call
obj.addX(3).addY(4)
will be equivalent to
obj.addY(4)
This is called method chaining.
The methods are implemented like this:
public SomeClass addX(int i) {
// ...
return this; // returns the same instance
}
public class Test1 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Test1 abc = new Test1();
abc.add1(10, 20).sub1(40, 30).mul1(23, 12).div1(12, 4);
}
public Test1 add1(int a, int b)
{
int c = a + b;
System.out.println("Freaking Addition output : "+c);
return this;
}
public Test1 sub1(int a, int b)
{
int c = a - b;
System.out.println("Freaking subtraction output : "+c);
return this;
}
public Test1 mul1(int a, int b)
{
int c = a * b;
System.out.println("Freaking multiplication output : "+c);
return this;
}
public Test1 div1(int a, int b)
{
int c = a / b;
System.out.println("Freaking divison output : "+c);
return this;
}
}

Categories

Resources