Returning multiple values java - java

Say I have a java function as follows,
public static int my(int a, int b)
{
int c = a + b;
return c;
String d = "Some Data";
return d;
float f = a/b;
return f
}
So, how do I get the 3 return values separately?
all the values are of different data types.
I've seen this question and this question but couldn't understand properly.

any function can only return one value. What you can do is to create an objet containing all your answers and return this object.
class ResultObject
{
public int c;
public int d;
public int e;
public int f;
}
in your function white
public static ResultObject my(int a, int b)
{
ResultObject resObject = new ResultObject();
resObject.c = a + b;
resObject.d = a*b;
resObject.e = a-b;
resObject.f = a/b;
return resObject;
}
You can return only one value. You have to make that value to "contain" other values.

There are two ways.
If you returning uniform values, e.g. hundred values for temperature over a period of time - use arrays.
If values are non-uniform, e.g. first name, last name and age - introduce a new class.
Reason for this is that Java is a strongly-typed programming language. Wanna describe a new data structure - write a new class.

return array of int.. e.g. int[]...
public static int[] my(int a, int b) {
int res[] = new int[4];
int c = a + b;
res[0] = c;
int d = a * b;
res[1] = d;
int e = a - b;
res[2] = e;
int f = a / b;
res[3] = f;
return res;
}

You can try something like this
public static int[] my(int a, int b) { // use an array to store values
int[] arr = new int[4];
int c = a + b;
arr[0] = c;
int d = a * b;
arr[1] = d;
int e = a - b;
arr[2] = e;
int f = a / b;
arr[3] = f;
return arr; // return values
}

You can return only one element but the element may be array or list.you may return list of values.(some exercise). I hope this may bring some solution.

public class DataStorage{
private int a;
private String data;
private float f;
public DataStorage(int a, String data, float f){
this.a = a;
this.data = data;
this.f = f;
}
/* standard get/set method. */
}
public static DataStorage my(int a, int b)
{
int c = a + b;
String d = "Some Data";
float f = a/b;
DataStorage dataStorage = new DataStorage(c,d,f);
return dataStorage;
}

Related

How to retrive itrms froma set (hashset)

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.

am getting a variable value as zero even it assigned with some value in java

I have 3 classes, among the classes, I am trying to play with methods for that from Second class I am passing some values into First class and from there I am passing values to third class
in the Third I am combining 3 parameters and storing in a variable called p.
now I am trying to print p value in Second class using a method which returns p value but it printing as zero but in the setFive() method it printing the actual value.
Please help me with this where i am doing wrong
Tried Code:
class First {
int x, y, z;
void setOne(int a, int b, int c) {
a = a + x;
b = b + y;
c = c + z;
Third obj = new Third();
obj.setFive(a, b, c);
}
void two(int a) {
this.x = a;
}
void three(int a) {
this.y = a;
}
void four(int a) {
this.z = a;
}
}
class Second {
public static void main(String args[]) {
First f = new First();
f.two(100);
f.three(150);
f.four(170);
f.setOne(1, 2, 3);
Third obj = new Third();
System.out.println(obj.getFive());
}
}
class Third {
int p;
public void setFive(int a, int y, int n) {
this.p = a + y + n;
}
public int getFive() {
return p;
}
}
Thanks
When you do Third obj = new Third(); inside first.setOne(int a,int b,int c), this obj is local to that method, no other object can see it. It is destroyed when the code exits that method
What you need to do it create that Third object in your Second class, and then pass it to First:
Third obj = new Third();
f.setOne(obj, 1, 2, 3);
then on First you need to change the signature to take the object, and call the setter on it:
void setOne(Third obj, int a, int b, int c) {
a = a + x;
b = b + y;
c = c + z;
obj.setFive(a, b, c);
}

How to transform this class to immutable?

I am in process of learning immutability but I am not able to exactly digest how this works. So in order for me to understand immutability, I created a test program.
The funtion getArray(Box b) will make an ArrayList of Box objects.
Expected output: Actual output:
Output Output
a is 5 a is 5
b is 10 b is 10
Output Output
a is 0 a is 4
b is 0 b is 40
Output Output
a is 1 a is 4
b is 10 b is 40
Output Output
a is 2 a is 4
b is 20 b is 40
Output Output
a is 3 a is 4
b is 30 b is 40
Output Output
a is 4 a is 4
b is 40 b is 40
Logic:
public class Box {
static int a;
static int b;
public Box() {
a = 5;
b = 10;
}
public int getA() {
return a;
}
public void setA(int x) {
a = x;
}
public int getB() {
return b;
}
public void setB(int x) {
b = x;
}
public void display() {
System.out.println("Output");
System.out.println("a is " + a);
System.out.println("b is " + b);
System.out.println();
}
}
Main Class
import java.util.ArrayList;
public class Check {
public static void main(String[] args) {
Box b = new Box();
b.display();
ArrayList<Box> arr2 = new ArrayList<Box>();
arr2 = getArray(b);
for (int i = 0; i < arr2.size(); i++) {
arr2.get(i).display();
}
}
public static ArrayList<Box> getArray(Box b) {
ArrayList<Box> arr = new ArrayList<Box>();
for (int i = 0; i < 5; i++) {
b.setA(i);
b.setB(i * 10);
arr.add(b);
}
return arr;
}
}
How do I change the logic in such a way that I get the desired output? How do we decide how and where to edit the code to ensure immutability?
This would be an immutable:
public final class Box {
final int a;
final int b;
public Box(int a, int b) {
this.a = a;
this.b = b;
}
}
And then your array method would be:
public static ArrayList<Box> getArray(Box b) {
ArrayList<Box> arr = new ArrayList<Box> ();
for(int i =0 ;i <5; i++) {
arr.add(new Box(i, i*10));
}
return arr;
}
The data members are declared final because they're immutable, and so getters are pointless and setters just make no sense.
The class is declared final so you cannot subclass it.
In short, an immutable object is an object whose state cannot be modified after it's created. Your immutable Box object would look like this:
public final class Box {
private final int a;
private final int b;
public Box(int a, int b) {
this.a = a;
this.b = b;
}
public int getA() {
return a;
}
public int getB() {
return b;
}
public void display() {
System.out.println("Output");
System.out.println("a is " + a);
System.out.println("b is " + b);
System.out.println();
}
}
Notice that the variables a and b are assigned exactly once, during the construction of the Box instance. There are no setters, because Box's immutability means that its state (including variables a and b) will not change over its lifetime.
The final keyword in front of a and b means that you must assign them exactly once. It's actually considered good practice to make all your variables final unless you specifically need them not to be; but for an immutable object it's essential.
You were using the static keyword. Static has nothing to do with immutability. It means the variable is shared among all instances of the Box class. In my example, each Box instance has its own copies of a and b, because I didn't make them static.
To wrap this up, I'll give an example of your main class which has the desired output:
public class Check {
public static void main(String[] args) {
final List<Box> arr2 = getArray();
for (int i = 0; i < arr2.size(); i++) {
arr2.get(i).display();
}
}
public static ArrayList<Box> getArray() {
final ArrayList<Box> arr = new ArrayList<>();
for (int i = 0; i < 5; i++) {
final Box box = new Box(i, i * 10);
arr.add(box);
}
return arr;
}
}
Note that a new instance of box is created at every iteration of the loop.

Create a Struct In Java Like C++

i want to create an struct in java , like c++ :
struct MyStruct {
int x;
};
#include <iostream>
int main() {
MyStruct Struct;
Struct.x = 0;
std::cout << Struct.x;
return 0;
}
can anyone help me ?
You can use a class, which functions similarly to a struct in C++.
For example, a C++ point struct may look like
typedef struct __point {
int x, y;
} point;
A Java point class has the form
final class Point {
private final double x; // x-coordinate
private final double y; // y-coordinate
// point initialized from parameters
public Point(double x, double y) {
this.x = x;
this.y = y;
}
// accessor methods
public double x() { return x; }
public double y() { return y; }
// return a string representation of this point
public String toString() {
return "(" + x + ", " + y + ")";
}
}
We may then call the following:
Point q = new Point(0.5, 0.5);
System.out.println("q = " + q);
System.out.println("x = " + q.x());
public class ircodes {
public ircodes(String msg_id, String node_id, String frequency, String data) {
this.hdr = new msg_hdr(4 + data.length(), Integer.parseInt(msg_id), Integer.parseInt(node_id));
this.frequency = Integer.parseInt(frequency);
this.data = data;
}
public class msg_hdr {
int msg_len;
int msg_id;
int node_id;
public msg_hdr(int msg_len, int msg_id, int node_id) {
this.msg_len = 12 + msg_len;
this.msg_id = msg_id;
this.node_id = node_id;
}
}
msg_hdr hdr;
int frequency;
String data;
public ByteBuffer serialize() {
ByteBuffer buf = ByteBuffer.allocate(hdr.msg_len);
buf.putInt(hdr.msg_len);
buf.putInt(hdr.msg_id);
buf.putInt(hdr.node_id);
buf.putInt(frequency);
buf.put(data.getBytes());
return buf;
}
}
Java doesn't have structs like C or C++, but you can use Java classes and treat them like a struct. On top of that, you can of course declare all its members as public. (to work exactly like a struct)
class MyClass
{
public int num;
}
MyClass m = new MyClass();
m.num = 5;
System.out.println(n.num);
One of the differences between a struct and a class is that a struct do not have methods. If you create a class without methods, it will work like a struct.
However, you can always put in methods (getters and setters) and set the variables as private like this (it doesn't hurt).
class MyClass
{
private int num;
public void setNum(int num){
this.num = num
}
public int getNum(){
return num
}
}
MyClass m = new MyClass();
m.setNum(5);
System.out.println(n.getNum());
Java doesn't have structs, but a Class can do exactly the same things a struct does.

Getting a function to return two integers

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

Categories