Java Return is Returning Blank - java

I'm trying to create a java method that returns the sum of two values x and y. Currently when I run the code, the output isn't returning anything. Is there any way I can get the value to return the sum WITHOUT modifying the "getSum(x,y);" in line 6 while using the return method???
public class ZawMethods2
{
public static void main(String[] args)
{
int x = 7, y = 45;
getSum(x,y);
}
public static int getSum(int x, int y){
int sum = x+y;
return (sum);
}
}
Thank you all in advance!!! I'm still in the beginning stage of coding so I appreciate all the help.

Sorry I thought that you are not allowed to modify getSum method. Just add System.out.println(sum); to getSum method.

public class ZawMethods2
{
public static void main(String[] args)
{
int x = 7, y = 45;
System.out.print(getSum(x,y));
}
public static int getSum(int x, int y){
//no need to create temprory varibale
return x+y;
}
}

Just print it inside the getSum method, before returning:
public static int getSum(int x, int y){
int sum = x+y;
System.out.println(sum);
return sum;
}
As mentioned by #Stultuske in the comments. if you want to only print the sum, and never get it. Then just remove the return type and aswell name the method differently for clarification:
public static void printSum(int x, int y){
System.out.println(x + y);
}
You might even want to introduce a whole new method. Leaving the old getSum all on itself. The new method then delegates and just prints the result returned:
public static void printSum(int x, int y){
System.out.println(getSum(x, y));
}

Actually, you are compiling a program without any output. You have to use something like
System.out.println(getSum(x, y));
Otherwise you wont get any output.
If you modify the main-method like:
public static void main(String[] args)
{
int x = 7, y = 45;
int sum = getSum(x,y);
System.out.println(sum);
}
you will get the output: 52.
In this case you will save the returned Integer in sum and will print a new line to your console.
If you want to add some words, you can modify the main like:
public static void main(String[] args)
{
int x = 7, y = 45;
int sum = getSum(x,y);
System.out.println("The result is" + sum);
}

You should store your result in a variable or display a result.
int c = getSum(x,y);
or
System.out.println("The result of the two numbers are " +getSum(x,y);

Try This:
public class ZawMethods2
{
public static void main(String[] args)
{
int x = 7, y = 45;
System.out.print(getSum(x,y));
}
public static int getSum(int x, int y)
{
int sum = x+y;
return (sum);
}
}
This code will resolve your problem very easily.

Related

How to print each number of a given number separately?

I have a code is written that is supposed to print each of the numbers separately. Heres an example.
printDigits(1362) prints
2
6
3
1
printsDigits(985) prints
5
8
9
You can pull apart a number into its digits using / 10 and % 10.
I have started some code the way I was taught but I am not sure what to do with the other variables.
Please have a look:
public class Main {
public static void main(String[] args) {
System.out.println(printDigits(1362));
System.out.println(printDigits(985));
}
public static int printDigits(int x){
int y = x % 10;
while (x > 0){
x = y;
System.out.println(x);
x = x / 10;
}
return x;
}
}
Why don't you convert the parameter x to String then read each Char in the String since a String is array of Char. If the output must be an int you convert the Char to int.
printDigits method should be like this:
public static void printDigits(int x) {
int y;
while (x > 0) {
y = x % 10;
System.out.println(y);
x = x / 10;
}
}
And the calling of the method will be like this:
printDigits(1362); // without the System.out.println()
There are various ways to achieve such results. You can better understand all solutions in these answers.
public static void printDigits(int num) {
while(num>0) {
int remainder = num%10;
num = num/10;
System.out.println(remainder);
printDigits(num);
}
}
You can use recursion to make it even more efficient.
You need to write int y = x % 10; inside the loop to "pull apart" every digit and print the digit y you have "pulled out".
Remove the System.out.println around your function calls.
You don't need to return a number, so you can change your return type to void:
public class Main {
public static void main(String[] args) {
printDigits(1362);
System.out.println();
printDigits(985);
}
public static void printDigits(int x) {
while (x > 0) {
int y = x % 10;
System.out.println(y);
x = x / 10;
}
}
}

bad operand types for binary operator '*' how to covert the type to int

I'm having some problems with the following program.
public static void main(String[] args) {
Int x =new Int(3);
int y= square() +twice() +once();
System.out.println(y);
}
private int square (Int x)
{
x= x*x;
return x;
}
private int twice (Int x)
{
x= 2*x;
return x;
}
private int once (Int x)
{
x= x;
return x;
}
and the output for this program should be 45.
here is the Int class.
public class Int {
private int x;
public Int (int x)
{
this.x=x;
}
the problem I have is in
private int square (Int x)
{
x= x*x;
return x;
}
x=xx gives an error of bad operand types for binary operator ''.first type Int, Second Type Int.
I know for '*' to work it need an int type, I tried to use Integer.parseInt(x), but it says, x is not a string.
can someone help me?
what causes this problem and how to fix it.
The problem is simple: you define an Int type and expect it to be implicitly convertible to a primitive int but this has nothing to do with what your Int type is expected to be in your design, it could be called Foo instead that Int but that would be the same.
If you want to be able to get the int value wrapped inside an Int instance then you must provide your own way to do it, eg:
class Int {
int x;
public int intValue() { return x; }
}
so that you can do:
Int x = new Int(3);
int square = x.intValue() * x.intValue();
or, to avoid breaking encapsulation:
class Int
{
int x;
public Int(int x) { this.x = x; }
public Int square() { return new Int(x*x); }
/* or: int square() { return x*x; }*/
}
Your class Int looks (very lightly) like the Integer wrapper. If you really need a wrapper, use the very tested Java Integer, otherwise, use the primitive int.
Remember, Java does not support operator overloading.

changing static variables from another method in java

I want to create a method, moveQ(), that I will be able to call in method find() in order to change find()'s variables, but in method moveQ() I am getting the error cannot find symbol variable x in this example x, y, and z are the variables I need to change.
edited:
I also have a few restrictions as this is taken from an exercise from Java course:
1. method must be static.
2. global variables are not allowed.
3. time complexity should be less than O(n), I cannot add to memory complexity (meaning can not use another array or objects).
4. the method find() can not accept parameters.
In the actual program, I need to write a static boolean method that will return true if number x is found in an array that is divided into quadrants. To do that, it searches for each quadrant's highest number. If x is larger than the quadrant highest number, then I need to move to the next quadrant.
x, y, and z are the maximum number, middle number and the minimum number of the quadrant of the array and by changing them, I can move quadrants.
I've already written the find() method, but I want to use helper methods to make the code better.
Is what I am trying to do even possible, and if so how do I accomplish it?
public class Test
{
public static boolean find()
{
int x = 10;
int y = 20;
int z = 30;
change(x,y,z); // call helper method to change this method's variables.
System.out.println(x); // should be 20
System.out.println(y); // should be 22
System.out.println(z); // should be 15
}
//helper method to be called from find() method
private static void change(int changeX ,int changeY,int changeZ)
{
//change find() variables.
x = changeX * 2;
y = changeY + 2;
z = changeZ /2;
}
}
The problem comes from your second method. You pass changeX, changeY, and changeZ but try to set the values of x, y, and z. The variables x, y, and z are not within the scope of this method and therefore the program will throw an error.
Moreover, this methodology will not work regardless of these names. Java does not allow you to change the values of primitives when you pass them to a new method. The best solution is probably to put them in an array and change the second method to accept an array. The body of your first method may now look like
int [] intarray = new int[3];
intarray[0] = 10;
intarray[1] = 20;
intarray[2] = 30;
change(intarray);
System.out.println(intarray[0]);
System.out.println(intarray[1]);
System.out.println(intarray[2]);
and the second method would become
private static void change(int [] changeArray) {
changeArray[0] *= 2;
changeArray[1] += 2;
changeArray[2] /= 2;
}
(The *=, +=, and /= operators are shorthand for what you were doing above.
You declared variables inside of method so you don't have access to them, if you want to change them you either make them global(define them outside of method):
public class Test
{
int x;
int y;
int z;
void yourMethod(){
}
}
Or change method find to take x, y and z values as parameters.
You could write a class encapsulating your x, y, z as fields and convert your methods to its instance methods (that is, they should not be static anymore).
public class Calculation {
private int x = 10, y = 20, z = 30;
public boolean find()
{
x = 10;
y = 20;
z = 30;
change(x,y,z); // call helper method to change this method's variables.
System.out.println(x); // should be 20
System.out.println(y); // should be 22
System.out.println(z); // should be 15
}
private void change(int changeX ,int changeY,int changeZ)
and so on.
Then create an instance of it and call your methods on it:
Calculation calculation = new Calculation();
calculation.find();
...
You can achieve that in more organized way :
Create Calculation class then put all your variables and methods on it
File Calculation.java:
public class Calculation {
private int x = 10;
private int y = 20;
private int z = 30;
public void setX(int value){
x = value;
}
public void setY(int value){
y = value;
}
public void setZ(int value){
z = value;
}
public int getX(){
return x;
}
public int getY(){
return y;
}
public int getZ(){
return z;
}
private void change(int changeX, int changeY, int changeZ){
setX(changeX * 2);
setY(changeY + 2);
setZ(changeZ / 2);
}
public void find(){
change(x,y,z);
System.out.println(getX());
System.out.println(getY());
System.out.println(getZ());
}
}
After that just create new object of class Calculation in your main program and call find() method on this object variable
File Main.java:
public class Main {
public static void main(String[] args) {
Calculation c = new Calculation();
c.find();
}
}
Output:
20
22
15

How does this code (parameters (of Primitive Type)) work?

I am new to java and just learned a little bit about methods and classes, and I am really confused about this whole chapter. This code comes from our review powerpoint and I really don't know how to do it. And I feel like the last section should be in the class? But this is how the powerpoint says. Can someone please explain how does this code work and how to get the printout result specifically step by step?? I really appreciate it, thanks!
public class MyClass {
public void swap(int x, int y){
int temp = x;
x = y;
y = temp;
}
}
int w = 10,
z = 20;
MyClass m = new MyClass();
m.swap(w,z);
System.out.println(w + " " + z);
In order to execute Java you need a main method somewhere.
public static void main(String[] args) {
// Do stuff
}
So you can rewrite the example like so to get it executing:
public class Main {
public static void main(String[] args) {
int w = 10,
z = 20;
MyClass m = new MyClass();
m.swap(w,z);
System.out.println(w + " " + z);
}
}
public class MyClass {
public void swap(int x, int y) {
int temp = x;
x = y;
y = temp;
}
}
The whole point of this code example is that Java passes primitive types by value and not by reference. Look at the main method. You have two integers, w=10 and z=20. After that you pass w and z to the swap method. Since java passes these primitive types as values, the original w and z are not modified by the swap, which is proven by the println where w is still 10 and z is still 20.

Calculate third side of a triangle using methods

Ask the user for 2 sides of a triangle and then print out the length of the third side, as calculated by a method. Write a method to find the length of the third side using the Pythagorean theorem.
I'm new to java and I am suck with the following code which may be way off...
import java.util.*;
public class Tri8 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter two numbers:");
int a = input.nextInt();
int b = input.nextInt();
System.out.println(pythagoraen(a, b));
}
//Method goes here
public static int pythagoraen(int x, int y) {
Math.pow(x, y);
int z = Math.sqrt(x, y);
Math.sqrt(x, y);
}
}
Assuming you meant to find the hypotenuse of a right-angled triangle using the pythagorean theorem, you need to return the root of the sum of squares of both other sides:
public static double pythagoraen(int x, int y) {
return Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2));
}
private static double pythag(double x, double y){
return Math.sqrt(x*x + y*y);
}
or if you want to use math.pow, you can replace x*x with Math.pow(x, 2)
in java calling math.sqrt and math.pow dont directly edit the variables, they actually return a value that you can use, for instance math.pow takes in two double, the first is the base and the second is the exponent, so Math.pow(2,3) would be the same to you and me as 2^3
Here's the fixed code:
import java.util.*;
public class Tri8 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter two numbers:");
int a = input.nextInt();
int b = input.nextInt();
System.out.println(pythagoraen(a, b));
}
//Method goes here
public static int pythagoraen(int x, int y) {
return Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2));
}
}

Categories

Resources