Method not getting invoked - java

I have some experience using Python so I've been trying to learn Java by writing the same programs I write in Python for school in Java.
I have this function where I enter two integers and it returns the sum. If the integers are the same, then it returns double the sum. For example, 5 + 5 = 20.
I have the following code for this function.
public class sumDouble
{
public int sumDouble(int a, int b) {
int sum = a + b;
if (a == b) {
sum = sum * 2;
}
return sum;
}
}
Next, I want to write a script where I ask the user to input two integers and the main class calls this function. I have the following code for this. Where did I go wrong?
import java.util.Scanner;
public class GetSumFromUser
{
public static void main (String[] args){
Scanner in = new Scanner(System.in);
int a;
int b;
int sumDouble;
sumDouble sum = new sumDouble();
System.out.println("Please enter an integer.");
a = in.nextInt();
System.out.println("You entered "+a);
System.out.println("Please enter another integer.");
b = in.nextInt();
System.out.println("You entered "+b);
System.out.println("Your sum is "+sum);
}
}
At the last line, the output reads "Your sum is sumDouble#1777aec".

You never actually invoked the sumDouble() method. Rather than print out sum (which is an Object), you should print like this:
System.out.println("Your sum is "+sum.sumDouble(a,b));

Try this:
public class SumDouble
{
public static int sumDouble(int a, int b) {
int sum = a + b;
if (a == b) {
sum = sum * 2;
}
return sum;
}
}
...
System.out.println("Your sum is "+SumDouble.sumDouble(a, b));

If you do print(sum) then you are printing the object...
do instead
System.out.println("Your sum is "+sum.sumDouble(a,b));

You get an object from sumDouble class, but you never invoke it's sumDouble method:
sumDouble sum = new sumDouble();
change this to:
sumDouble sd = new sumDouble();
int sum = sd.sumDouble(a,b);

/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package test;
import java.util.Scanner;
class sumDouble
{
public int sumDouble(int a,int b)
{
int sum=a+b; //add the numbers
if(a==b) //check if both numbers are same
sum=sum*2; //double th value if same
return sum; //return sum
}
}
public class GetSumFromUser
{
public static void main (String[] args){
Scanner in = new Scanner(System.in);
sumDouble s=new sumDouble();
int a;
int b;
int sum;
System.out.println("Please enter an integer.");
a = in.nextInt();
System.out.println("You entered "+a);
System.out.println("Please enter another integer.");
b = in.nextInt();
System.out.println("You entered "+b);
sum= s.sumDouble(a, b) ; //call the sum double function
System.out.println("Your sum is "+sum);
}
}

System.out.println("Your sum is "+sum);
Change this to:
System.out.println("Your sum is "+sum.sumDouble(a,b));
You haven't called the method. "Your sum is "+sum -this will call the toString method of sum which is sumDouble#1777aec.

Related

How can I add a method that returns a result?

I have been working on these programs.
They don't have any errors but I need to make them return a result in order for them to work properly. More specifically to add a method that returns a result.
The instructions were the following:
Write a program that is split in to methods at least one of which returns a result
This is the first program:
import java.util.Scanner; // Needed to make Scanner available
public class onlineCalculator {
public static void main(String[] args) {
Calculator();
} //END of main method
// Inserting your loan at the start of the year and the amount paid off
// and calculates the amount yet to pay with interest
//
public static void Calculator(){
int a;
int b;
Scanner scanner = new Scanner(System.in);
System.out.print("Amount of loan at start of year? ");
a = scanner.nextInt();
System.out.print("Amount paid off this year? ");
b = scanner.nextInt();
int c;
c= a - b;
double d;
final double e;
d = c * 1.07 * 10.0;
e = (int)d / 10.0;
System.out.println("The new amount owed is (in pounds): " + e);
} //END of Calculator
}
This is the second program:
import java.util.Scanner; // Needed to make Scanner available
public class BodyAge {
public static void main(String[] args) {
CalculateAge();
} // END of main method
// Inserting age and heart rate and stretch distance
//and calculates the body age based on conditions
public static void CalculateAge() {
int age;
int heartRate;
int stretch;
Scanner input = new Scanner(System.in);
System.out.print("What is your age? ");
age = input.nextInt();
System.out.print("What is your heart rate? ");
heartRate = input.nextInt();
if (heartRate <= 62) {
age -= 5; // block of code to be executed if condition1 is true
} else if (62 <= heartRate && heartRate <= 64) {
age--; // block of code to be executed if the condition1 is false and condition2 is
// true
} else if (65 <= heartRate && heartRate <= 70) {
age++; // block of code to be executed if the condition1 and condition2 are false and
// condition3 is true
} else {
age += 2; // block of code to be executed if the condition1 and condition2 and condition3
// are false and condition4 is true
}
System.out.print("How far can you stretch? ");
stretch = input.nextInt();
if (stretch <= 20) {
age += 4; // block of code to be executed if condition1 is true
} else if (20 <= stretch && stretch <= 32) {
age++; // block of code to be executed if the condition1 is false and condition2 is
// true
} else if (33 <= stretch && stretch <= 37) {
age = age + 0; // block of code to be executed if the condition1 and condition2 are false and
// condition3 is true
} else {
age = age + 3; // block of code to be executed if the condition1 and condition2 and condition3
// are false and condition4 is true
}
System.out.println("Your body's age is " + age);
} //END of CalculateAge
}
Here's an example of one possible way you might consider breaking up a class into using some methods with returns. Let's take your first class for this example. You frequently are taking input from your user.
Scanner scanner = new Scanner(System.in);
System.out.print("Amount of loan at start of year? ");
a = scanner.nextInt();
System.out.print("Amount paid off this year? ");
b = scanner.nextInt();
This could potentially be broken out into another method for condensed reusability.
public static int askForInt(Scanner scanner, String message) {
System.out.print(message);
return scanner.nextInt();
}
From there you can replace your calls for information with this method. Full example:
import java.util.Scanner; // Needed to make Scanner available
public class OnlineCalculator {
public static void main(String[] args) {
calculator();
} //END of main method
// Inserting your loan at the start of the year and the amount paid off
// and calculates the amount yet to pay with interest
//
public static void calculator(){
int a;
int b;
Scanner scanner = new Scanner(System.in);
a = askForInt(scanner, "Amount of loan at start of year? ");
b = askForInt(scanner, "Amount paid off this year? ");
scanner.close();
int c;
c= a - b;
double d;
final double e;
d = c * 1.07 * 10.0;
e = (int)d / 10.0;
System.out.println("The new amount owed is (in pounds): " + e);
} //END of Calculator
public static int askForInt(Scanner scanner, String message) {
System.out.print(message);
return scanner.nextInt();
}
}
First program,
You could for example split your calculate() method into 2 method and move your int variable "a" and "b" in the main() method
1ST method:
void getInput(){
...
}
2nd method:
int calculateAndreturnResult(int a, int b) {
...
}
Finally use those method in the main() and print the result :
getInput();
int result = calculateAndreturnResult(){
}
system.out.println(result);
So how Java will work is the compiler will only read commands from the "main" method. So in the case of the calculator, Java will see that you want to run the calculator method, which has a return type of "void" It goes PUBLIC (meaning other classes can see and interact with it) STATIC (basically meaning that the method belongs to the class itself, not instances of the class) VOID ( this is your return type, meaning after the method is done, what is being put back into main) so if you want a method to return something, you need to change the return type. In the case of your calculator project something like this would split it up into 2 methods one of which returns something:
public class OnlineCalculator {
public static void main(String[] args) {
Calculator();
} //END of main method
// Inserting your loan at the start of the year and the amount paid off
// and calculates the amount yet to pay with interest
//
//this will return an int type
public static int loanDifference(int amountOwed, int amountPaid) {
int c = amountOwed - amountPaid;
return c;
}
// this will return a double type
public static double newAmountOwed(double d) {
double e = (int)d / 10.0;
return e;
}
public static void Calculator(){
int a;
int b;
Scanner scanner = new Scanner(System.in);
System.out.print("Amount of loan at start of year? ");
a = scanner.nextInt();
System.out.print("Amount paid off this year? ");
b = scanner.nextInt();
scanner.close();
int c = loanDifference (a, b);
double d;
d = c * 1.07 * 10.0;
final double e = newAmountOwed(d);
System.out.println("The new amount owed is (in pounds): " + e);
} //END of Calculator
}
seems like they want you to put more code in, but the idea is that they want you to know how to use methods that work together to make something at the end!
use the same idea with the other one!

Java print the recursion in main method

I was wondering when I tried to print the value of recursion in main, the answer was:
Enter the number: 1
2The result is:
How to make the number 2 to the front like,
The result is: 2
import java.util.Scanner;
public class Question4Final {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("Enter the number: ");
int a = scan.nextInt();
System.out.printf("The result is: ", multiplication(a));
}
public static int multiplication(int a) {
if (a == 5) {
int multiply = 10 * 6 * 2;
System.out.print(multiply);
} else if (a == 4) {
int multiply2 = 6 * 2;
System.out.print(multiply2);
} else if (a == 1) {
System.out.print("2");
}
return a;
}
}
To call the method:
System.out.printf("The result is: ", multiplication(a));
first the arguments must be evaluated, so multiplication(a) is executed before System.out.printf("The result is: ", multiplication(a)). Since multiplication(a) prints something, that printing takes place before "The result is:" is printed.
You should change multiplication(a) to simply return the result without printing it. Then use System.out.println("The result is: " + multiplication(a)) to print the result.
Note the you have to change the value returned by multiplication(a), since currently you return a, which is not the value printed by that method.
You have 2 issues in your code.
First is you are printing the value of 'multiply' in your static method :
public static int multiplication(int a){
System.out.print(multiply);
That is a reason why it is printing 2 before the statement :
2The result is:
2nd issue is you are calling the method multiplication in the print statement :
System.out.printf("The result is: ", multiplication(a));
That is not how to print the result by calling the method.
I have taken your example and run the below code. You can check this code.
import java.util.Scanner;
public class Main
{
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("Enter the number: ");
int a = scan.nextInt();
int product = multiplication(a);
System.out.println("The result is : " +product);
}
public static int multiplication(int a){
int multiply = 0;
if(a == 5){
multiply = 10 * 6 * 2;
}else if(a == 4){
multiply = 6 * 2;
}else if(a == 1){
multiply = 2;
}
return multiply;
}
}
Below are the outputs on different options :
Enter the number: 4
The result is : 12
Enter the number: 5
The result is : 120
Enter the number: 1
The result is : 2

Little coding challenge (Fermat’s Last Theorem)

I am trying to learn Java; here is the exercise I am struggling with:
Fermat’s Last Theorem says that there are no integers a, b, and c such that a^n + b^n = c^n except in the case when n = 2.
Write a method named checkFermat that takes four integers as parameters— a, b, c and n—and that checks to see if Fermat’s theorem holds. If n is greater than 2 and it turns out to be true that a^n + b^n = c^n, the program should print “Holy smokes, Fermat was wrong!” Otherwise the program should print “No, that doesn’t work.”
You should assume that there is a method named raiseToPow that takes two integers as arguments and that raises the first argument to the power of the second. For example:
int x = raiseToPow(2, 3);
would assign the value 8 to x, because 2^3 = 8.
I have encountered several problems, for example I can't seem to use Math.Pow(a, n) with an int, only with a double. If you are interested, here is what I have so far, feel free to skip it and just write your own version of the program in the answers.
(Please keep in mind I started this book only a few days back.)
package fermat.s_last_theorem;
import java.lang.Math;
import java.util.Scanner;
public class FermatS_Last_Theorem {
public static void main(String[] args) {
Scanner s = new Scanner (System.in);
System.out.println("Inster First Number");
double frst = s.nextDouble();
System.out.println("Insert Second Number");
double scnd = s.nextDouble();
System.out.println("Insert Exponent");
double expo = s.nextDouble();
double v = FLaw(frst,scnd,expo);
double k = FLawRes(v, expo);
System.out.println("The answer is " + v);
System.out.println("Your answer rooted by your exponent is " + k);
Law(v, Pow(k, expo));
}
public static double Pow(double a, double b) {
double res = Math.pow (a, b);
return (res);
}
public static double FLaw(double frst, double scnd, double expo) {
double D1 = Pow(frst, expo);
double D2 = Pow(scnd, expo);
return (D1 + D2);
}
public static double FLawRes(double res, double base) {
double D3 = Pow(res, 1/base);
return D3;
}
public static void Law(double v, double k) {
if (v==k) {
System.out.println("Pythagora works.");
} else {
System.out.println("Pythagora doesnt work");
}
}
}
The main problem is that I am not exactly sure how to answer the question the exercise asks, and the program listed above does not work as it should.
You should assume that there is a method named raiseToPow ...
That means you write your code using such a method, even though you don't have the method. Your code will be reviewed manually, or teacher may supply the method and run your code.
If you want to test your code, you can always implement it yourself. You should just remove the method before turning in the code.
But the intent here is that this is a write-on-paper exercise.
Now, how to implement int raiseToPow(int a, int b)?
Think about what it means. 34 means 3 * 3 * 3 * 3.
So, implement the method to multiply by a by itself b times.
I'll leave that as another exercise for you.
You can break it out like this :
public boolean checkFermat(int a, int b, int c, int n) {
if(n != 2 &&
(checkFermatCondition(a,b,c,n) ||
checkFermatCondition(a,c,b,n) ||
checkFermatCondition(b,c,a,n))) {
System.out.println("Holy smokes, Fermat was wrong!");
} else {
System.out.println("No, that doesn’t work.");
}
}
In this method you are just trying to reduce you check condition with all of the combinations by calling this method with different parameters
private boolean checkFermatCondition(int a, int b, int c, int n) {
return raiseToPow(a,n)+raiseToPow(b,n) == raiseToPow(c,n);
}
Your function raiseToPow()'s functionality can be achieved using Math.pow:
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println( "Fermat's Last Theorem: a^n+b^n != c^n (n!=2)");
int a, b, c, n;
System.out.print("Enter value for a:");
a = s.nextInt();
System.out.print("Enter value for b:");
b = s.nextInt();
System.out.print("Enter value for c:");
c = s.nextInt();
while(true){
System.out.print("Enter value for n:");
n = s.nextInt();
if(n!=2)
break;
System.out.println("n cannot be 2");
}
checkFremat(a,b,c,n);
}
public static void checkFremat(int a, int b, int c, int n){
if ((int)Math.pow(a, n)+(int)Math.pow(b, n)!=(int)Math.pow(c, n))
System.out.println("Fermat was correct!");
else
System.out.println("Holy smokes, Fermat was wrong!");
}
}
Try it here!

How do I use a function involving integers?

We have an assignment in class to create a greatest common divider (gcd) program using functions. I missed out on the lesson where we learned how to properly use them. I finished the part that actually does the division but I don't know how to separate it into a function and have it work. I'd like to have the input in the main class and the process in function.
This is what I have, it does not work when I run it
package gcd.function.java.program;
import java.util.Scanner;
/**
*
* #author sarah_000
*/
public class GCDFunctionJavaProgram {
public static void main(String[] args) {
int num1;
int num2;
int div;
Scanner input = new Scanner(System.in);
System.out.print("Enter your first number: ");
num1 = input.nextInt();
System.out.print("Enter your second number: ");
num2 = input.nextInt();
System.out.printf("The GCD is %d ", div);
}
public static void GCDFunction() {
if(num1 > num2)
div = num2;
else div = num1;
while((num1 % div!= 0)||(num2 % div != 0))
{
div --;
}//end of while loop
}
}
Any tips or help you can give to me will be greatly appreciated, I'm very new
You declare two parameters and modify the return type in your GCDFunction like this:
public static int GCDFunction(int num1, int num2)
You are currently trying to access the variables in the main method but are out of scope.
Also, you never actually call your GCDFunction
Think of it like passing functions in math. The GCDFunction() has to receive the numbers into the function so we do
public static void GCDFunction(int num1, int num2)
That also lets Java know the type it is, type int. And your java variables are scoped inside of the functions so you have to print the output in the function that created the variable in your scenario.
So once you have that function set up to receive the variables and output after processing, you call the function in the main with a
GCDFunction(num1, num2);
Where num1 and num2 are the variables that have your integers stored in.
The end result after a little rearranging looks like this.
import java.util.Scanner;
public class GCDFunctionJavaProgram {
public static void main(String[] args) {
int num1;
int num2;
Scanner input = new Scanner(System.in);
System.out.print("Enter your first number: ");
num1 = input.nextInt();
System.out.print("Enter your second number: ");
num2 = input.nextInt();
GCDFunction(num1, num2);
}
public static void GCDFunction(int num1, int num2) {
int div;
if(num1 > num2){
div = num2;
}
else{ div = num1;}
while((num1 % div!= 0)||(num2 % div != 0))
{
div --;
}//end of while loop
System.out.printf("The GCD is %d ", div);
}
Trying to give you a example of how the code should be to take in variable number of parameters.
public int gcd(Integer... numbers) {
int gcd = 1;
int miNNumber=Collections.min(Arrays.asList(numbers));
boolean isDivisible;
for(int i=2; i<=miNNumber;i++) {
isDivisible=true;
for(Integer eachNumber : numbers) {
if(eachNumber%i!=0) {
isDivisible=false;
break;
}
}
if(isDivisible) {
gcd=i;
}
}
return gcd;
}
You can call it
gcd(10, 200, 400);
or
gcd(10, 200, 400, 4000, 40);

Why do I get a DivideByZeroException in my Java code?

import java.io.IOException;
import java.util.*;
public class calling {
public static String s;
public static String t;
public static int y;
public static int x;
public static int num1() {
int x;
Scanner scanner = new Scanner (System.in);
System.out.println("Please enter a number called x: ");
x=scanner.nextInt();
return x;
}
public static int num2() {
int y;
Scanner scanner = new Scanner (System.in);
System.out.println("Please enter a second number called y: ");
y=scanner.nextInt();
return y;
}
public static void calculation() {
Scanner input = new Scanner(System.in);
System.out.println("What process would you like to do? *, /, + or - ?");
s=input.next();
if (s.equals("*")) {
System.out.println("\nThe product of these numbers is:" + (x*y));}
else
if (s.equals("+")) {
System.out.println("\nThe sum of these numbers is: " + (x+y));}
System.out.println("\nDo you want x or y to be the dividor/subtractor?: ");
t=input.next();
if (t.equals("y") || t.equals("Y") ) {
if (s.equals("/")) {
System.out.println("\nThe quotient of these numbers is: " + (x/y));}
else
if (s.equals("-")) {
System.out.println("\nThe difference of these numbers is: " + (x-y));}}
else
if (t.equals("x") || t.equals("X")){
if (s.equals("/")) {
System.out.println("\nThe quotient of these numbers is: " + (y/x));}
else
if (s.equals("-")) {
System.out.println("\nThe difference of these numbers is: " + ((y-x)));}}
}
public static void main (String [] args) throws IOException {
num1();
num2();
calculation();
}
}
i keep getting this error in what should be my final result which is simply the result of the calculations being performed
this is the error:" Exception in thread "main" java.lang.ArithmeticException: / by zero
at calling.calculation(calling.java:44)
at calling.main(calling.java:64)"
Since this is likely homework, I'll give you a hint to point you in the right direction.
When you run your program, you execute num1 and num2 to collect the values of x and y from the user. Within num2, y is declared as a local variable. What happens to that variable when num2 returns? And what does that imply for the class field (variable) y declared on line 7?
This is also a good time to learn how to use a debugger. Put a breakpoint on line 44, and see what the values of x and y are.
You need to make sure that the:
int x;
int y;
are the ones you want. Integer's default to zero when static.

Categories

Resources