Calling specific index of Array in setter method - java

I have a class Gs with the following defined:
private static double[] r = new double[3];
I also create the getter/setter for this array:
public static double[] getR() {
return r;
}
public static void setR(double[] r) {
Gs.r = r;
}
In another class I want to set the value in the array, e.g. just r[1] but I don't know how I can do it with these functions.
How can I set the index of which I wish to set the value to?
r[0], r[1], r[2]....
The setter method expects an array arg double[] rather than double but I don't know how I'd specify it.

You could pass the index as an argument to the getter and the setter:
public static double getR(int index) {
return r[index];
}
public static void setR(int index, double r) {
Gs.r[index] = r;
}

try this
double[] val = new double[3];
//example values
val[0] = 3.4;
val[1] = 24d;
val[2] = 28.4;
Gs.setR(val);
Note: This will set the full array at once

You just can set the the value on the array returned by the getter:
Gs.getR()[1] = .1;

Related

Is it possible to modify the value of an attribute sent in argument of a function in Java?

I'm working on a calculator and I search how I can optimize my code.
The thing is that I have much code duplication due to if I'm working on the first number of the calculation or the second. So I'm searching if it is possible to modify the value of an attribute sent in argument of a function ? (I think not because I saw nowhere the answer).
Maybe I'm expressing myself badly so here is a code below to explain what I'm talking about:
public class MyClass
{
private static int number1 = 1;
private static int number2 = 2;
public MyClass()
{
changeValueOf(number1, 3);
}
private static void changeValueOf(int number, int value)
{
//Change here the value of the correct field
}
}
First of all, you can modify static variables inside the method:
private static void changeValueOf(int value)
{
number1 = value;
}
But I guess that is not what you a looking for :)
In Java (and in most other languages) primitive data type (int, short, long, etc) passed by value, e.g. the copy of value passes to the method (function).
And reference types (objects, e.g. created with new operator) passed by reference. So, when you modigy the value of reference type (object) you can see the changes in the outer scopes (for example, in method caller).
So, the answer is no - you cannot change the value of int so that the outer scope would see the updated value.
Howewer, you could wrap your int values with some object - and it change the value inside of it:
public class Example {
public static void main(String[] args) {
Example app = new Example();
// Could be static as well
Holder val1 = new Holder(1);
Holder val2 = new Holder(2);
app.changeValue(val1, 7);
System.out.println(val1.value); // 7
}
public void changeValue(Holder holder, int newValue) {
holder.value = newValue;
}
static class Holder {
int value;
Holder(int value) {
this.value = value;
}
}
}
Also, you could create an array with 2 values and update them inside the method, but it's not very good approach IMO
And finally, you could just return updated value and assign it to your variables:
public class Example {
private static int number1 = 2;
private static int number2 = 3;
public static void main(String[] args) {
Example app = new Example();
number1 = app.mul(number1, 7);
number2 = app.mul(number2, 7);
System.out.println(number1); // 14
System.out.println(number2); // 21
}
public int mul(int a, int b) {
return a * b;
}
}
One possibility is to use an array to store your variables, instead of separate variables with numbers affixed. Then you would write number[1] instead of number1 for example. You can pass the array index number around to indicate which variable you are referring to.
public class MyClass
{
private static int[] variables = {1, 2};
public MyClass()
{
// change value of first variable
changeValueOf(0, 3);
// now variable[0] = 3
}
private static void changeValueOf(int number, int value)
{
variables[number] = value;
}
}

How to call an Array between classes?

Hello I am new to java so please be gentle,
class Result{
public float Mean(){
//find the mean of the array
}
public float lowest(){
// find the lowest
}
}
public class Main{
public static void main(String[] args) {
float arr[] = {1.1,2.2,3.3};
}
}
What I want to do is to take the array arr from Main, and bring it to class Result so that I can use it
in Mean() and Lowest().
Thank you.
Try add the array as part of constructor of Result/Solve, then you could work with numbers inside the instance you create.
class Solve {
final float[] numbers;
public Result(final float[] numbers){
this.numbers = numbers;
}
public float mean(){
//find the mean using the this.numbers
}
public float lowest(){
// find the lowest using this.numbers
}
}
public class Main{
public static void main(String[] args) {
float numbers[] = new float[]{1.1,2.2,3.3};
Solve solve = new Solve(numbers);
float mean = solve.mean();
float lowest = solve.lowest();
System.out.println("Mean: " + mean);
System.out.println("Lowest: " + lowest);
}
}
Another option is to make your methods static and pass the numbers as part of the methods, similar to Math class.
class Solve {
public static float mean(float[] numbers){
}
public static float lowest(float[] numbers) {
}
}
public class Main{
public static void main(String[] args) {
float numbers[] = new float[]{1.1,2.2,3.3};
float mean = Solve.mean(numbers);
float lowest = Solve.lowest(numbers);
System.out.println("Mean: " + mean);
System.out.println("Lowest: " + lowest);
}
}
Here's how I would handle this:
Result class:
class Result {
public static float mean(float... arr) { //make the method static, and have it take the array as a parameter
float sum = 0f;
for (float f : arr) { //add each number in the array to the sum variable
sum += f;
}
return sum / arr.length; //return sum / length, which is average
}
public static float lowest(float... arr) { //same as the above method
float lowest = arr[0];
for (float f : arr) { //loop through the array
if (f < lowest) { //if this number is lower than the current "lowest" number, set lowest to be this number
lowest = f;
}
}
return lowest; //return the lowest number
}
}
Main class:
public class Main {
public static void main(String[] args) {
float[] arr = new float[] { 1.1f, 2.2f, 3.3f }; //here's the array
System.out.println(Result.mean(arr)); //I pass it to the method as a parameter
System.out.println(Result.lowest(arr)); //same here
}
}
An alternative solution would be to use Java streams instead of for loops. Java streams can get more complicated than for loops, but they can be much cleaner and easier to read. Here's how I would rewrite the Result class using streams:
class Result {
public static float mean(float... arr) {
return (float) IntStream.range(0, arr.length)
.mapToDouble((i) -> arr[i])
.average()
.getAsDouble(); //returns the average of the array
}
public static float lowest(float... arr) {
return (float) IntStream.range(0, arr.length)
.mapToDouble((i) -> arr[i])
.min()
.getAsDouble(); //returns the minimum value in the array
}
}
Pass your array as an argument to the other object’s method.
float[] arr = { 1.1F, 2.2F, 3.3F } ;
Result r = new Result() ;
float output = r.lowest( arr ) ;
Define that argument on the method.
class Result{
public float mean( float[] input ){
// … find the mean of the array
}
public float lowest( float[] input ){
// … find the lowest
}
}
See this code run live at IdeOne.com.
Passing an argument/parameter to a method is a basic minimal skill in Java. You should study the Java Tutorials by Oracle, and consult a textbook to get the basics down.

Passing two variables to one method to get two results

I am trying to pass two variables along to a method and have the method give me back two independent results.
int numX = 5;
int numY = 3;
System.out.println(displayTwiceTheNumber(numX, numY));
}
public static int displayTwiceTheNumber(int numX, int numY) {
int numW, numZ;
numW, numZ = 2 * (numX, numY);
return numW numZ;
}
Java takes it that at numW, numZ = 2 * (numX, numY); that I am trying to redefine numX and numY. How do I phrase the last block to take two variables and give two results?
A single int function can only return 1 int at a time.
If you want to return 2 values, consider calling the function twice or creating a custom object to be used.
You need to change the return type of the function. Currently, the return type is int, so you have to return one integer.
To return two integer, you should consider returning an array or a list or something similar.
public static int[] displayTwiceTheNumber(int numX, int numY){
//your code that do something
int[] ret = {numW, numZ};
return ret;
}
Or knowing that this function would change the value of numW and numZ, you could declare those as global variable. Now, when you call this function, those variable will be changed. Then, you can use numW and numZ subsequently.
public int numW;
public int numZ;
public static void displayTwiceTheNumber(int numX, int numY){
//your code that do something and modifies numW and numZ
}
public static void anotherfunction(){
//after calling displayTwiceTheNumber, numW and numZ would have the appropriate value
//you can now just use numW and numZ directly
}
Overview: Use a tuple. In this example I use an tuple to return more than one result. Tuple means to return more than one result type. In this example I return a tuple of two integer types. My class TupleCustom contains one method function1 which receives two parameters of type integer: x and y. I create a tuple of type integer and return the tuple as a variable. Internally, the precomiler converts the tuple json than back to a tuple with variable Item1, Item2...ItemN in the unit test method.
public class TupleCustom
{
public async Task<Tuple<int, int>> Function1(int x, int y)
{
Tuple<int, int> retTuple = new Tuple<int, int>(x, y);
await Task.Yield();
return retTuple;
}
}
public class TestSuite
{
private readonly ITestOutputHelper output;
public TestSuite(ITestOutputHelper output)
{
this.output = output;
}
[Fact]
public async Task TestTuple()
{
TupleCustom custom = new TupleCustom();
Tuple<int, int> mytuple = await custom.Function1(1,2);
output.WriteLine($" Item1={mytuple.Item1} Item2={mytuple.Item2} ");
}
When I have this problem I create a private utility class for handling the return values. By doing it this way, you can pass various types in the argument list. Aspects of the class can be tailored to your requirements.
public static void main(String [] args) {
int numX = 5;
double numY = 3.0;
Nums n = displayTwiceTheNumber(numX, numY);
System.out.println(n.numX);
System.out.println(n.numY);
}
public static Nums displayTwiceTheNumber(int numX, double numY) {
int numW;
double numZ;
// do something with arguments.
// in this case just double them and return.
return new Nums(2*numX, 2*numY);
}
private static class Nums {
int numX;
double numY;
public Nums(int nx, double ny) {
this.numX = nx;
this.numY = ny;
}
public String toString() {
return "(" + numX + ", " + numY +")";
}
}
Prints
10
6.0

issue with Arrays.asList()

I have a very simple program and I just need to check an array for a value in it.
I have a class called bulkBean. this is it.
public class bulkBean {
private int installmentNo;
private double amount;
public int getInstallmentNo() {
return installmentNo;
}
public void setInstallmentNo(int installmentNo) {
this.installmentNo = installmentNo;
}
public double getAmount() {
return amount;
}
public void setAmount(double amount) {
this.amount = amount;
}
}
Now I have an array of this bulkBean type in my program, this is my program.
import java.util.Arrays;
public class test {
public static boolean scan_bulkList(bulkBean[] bulkList, int i) {
int[] arr = new int[bulkList.length];
for(int x=0;x<bulkList.length;x++){
arr[x] = bulkList[x].getInstallmentNo();
}
for(int j = 0; j< arr.length ;j++){
System.out.println("INFO: array "+j+" = "+arr[j]);
}
if (Arrays.asList(arr).contains(i) == true) {
return true;
} else {
return false;
}
}
public static void main(String[] arg){
bulkBean bb1 = new bulkBean();
bb1.setInstallmentNo(1);
bb1.setAmount(5500);
bulkBean bb2 = new bulkBean();
bb2.setInstallmentNo(2);
bb2.setAmount(4520);
bulkBean[] bulkArray = new bulkBean[2];
bulkArray[0] = bb1;
bulkArray[1] = bb2;
boolean a = scan_bulkList(bulkArray,1);
System.out.println("val = "+a);
}
}
I create 2 instances of bulk bean and I set values to them. Then I added those two instances to an array. Then I pass that array to the method to check for a value(also given as a parameter. In this case it is 1.). If the array contains that value, it should return true, otherwise false.
whatever value I enter, it return false.
Why do I get this issue?
Arrays.asList() returns a List which has a single element - an array. So, you are actually comparing against an array. You need to compare against each value in the array.
As TheListMind told, Arrays.asList() taken on an int[] gives you a list containing the array.
Personally, I would construct directly the List instead of constructing the array, or even better (no need of array instanciation), test while iterating the bulk array :
for(int x=0;x<bulkList.length;x++){
if (bulkList[x].getInstallmentNo() == i){
return true;
}
}
return false;
The mistake you made here is , you created the int array which must be Integer array because Arrays.asList().contains(Object o); makes the input parameter also Integer(Integer i). int is not an object Integer is the object. Hope it will work.
int[] arr = new int[bulkList.length];
change to:
Integer[] arr = new Integer[bulkList.length];
Change the method as below to avoid complications:
public static boolean scan_bulkList(bulkBean[] bulkList, int i) {
int[] arr = new int[bulkList.length];
for(int x=0;x<bulkList.length;x++){
arr[x] = bulkList[x].getInstallmentNo();
if (bulkList[x].getInstallmentNo()==i) {
return true;
}
}
return false;
}

How do I call an Array constructor initializing the Array length?

How do I make a constructor to set the length of a global array?
I have already tried several ways to do it, none successful.
Example:
public Class{
public Class(int length){
double[] array = new double[length]; <- this is not global
L = length;
}
int L;
double[] array = new double[L]; <- this does not work
}
I need an array with a length determined by Constructor.
I think it's as simple as this:
public class MyClass{
double[] array;
public MyClass(int length){
array = new double[length];
}
}
I've also made the code actually compile :) You were missing some keywords etc.
If you want to access length in your code, use array.length rather than storing it redundantly in a separate field.
Also calling your class Class is a bad choice, even as an example, because it clashes with java.lang.Class.
Declare the array as member variable. Then initialize it in the constructor.
public class A{
private double[] array;
public Class(int length){
array = new double[length];
L = length;
}
}
You could initialize it in second way. But then you need to use a fixed length
public class A{
private double[] array = new double[100]; // use fixed length
public Class(int length){
array = new double[length];
L = length;
}
}
I don't know what you are trying to achieve but why you don't simply do it this way:
public class Class{
public Class(int length){
this.array = new double[length]; // <- this is not global
}
double[] array;
}
public class aClass{
//define the variable name here, but wait to initialize it in the constructor
public double[] array;
public aClass(int length){
array = new double[length];
}
}
You can do it
public class Test {
double[] array;
public Test (int length){
array = new double[length]; <- this is not global
}

Categories