If my method return an array how can I link for it?
private int[] osszesVizsgalata(int currentFord){
int[] truefalse = new int[2];
for(int i = 0; i<currentFord-1;i++){
if(this.ellenfelValaszai[i] == true){truefalse[1]++;}
else{truefalse[0]++;}
}
return truefalse;
}
This is my method and I cant call it that I can use both element of truefalse.
osszesVizsgalata(2)[0];
This is my try.
Declare an array in the client method and initialize it with the result of this method:
public void clientMethod() {
int currentFord = 2;
int[] foo = osszesVizsgalata(currentFord);
//code used for example purposes
System.out.println(foo[0]);
}
Related
So I have this code in the main class
public class OneDArrays
{
public static int[] create (int size)
{
int[] a1 = new int[size];
for (int i = 0; i < size; i++)
{
a1[i] = i*2+1;
}
return a1;
}
public int sumSome (int[] b1, int howmany)
{
int sum = 0;
if (howmany <= b1.length)
{
for (int i = 0; i < howmany; i++)
{
sum = sum + b1[i];
}
}
else
{
sum = -1;
}
return sum;
}
public int[] grow (int[] c1, int extra)
{
int[] newArray = new int[c1.length+extra];
for (int i = 0; i < newArray.length; i++)
{
while (i <= c1.length)
{
newArray[i] = c1[i];
i++;
}
newArray[i] = 0;
}
return newArray;
}
public void print (int[] d1)
{
for (int i = 0; i < d1.length; i++)
{
System.out.println (d1[i] + ", ");
}
}
}
And then I have my tester class,
public class OneDArraysTester
{
public static void main (String[] args)
{
int[] test1;
test1.create (5);
}
}
How do retrieve the method from the first class? I get the error that "create" is an undeclared method. If the "create" method were a constructer, I know I could just type create test1 = new create (5) but I don't see a way to turn it in to a constructer, so what's the way of doing that but for a method?
You invoke a static method with the classname. Literally className.methodName. Like,
int[] test1 = OneDArrays.create(5);
You have made a class named OneDArrays so you can call it's methods by creating an instance or object of that class.
like this :
OneDArrays ObjectOfClass = new OneDArrays();
int test1[] = ObjectOfClass.create(5);
similarly you can also call other methods of that class by accessing methods of this newly created object ObjectOfClass.
like :
sumOfArray = ObjectOfClass.sumSome(test1,3);
int biggerTest1[] = ObjectOfClass.grow(test1,10);
If you want to make create method works as a constructor than you can but you cannot return value from a constructor so you cannot return your array from that constructor.
Since you have declared the create method as static, #ElliotFrisch is the best way. But, it is not always a good idea to make methods static. So another way to achieve what you want would be to make the create method non-static.
public int[] create (int size){/*Method Body*/};
And then create an object of the OneDArray class to access the method.
OneDArrays oneDArrays = new OneDArrays();
int[] test1 = oneDArrays.create(5);
or,
int[] test1 = new OneDArrays().create(5);
This code generates unsorted array. My question is how do I clone the generated array so I can reuse the unsorted array in different sorting algorithms.
public class UnsortedData{
private int [] coreData;
private int maxArraySize;
private int currentArraySize;
public UnsortedData(int size){
this.maxArraySize = size;
this.coreData = new int[this.maxArraySize];
this.currentArraySize = 0;
}
public boolean addData(int data){
if (currentArraySize < maxArraySize)
{
coreData[currentArraySize] = data;
currentArraySize++;
return true;
}
return false;
}
public class dataSorting {
public static void main(String[] args) {
Random rand = new Random();
UnsortedData uD = new UnsortedData(1000000);
for (int x = 0; x < 50; x++) {
uD.addData(rand.nextInt(3000000));
}
}
Use build in methods from java.lang.Object to clone the original array and java.util.Arrays to sort the cloned array.
int[] arr = {6,9,4,5}; // original array
int[] arrCopy = arr.clone() // we created a copy of the array
Arrays.sort(arrCopy); // it sort the array that we cloned
References: Arrays Class , Class Object
Easiest way? Object.clone()
int[] arr = coreData.clone();
You can also use the Stream API or external libraries such as Apache Commons.
This question already has answers here:
How to convert an int array to String with toString method in Java [duplicate]
(8 answers)
Closed 6 years ago.
I am trying to print array's content with
toString()
and I can't figure out what I am doing wrong.
The output should be 5 random numbers from 0 to 100 which I will store in array after all I have to print them all.
Here is my code:
public class Ary {
private int[] anArray;
private int arraySize;
private String numberAsString;
Random r = new Random();
public Ary(int arraySize) {
this.anArray = printArray();
}
public Ary() {
arraySize = 2;
printArray();
}
public int getArraySize() {
return arraySize;
}
public void setArraySize(int arraySize) {
this.arraySize = arraySize;
}
public int[] printArray() {
// Assign anArray with a custom number
anArray = new int[arraySize];
for(int numbers : anArray) {
anArray[numbers] = r.nextInt(100);
System.out.println(anArray[numbers] + " ");
}
return anArray;
}
#Override
public String toString() {
return "Array = " + Arrays.toString(anArray);
}
}
Output:
Music.app.Ary#5e2de80c
Here is my code with Arrays.toString():
public int[] printArray() {
// Assign anArray with a custom number
anArray = new int[arraySize];
for(int numbers : anArray) {
anArray[numbers] = r.nextInt(100);
System.out.println(Arrays.toString(anArray));
}
return anArray;
}
I've already tried tons of methods but still haven't figure it out.. Can you please explain what am I doing wrong?
Thank you very much!
You've changed the signature of toString() (so you aren't calling the method you have defined). Instead, you need something like1,
#Override
public String toString() {
return "Array = " + Arrays.toString(anArray);
}
And you should probably initialize anArray in your constructor(s)2 and remove "printArray"
public Ary(int arraySize) {
this.arraySize = arraySize;
this.anArray = new int[arraySize];
for (int i = 0; i < arraySize; i++) {
this.anArray[i] = r.nextInt(101); // <-- [0, 100], or [0, 101)
}
}
public Ary() {
this(5); // <-- use the other constructor.
}
1And the override annotation will alert you to this mistake.
2And you shouldn't print the array until you finish initializing it.
This is a custom method System.out.print(array.toString());
so you overloaded the toString() BUT for printing out the object in the console is the toString() method (no params) what is getting invoked...
remove the int[] parameter and it will called normally, you need for sure modify the body of the method too
public String toString() {
return "Array = " + Arrays.toString(a);
}
ussing teh override annotation will be recommended always, it will prevent that errors while writing the code....
Can I pass the return value from a method into the main method then utilize that value in another method? That sounds confusing but let me try to explain it better with some code...
public static void main(String[] args){
ArrayList<GeometricObject> geoList = new ArrayList<GeometricObject>();
findPositionLargestObject(geoList);
System.out.println("BIGGEST OBJECT AT "+ maxIndex +" AREA =
"+geoList.get(maxIndex).getArea());
showObjects(geoList.get(maxIndex));
}
//METHOD RETRIEVING INT OF ARRAYLIST
private static int findPositionLargestObject(
ArrayList<GeometricObject> geoList) {
int maxIndex = 0;
for (int i = 1; i < geoList.size(); i++) {
// AREA OF I COMPARES MAX INDEX
if (geoList.get(i).getArea() > geoList.get(maxIndex).getArea()) {
maxIndex = i;
}
}
return maxIndex;
}
// METHOD FOR PRINTING SINGLE OBJECT OF ARRAYLIST
private static void showObjects(GeometricObject geometricObject) {
System.out.println(geometricObject.toString());
}
Lets say I even instantiate the index in the main method such as
int maxIndex = 0;
I want the first method called to return the value, assign that value to the variable maxIndex then utilize that value for the showObjects method. Thanks for any insight that can be given to a coding novice like myself. Is instantiating the variable in the main method no good? What is the logic behind the JAVAC execution here?? The curriculum covered in my course feels like this is an enormous hole that needs to be filled. Basically, How do I utilize a value returned from a method then implement into another method?
Variables are only containers for a value bound to its type. If a method is returning a type, you can place it's return value in a variable located in another block of code. To provide a very basic example for an easier understanding of how this can work:
private String getString(int number) {
if (number == 2) {
return "Not One";
}
return "One";
}
private void printValue(String number) {
if (number.equals("One")) {
System.out.println("i is 1");
} else {
System.out.println("i is not one");
}
}
public static void main(String[] args) {
int i = 1;
String testNum = getString(i);//returns "One"
printValue(testNum);//output: i is 1
}
With this example in mind,
int maxIndex = findPositionLargestObject(geoList);
showObjects(geoList.get(maxIndex));
is valid.
Unless I'm missing something, assign the result of your function call. I suggest you program to the List interface. Also, if using Java 7+ you could use the diamond operator <> like
List<GeometricObject> geoList = new ArrayList<>(); // <-- diamond operator
// ... populate your List.
int maxIndex = findPositionLargestObject(geoList);
and then yes you can use the variable maxIndex
you can obtain the return value in main method like this,
int maxIndex=findPositionLargestObject(geoList);
Code:
public static void main(String[] args){
ArrayList<GeometricObject> geoList = new ArrayList<GeometricObject>();
int maxIndex=findPositionLargestObject(geoList);
System.out.println("BIGGEST OBJECT AT "+ maxIndex +" AREA =
"+geoList.get(maxIndex).getArea());
showObjects(geoList.get(maxIndex));
}
//METHOD RETRIEVING INT OF ARRAYLIST
private static int findPositionLargestObject(
ArrayList<GeometricObject> geoList) {
int maxIndex = 0;
for (int i = 1; i < geoList.size(); i++) {
// AREA OF I COMPARES MAX INDEX
if (geoList.get(i).getArea() > geoList.get(maxIndex).getArea()) {
maxIndex = i;
}
}
return maxIndex;
}
// METHOD FOR PRINTING SINGLE OBJECT OF ARRAYLIST
private static void showObjects(GeometricObject geometricObject) {
System.out.println(geometricObject.toString());
}
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;
}