How can I invoke a method and print its result? - java

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;
}

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

having problems with sum() method

The question asks me to make a class where there are addNumber(int numbers) and sum() methods in NumberStatistics class. The addNumber method can't store any value.
public class NumberStatistics {
private int number;
private int sum;
public NumberStatistics() {
this.sum = 0;
}
public void addNumber(int numbers) {
this.number = numbers;
sum();
}
public int sum() {
this.sum = this.sum + this.number;
return this.sum-this.number;
}
}
Main:
public class Main {
public static void main(String[] args) {
NumberStatistics stats = new NumberStatistics();
stats.addNumber(3);
stats.addNumber(5);
stats.addNumber(1);
stats.addNumber(2);
System.out.println("sum: " + stats.sum());
}
}
So I have to do return this.sum-this.number; But is there other way to achieve same result?
update: edited to fix errors.
I would use this implementation:
public class NumberStatistics {
private int sum;
public NumberStatistics() {
this.sum = 0;
}
public void addNumber(int number) {
this.sum += number;
}
public int getSum() {
return this.sum;
}
}
While this is far from an ideal implementation for a basic calculator, it meets the requirement The addNumber method can't store any value. If we cannot store any state about the numbers being input, then the only option is to compute the sum on the fly. Hence, I also renamed the sum() method to getSum(), because now it simply returns the sum which is already known.
You can add the line:
this.sum = this.sum + numbers;
in the addNumber method, so you remove the need for the "number" variable, and in the sum method just return this.sum

Calculating two variables in method

This is some really beginner stuff. And cannot for the life of me figure out why I cannot have a method calculate two variables for me.
public class Testing {
int val1;
int val2;
int res;
public static void main(String[] args)
{
int calcResult();
}
public Testing()
{
val1 = 4;
val2 = 8;
res = 0;
}
public static int calcResult()
{
res = val1 + val2;
return res;
}
}
val1 and val2 aren't static and your method is static that's a problem.
I would recommend you to do this:
public class Testing {
private int val1;
private int val2;
private int res;
public static void main(String[] args)
{
new Testing();
}
public Testing()
{
this.val1 = 4;
this.val2 = 8;
this.res = 0;
this.calcResult();
}
public int calcResult()
{
res = this.val1 + this.val2;
return res;
}
}
static method can not access instance variables.
Remove static keyword and try something like:
public class Testing {
int val1;
int val2;
int res;
public static void main(String[] args)
{
System.out.println( new Testing().calcResult() );
}
public Testing()
{
val1 = 4;
val2 = 8;
res = 0;
}
public int calcResult()
{
res = val1 + val2;
return res;
}
}
You have multiple errors in your code. First off, you can only assign a function result to a variable, so the current code won't compile:
public static void main(String[] args)
{
int calcResult();
}
Also, you cannot reference a field (non static) variable from a static function, so also the following won't compile:
public static int calcResult()
{
res = val1 + val2;
return res;
}
because all the variables will not be available from within the static function calcResult().
Not to mention that it's generally bad practice to use field variables in calculations. What I would recommend is something like the following:
public class Testing {
public static void main(String[] args)
{
new Testing();
}
public Testing()
{
int val1 = 4;
int val2 = 8;
int res = calcResult(val1, val2);
System.out.println(res);
}
public static int calcResult(int val1, int val2)
{
return val1 + val2;
}
}

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

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;
}

Communication between 2 Classes

I'm a newbie java programer and I'm trying to make my first project.
I need to pass a variable between 2 classes, which is going fine. The problem is that the variable has a changing value and i cannot pass the actual value. Here is an example:
public class A{
private int counter = 0;
public int getCounter(){
return counter;
}
//here some code which will increase or decrease the value of the counter variable
//lets say for the sake of the example that at this point the value of the variable is 1.
//counter = 1;
}
public class B{
public static void main(String[] args) {
A a = new A();
System.out.println(a.getCounter());// here I need the actual counter variable value which is currently: 1
}
}
My problem is that i always receive 0. How can i pass the actual value of the variable.
Any help or advice is greatly appreciated.
A a = new A();
After instantiation (above statement) you need to call the method which will increment the counter here.
Example:
a.incrementCounter();
Then below statement will get counter value.
System.out.println(a.getCounter());
lets say for the sake of the example that at this point the value of the variable is 1.
No, by the time that code is read, the value did not change. All you do inside a class-block is to define a class, the “template” for an object. At that time, no values are set though.
The a.getCounter() you use already does the correct job: It returns the current value of a’s counter variable. If it does not return 1, then obviously the value hasn’t changed yet.
public class A {
private int counter = 0;
public int getCounter() {
return counter;
}
public void increaseCounter() {
counter++;
}
}
public class B {
public static void main() {
A a = new A();
System.out.println(a.getCounter());
a.increaseCounter();
System.out.println(a.getCounter());
}
}
Make variable static so that it will be associated with class.
public class A{
private static int counter = 0;
public int getCounter(){
counter++;
return counter;
}
public static void main(String[] args) {
A a = new A();
a.setCounter(5);
System.out.println(a.getCounter());
}
public class A{
private int counter = 0;
public int getCounter(){
return counter;
}
public void setCounter(int count ){
this.counter=count;
}
}
Use constructors/setter...
public class A{
private int counter = 0;
public A(int c){
counter = c
}
public int getCounter(){
return counter;
}
public void setCounter(int c){
counter = c;
}
public void incCounter(){
counter++;
}
}
public class B{
public static void main(String[] args) {
A a = new A(123);
System.out.println(a.getCounter());
a.setCounter(456);
System.out.println(a.getCounter());
a.incCounter();
System.out.println(a.getCounter());
}
}
class A {
private int counter = 0;
public int getCounter() {
return counter;
}
public int increment() {//////////create increment Method which will increase the counter , or do any function you want
return counter++;
}
public void setCounter(int c) {///////////this method will allow you to set the counter
counter=c;
}
}
class B {
public static void main(String[] args) {
A a = new A();
a.increment();///////if you call this function will change your counter , if not , you will get it = 0
System.out.println(a.getCounter());
}
}
A a = new A();
System.out.println(a.getCounter());
The Output = 0
A a = new A();
a.increment();
System.out.println(a.getCounter());
The Output =1
a = new A();
a.setCounter(10);//////////here you set the `counter` by 10
System.out.println(a.getCounter());
The Output =10;
You have one class (Counter) which manages the counter int variable.
You would like for one or more other classes to be able to increment and/or get the counter value.
In that case, each instance of those classes should have a reference to the same instance of Counter (stored as member variable, passed to their constructor or a setter method).
class Counter {
private int counter = 0;
public int getValue() { return counter; }
public void increment() { counter++; }
public String toString() { return Integer.toString(counter); }
}
class CounterUser {
private final Counter counter;
public CounterUser(Counter counter) { this.counter = counter; }
public String toString() { return Integer.toString(counter.getValue()); }
}
class Test {
public static void main(String[] args) throws Exception {
Counter counter = new Counter();
CounterUser a = new CounterUser(counter);
CounterUser b = new CounterUser(counter);
System.out.printf("%s %s %s\n", counter, a, b);
counter.increment();
System.out.printf("%s %s %s\n", counter, a, b);
b.increment();
System.out.printf("%s %s %s\n", counter, a, b); }
}
Output:
0 0 0
1 1 1
2 2 2
You can do it from the constructor and/or create method that changes the value.
public class A
{
private int counter = 0;
public A()
{
// value is set first time you create an instance of A. (e.g when you do A a = new A();
counter = 1;
}
public int getCounter()
{
return counter;
}
public void incrementCounter()
{
counter++;
}
}
public class B
{
public static void main(String[] args)
{
A a = new A();
System.out.println(a.getCounter());// Output : 1
a.incrementCounter();
System.out.println(a.getCounter());// Output : 2
a.incrementCounter();
a.incrementCounter();
a.incrementCounter();
System.out.println(a.getCounter());// Output : 5
}
}

Categories

Resources