How can I get values from function that is inside of class? - java

I want to get some values from one function inside of different class and use it on Main class. But it seems like I am doing somethings wrong.
public class test {
public static int enkucukbul ( double[] x){ // this method finds the smallest index
return IntStream.range(0, x.length)
.mapToObj(i -> i)
.min(Comparator.comparing(i -> x[i]))
.orElse(Integer.MIN_VALUE);
}
public static double tabu(double x, int isayi) {
Random rrandom = new Random();
float r;
double[] fxdizi = new double[4];
double[] xdizi = new double[4];
double[] hareket = new double[4];
for (int j = 0; j < isayi; j++) {
r = rrandom.nextFloat();
hareket[0] = x + 2 * r;
hareket[1] = x + 4 * r;
hareket[2] = x - 2 * r;
hareket[3] = x - 4 * r;
xdizi[0] = hareket[0];
xdizi[1] = hareket[1];
xdizi[2] = hareket[2];
xdizi[3] = hareket[3];
for (int i = 0; i < 4; i++) {
if (xdizi[i] <= 1) {
fxdizi[i] = xdizi[i] * xdizi[i];
} else {
fxdizi[i] = Math.pow((xdizi[i] - 3), 2) - 3;
}
} // for dongusu
int minIndex = enkucukbul(fxdizi); // found the smallest index
return x;
return minIndex;
return j;
return xdizi[minIndex];
return fxdizi[minIndex];
x = xdizi[minIndex]; // we found the smallest x
} // all things
}
}
Also my Main class:
public class Main {
public static void main(String[] args) {
test ts = new test();
System.out.println(ts.tabu(7.26,2));
}
}
I just want to get the values in return statements like x, j ...etc. But I get error "java:unreachable statement" on every return statement and also "java:missing return statement" in the end. Where do i do wrong?
Extra Note: I'm sorry for the localized variable names since this is my optimization class assignment

You've wrote multiple return statements in following lines :
return x;
return minIndex;
return j;
return xdizi[minIndex];
return fxdizi[minIndex];
It is not acceptable in java.
Also you are missing return value at the end of method tabuoutside of for loop. I see several logical mistakes in your code.
You need to refactor your code, also if you can explain what you are trying to achieve it will be much more clear.

In java a method can have only one return statement. You can't have more than one return statement per method unless used in an if-else block.
As the compiler tells you the remaining statements are unreachable after the first return statement.
As per your latest comment, you can create a wrapper class to hold multiple values that you want to return. For eg :
class Calculation {
public double a;
public double b;
// getters and setters
}
Now from your method you could capture the values of the variables and then store them in an object of the class created above :
public static Calculation tabu(double x, int y) {
Calculation cal = new Calculation();
// do something with x and y and other things
cal.setA(x);
cal.setB(y);
return cal;
}

Related

How to use loops to find the exponent of a base that produces an argument

I am attempting to use loops to find the exponent of a given base that produces a specific argument. For example, in the equation 5^x=625, 5 would be the base and 625 would be the argument. I know that in that equation x=4 but I am unsure of how to get 4 in my return.
Here is what I have so far:
public static int log(int base, int argument) {
int result = 1;
for (int i=0; i<=; i++)
result = ;
return result;
}
I am unsure what to put for my condition statement and my result. What am I missing here?
edit: I forgot to mention that I am attempting to do this without using the math library. I also thought it might help to include my code for finding the powers:
public static int pow(int base, int exponent) {
int result = 1;
for(int i=0; i<exponent; i++) {
result = result*base;
}
return result;
I essentially just trying to reverse this to find the exponent.
Something like that:
public static int log(int base, int argument) {
if(argument <= 0 || base <= 0) {
throw new IllegalArgumentException("This method only works with positive integers");
}
int result = 1;
int i = 0;
while(result < argument) {
result = result * base;
i++;
}
if(result == argument) {
return i;
} else {
throw new IllegalArgumentException("There is no integer for x in base^x = argument");
}
}
This as some flaws as it handle all cases but it's a start.
This is more of a math question.
For the formula 5^x = 625, you find x using x = log₅(625) = log(625)/log(5).
So:
public static int log(int base, int argument) {
return (int) (Math.log(argument) / Math.log(base));
}
But maybe you already knew this, since you named the method right.
Count how many times you can divide the argument by the base while the result is 1 or greater:
public static int log(int base, int argument) {
int result;
for (result=0; argument>=1 ; result++) {
argument = argument/base;
}
return result;
}

GC overhead limit exceeded - Arrays

i get this error after waiting long time for my code to execute and its pointing me to this method
public Iterable<Board> neighbors() {
Queue<Board> q = new LinkedList<>();
int n = dimension();
int x = 0, y = 0;
outer:
// do some stuff to get the x and y
if (y+1 < n) {
the line where i get the error -> int [][]arr = new int[n][n];
for (int i = 0; i < tiles.length; i++) {
arr[i] = Arrays.copyOf(tiles[i], n);
}
// do some stuff
Board br = new Board(arr);
if(!this.equals(br)) {
q.add(new Board(arr));
}
}
if (y-1 >= 0) {
int [][]arr = new int[n][n];
for (int i = 0; i < tiles.length; i++) {
arr[i] = Arrays.copyOf(tiles[i], n);
}
// do some stuff
Board br = new Board(arr);
if(!this.equals(br)) {
q.add(new Board(arr));
}
}
if (x-1 >= 0) {
int [][]arr = new int[n][n];
for (int i = 0; i < tiles.length; i++) {
arr[i] = Arrays.copyOf(tiles[i], n);
}
// do some stuff
Board br = new Board(arr);
if(!this.equals(br)) {
q.add(new Board(arr));
}
}
if (x+1 < n) {
int [][]arr = new int[n][n];
for (int i = 0; i < tiles.length; i++) {
arr[i] = Arrays.copyOf(tiles[i], n);
}
// do some stuff
Board br = new Board(arr);
if(!this.equals(br)) {
q.add(new Board(arr));
}
}
return q;
}
i basically need to copy tiles array and make changes to the copy "arr" but keep the tiles array without changing to use it later..i really don't like the way i'm doing it copying and pasting code i think its inefficient but no other way comes to my mind so i would like to know why i get this error "i know its because GC taking more time and not doing alot" but i want to know why its happening in this case also if there is better way to copy the array.
also i increased the heap memory to -Xmx1600m
Thanks for your time.
The Problem
It is likely that the problem arises from creating a lot of objects in a short period of time. See this answer for more information.
At the moment, one Board consist of at least four objects:
The Board itself
The array arr inside the board
The three arrays inside arr
Creating Less Objects
Our goal is to create fewer objects (arrays). Since you want to deal with small boards only, we could use one long to store the complete 3×3 board. A long has 64 bit. We use 64 / 9 = 7 bits per field to store the value on that field:
state = ... 0000100 0000011 0000010 0000001 0000000
4th field ↑ 2nd field ↑ 0th field
3rd field 1st field
The following class handles the bit operations.
class Board {
private final static int SIDE_LENGTH = 3;
private final static int FIELDS = SIDE_LENGTH * SIDE_LENGTH;
private final static int BITS_PER_FIELD = 64 / FIELDS;
private final static long FIELD_MASK = (1 << BITS_PER_FIELD) - 1;
private long state;
public Board() {
for (int field = 0; field < FIELDS; ++field) {
set(field, field);
}
}
/** Copy constructor. */
public Board(Board other) {
this.state = other.state;
}
public int get(int x, int y) {
return get(coordinatesToField(x, y));
}
public void set(int x, int y, int value) {
set(coordinatesToField(x, y), value);
}
private int coordinatesToField(int x, int y) {
return SIDE_LENGTH * y + x;
}
private int get(int field) {
return (int) ((state >>> (field * BITS_PER_FIELD)) & FIELD_MASK);
}
private void set(int field, int value) {
int shift = field * BITS_PER_FIELD;
state &= ~(FIELD_MASK << shift);
state |= (long) value << shift;
}
public String toString() {
StringBuilder sb = new StringBuilder();
for (int field = 0; field < FIELDS; ++field) {
sb.append(get(field));
sb.append((field + 1) % SIDE_LENGTH == 0 ? "\n" : "\t");
}
return sb.toString();
}
// TODO implement equals and hashCode
}
When using this class, you don't have to deal with arrays anymore, which saves not only a lot of objects, but also the copy code in your prorgram.
The class also works for 1×1, 2×2, and 4×4 boards, but not for larger ones due to the 64 bit limit.
Usage Examples
public static void main(String[] args) {
// Create and print the initial board
// 0 1 2
// 3 4 5
// 6 7 8
Board b = new Board();
System.out.println(b);
// Copy an existing board
Bord copy = new Board(b);
// Set the upper right field to value 8
copy.set(2, 0, 8);
// Print the center field
// 4
Syste.out.println(copy.get(1, 1));
}
Additional Ideas
You even could avoid creating Board objects at all, and just store the long values. But that doesn't help when you are using generics (such as LinkedList) because of Java's auto boxing.
Also note that LinkedList wraps each entry in an additional node object. Maybe you can use a more efficient DataStructure like a circular buffer.
Depending on what you are doing, you might as well have a look at the Flyweight design pattern.

How to merge two sorted arrays in Java?

I'm trying to create a third sorted array, c, from the two previously created arrays, a and b; however, I'm getting several errors within the merge method that say "The type of the expression must be an array type but it resolved to OrdArray". I've been at it for hours already, and feel like my brain is mush now. Can someone help me out?
class OrdArray
{
private long[] a; // ref to array a
private int nElems; // number of data items
//-----------------------------------------------------------
public OrdArray(int max) // constructor
{
a = new long[max]; // create array a
nElems = 0;
}
//-----------------------------------------------------------
public int size()
{ return nElems; }
//-----------------------------------------------------------
public int find(long searchKey)
{
int lowerBound = 0;
int upperBound = nElems-1;
int curIn;
while (true)
{
curIn = (lowerBound + upperBound ) / 2;
if (a[curIn] == searchKey)
return curIn; // found it
else if (lowerBound > upperBound)
return nElems; // can't find it
else // divide range
{
if (a[curIn] < searchKey)
lowerBound = curIn + 1; // it's in upper half
else
upperBound = curIn - 1; // it's in lower half
} // end else divide range
} // end while
} // end find()
//-----------------------------------------------------------
public void insert(long value) // put element into array
{
int j;
for (j = 0; j < nElems; j++) // find where it goes
if (a[j] > value) // (linear search)
break;
for (int k = nElems; k > j; k--) // move bigger ones up
a[k] = a[k-1];
a[j] = value; // insert it
nElems++; // increment size
} // end insert()
//-----------------------------------------------------------
public boolean delete(long value)
{
int j = find(value);
if (j == nElems) // can't find it
return false;
else // found it
{
for (int k = j; k < nElems; k++) // move bigger ones down
a[k] = a[k+1];
nElems--; // decrement size
return true;
}
} // end delete()
//-----------------------------------------------------------
public void display() // displays array contents
{
for (int j = 0; j < nElems; j++) // for each element,
System.out.print(a[j] + " "); // display it
System.out.println("");
}
//-----------------------------------------------------------
public static long[] merge(OrdArray a, OrdArray b)
{
long[] c = new long[a.nElems + b.nElems];
int i = 0, j = 0, k = 0;
while (i < a.nElems && j < b.nElems)
{
if (a.data[i] < b.data[j])
c[k++] = a.data[i++];
else
c[k++] = b.data[j++];
}
while (i < a.nElems)
c[k++] = a.data[i++];
while (j < b.nElems)
c[k++] = b.data[j++];
return c;
}
} // end class OrdArray
////////////////////////////////////////////////////////////////
class OrderedApp
{
public static void main(String[] args)
{
int maxSize = 100; // array size
OrdArray a, b, c; // reference to array
a = new OrdArray(maxSize); // create the array
b = new OrdArray(maxSize);
c = new OrdArray(maxSize);
a.insert(11);
a.insert(13);
a.insert(15);
a.insert(17);
a.insert(19);
a.insert(21);
a.insert(23);
a.insert(25);
a.insert(27);
a.insert(29);
b.insert(12);
b.insert(14);
b.insert(16);
b.insert(18);
b.insert(20);
b.insert(32);
b.insert(24);
b.insert(26);
b.insert(28);
b.insert(30);
OrdArray.merge(a,b);
System.out.print("Array a: ");
a.display();
System.out.println();
System.out.print("Array b: ");
b.display();
System.out.println();
System.out.print("Array c: ");
c.display();
System.out.println();
} // end main()
}// end class OrderedApp
OrdArray is not an array type (despite the name); therefore, you can't index it like an array. This expression
a[i++]
where a is an OrdArray, will have no meaning. Java doesn't give you a way to define your own [] operator for classes (unlike C++). Therefore, you'll have to add a method to OrdArray to return the element at a given index, something like
public long get(int index) { ...write the code... }
a.get(i++) // will then get the element at that index
Although I'm not sure this is what you want, since you've declared c to be an int[] and the array in OrdArray to be a long[], so I'm not sure what you're trying to do.
EDIT: After reading your comment, I realized that the merge method is inside the OrdArray class. I missed that before. Since that's the case, you don't need to add a get method; you can access the private fields of your OrdArray parameters directly. In your method:
public void merge(OrdArray a, OrdArray b)
you want to get at the private array a that you declare for each OrdArray. If you just use a, the variable will refer to the OrdArray, which isn't an array (as described above); to get at the long[] a belonging to the OrdArray a, you need to say
a.a[i++]
and likewise, for b,
b.a[i++]
This can look confusing to a reader, so I suggest coming up with a better name so that you're not calling two things a. Perhaps data?
A couple other things: You use merge like this: c.merge(a,b), which means that merge is an instance method and c is the instance you're operating on. But your method doesn't do anything with the current instance. (The c you declare in merge is a local variable that has nothing to do with the c you use when calling merge.) Right now, your method is going to a lot of trouble to construct the local array c, but then it just throws it away. You either need to (1) fix the method so that it sets up the a (or data) array in the current instance; or (2) make it a static method and make the method return the new array as a function result. I'm not sure which one your instructor wants you to do.
I'm not exactly sure what you are trying to do. But to resolve error, i have corrected the articular block.
To note, OrdArray class is not an array. It's a class that has a long[] a. So you need to get the array like any other property from the object.
For betterment, please change the method signature like this:
public void merge(OrdArray ordArr1, OrdArray ordArr2) {//Note parameters' name change
.
.
.
while (i < ordArr1.nElems && j < ordArr2.nElems)
{
if (ordArr1.a[i] < ordArr2.a[j]) //should resolve
c[k++] = ordArr1.a[i++];
else
c[k++] = ordArr2.a[j++];
}
while (i < a.nElems)
c[k++] = ordArr1.a[i++];
while (j < b.nElems)
c[k++] = ordArr2.a[j++];
}
If you accept solution wit Lists it would be:
List<Integer> result = new ArrayList<Integer>(Arrays.asList(sourceArray));
result.addAll(Arrays.asList(secondSourceArray));
Collections.sort(result);
You can optionally convert it back to array with
result.toArray();
I am confused why you are using binary search. Simple way is to insert two arrays using two insert methods or one. Using a merge method, just merge those two already sorted arrays by comparing the least element among two sorted arrays.
Remove delete, search etc methods, they are not required.
This is my code. I have inserted two integer arrays(elements) into inserta() and insertb() sorted them and merged them using insert() method. Finally I have this sorted array after merging them. Please see my code here:
package sample;
/**
*
* #author Shivasai
*/
public class Merge {
int i;
int j;
int k;
int n;
int m;
int p;
private long[] a;
private long[] b;
private long[] c;
public Merge()
{
a=new long[10];
b=new long[10];
c=new long[100];
n=0;
m=0;
p=0;
}
void inserta(long key)
{
for(i=0;i<n;i++)
{
if(a[i]>key)
break;
}
for(j=n;j>i;j--)
{
a[j]=a[j-1];
}
a[j]=key;
n++;
}
void insertb(long value)
{
for(i=0;i<m;i++)
{
if(b[i]>value)
break;
}
for(j=m;j>i;j--)
{
b[j]=b[j-1];
}
b[j]=value;
m++;
}
void insert()
{
i=0;
j=0;
while(i>n || j<m)
{
if(a[j]<b[i])
{
c[p]=a[j];
j++;
p++;
}
else
{
c[p]=b[i];
i++;
p++;
}
}
}
void displaya()
{
for(k=0;k<10;k++)
{
System.out.print("," +a[k]);
}
System.out.println();
}
void displayb()
{
for(k=0;k<10;k++)
{
System.out.print("," +b[k]);
}
System.out.println();
}
void displayc()
{
for(k=0;k<20;k++)
{
System.out.print("," +c[k]);
}
}
public static void main(String[] args)
{
Merge obj = new Merge();
obj.inserta(25);
obj.inserta(12);
obj.inserta(1800);
obj.inserta(9);
obj.inserta(10);
obj.inserta(15);
obj.inserta(18);
obj.inserta(19);
obj.inserta(0);
obj.inserta(1500);
obj.insertb(36);
obj.displaya();
obj.insertb(2);
obj.insertb(3);
obj.insertb(2000);
obj.insertb(5);
obj.insertb(6);
obj.insertb(7);
obj.insertb(8);
obj.insertb(21);
obj.insertb(85);
obj.displayb();
obj.insert();
obj.displayc();
}
}

Java - continues adding value on integer

im having a little problem about my codes
public class ex{
public static void main(String[] args) {
int sum,int a = 1,int b = 2;
int c = 1,int d = 2;
if (a<b) {
sum = sum+1;
}
if (c<b) {
sum = sum+1;
}
System.out.println("output :"+sum);
}
}
I wanted to add a value of 1 in the int sum if the conditions are met. but its not compiling
the output should be like this:
output: 2
First things first.. If you are a beginner to Java, this is an advise for you to learn well about the syntax of Java declaration, initialization and usage.
Declaration:
If you want to declare variables separately, you have to do it as below:
int a;
int b;
int c;
If you want to declare multiple variables in a single line, you have to do it as below:
int a,b,c;
Initialization:
If you want to initialize multiple variables in a single line, do it as below:
int a=0, b=4, c=3;
Usage:
Important thing you would like to learn here is - you can always declare 'n' number of variables without initialization.. but if you want to use any of them, they must be initialized at least once before you use them. Using them also includes even to print them.
If you won't follow any of the above mentioned points, you must get a compilation error.
Here is the code you must follow:
public class ex{
public static void main(String[] args) {
int sum = 0 , a = 1, b = 2;
int c = 1, d = 2;
if (a < b) {
sum = sum + 1;
}
if (c < b) {
sum = sum + 1;
}
System.out.println("output :"+sum);
}
}
public class TestExample {
public static void main(String args[]){
int sum = 0 ;
int a = 1;
int b = 2;
int c = 1;
int d = 2;
if (a<b) {
sum = sum+1;
}
if (c<b) {
sum = sum+1;
}
System.out.println("output :"+sum);
}
}
declaration of variable is wrong you should not declare your variable like int a,int b= 10
avoid declaration of variable on same line.
your code gives compilation error try this one it will give output as your expectation
Don't declare variables on the same line like this, even when it's compilable. It compacts your code in a way that makes it difficult to understand, especially when you name them a,b,c and d.
int sum = 0;
int a = 1;
int b = 2;
int c = 1;
int d = 2;
Change your declaration of variables to that and the rest of the code will run fine. But I would recommend reading some basic Java tutorials so you understand how to write code that compiles. I would also suggest using an IDE so these kinds of errors are flagged while you write your code.
IDEOne (with compilation errors): http://ideone.com/rYzIf5
IDEOne (without compilation errors): http://ideone.com/rYzIf5
Try this:
int sum = 0,a = 1,b = 2;
int c = 1, d = 2;
if (a<b) {
sum++;
}
if (c<b) {
sum++;
}
System.out.println("output :"+sum);

Math.random() problems in method

this might not be the hardest thing to acheive, yet I'm still having problems :S:
In my little program I'm simulating a card game (http://tinyurl.com/pf9fhf4) and I need to generate a random number from the range [0,35] in increments of 5. Ergo, the possible values should be : 0, 5, 10, 15, 20, 25, 30, 35.
I've tried this in a sepparate class first like this:
class RandomValue {
public static void main (String [] args){
int i =0;
do {
int n = (int) (Math.random()*36 );
if (n%5 ==0){
System.out.println(n);
i++;
}
} while (i <1);
}
}
And this works!!!
When I tried making a method that would return this generated value :
public class Tarot {
public static int rValue (){
int i =0;
do {
int n = (int) (Math.random()*36 );
if (n%5 ==0){
int r =n;
i++;
}
}while(i<1);
return r;
}
}
it returns an error:
Tarok.java:14: error: cannot find symbol
return r;
^
What am I doing wrong, any suggestions how to do this in a more pretty way?
r is known only in the scope of the if:
if (n%5 ==0) {
int r =n; //r is known only between the braces of the if
i++;
}
//I know r here said no one ever
Declare r outside the scope of the if.
I highly recommend you to indent your code for clarity and possible bug prevention.
change this code
public class Tarot {
public static int rValue (){
int i =0;
do {
int n = (int) (Math.random()*36 );
if (n%5 ==0){
int r =n;
i++;
}
}while(i<1);
return r;
}
}
to
public class Tarot {
public static int rValue (){
int i =0;
int r =0
do {
int n = (int) (Math.random()*36 );
if (n%5 ==0){
r=n;
i++;
}
}while(i<1);
return r;
}
}
reason
The scope of variable r is within if loop So when trying to return r compiler did not find r
It is easier to just generate numbers divisible by 5:
public static int rValue() {
return Random.nextInt(8) * 5;
}
Hello you are defining your "r" variable inside of the while loop scope, but trying to return it inside of the method scope. So just move your "r" variable definition to the begining of method as you do for "i".
r variable is not defined, and return statement can't see it.
Try to make so:
int r = 0;
do {
int n = (int) (Math.random()*36);
if (n%5 == 0){
r = n;
i++;
}
} while(i < 1);
return r;
And for what do you use this? U tryed to find first random number, that share out for 5

Categories