Math.random() problems in method - java

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

Related

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

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;
}

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;
}

Java sum algorithm not returning anything

I'm trying to solve the two sum algorithm on Leetcode:
Given an array of integers, return indices of the two numbers such that they add up to a specific target. You may assume that each input would have exactly one solution, and you may not use the same element twice.
And came up with this:
public class Leet {
public static void main(String[] args) {
System.out.println(Arrays.toString(twoSum(new int[]{1, 2, 3, 4, 5, 6}, 2)));
}
public static int[] twoSum(int[] nums, int target) {
int[] answer = null;
int i = 0;
for (int j = nums[i]; i < nums.length; i++) {
for (int x : nums) {
if (x != j & (j + x) == target) {
int x2 = java.util.Arrays.asList(nums).indexOf(x);
answer[0] = i;
answer[1] = x2;
} else {
return nums;
}
}
}
System.out.println("leet method executed");
return answer;
}
}
The problem is it's not returning anything, not event the printed statement. Any ideas?
See some fixes. Remember about array initialization and cases when values can be same in the array.
public class Solution {
public int[] twoSum(int[] nums, int target) {
int[] answer = null;
for(int i=0;i<nums.length;i++) {
int value = nums[i];
for(int j=i+1;j<nums.length;j++) {
int x=nums[j];
if ((value+x)==target) {
answer = new int[2];
answer[0]=i;
answer[1]=j;
}
}
}
System.out.println("leet method executed");
if (answer == null) {
return nums;
}
return answer;
}
}
I can see 2 things wrong or not intended in the program (leaving aside whether it's the best approach to the problem).
As stated in a comment, you should use && instead of & for boolean AND. & is bitwise AND, useful for integer bit twiddling.
You declare answer as an array, but never create space for it. You need to say int [] answer = new int[2]; or similar.
I haven't run the code, but if the test program ends with no output, check that you aren't getting a NullPointerException (caused by #2 above).
Don't forget about null-checks and the case where no correct number-pair was found.
public static int[] twoSum(int[] numbers, int target) {
if(Objects.isNull(numbers)){
throw new IllegalArgumentException("numbers is not allowed to be null");
}
for (int a=0;a<numbers.length;a++) {
int first = numbers[a];
for (int b=0;b<numbers.length;b++) {
int second = numbers[b];
if (first + second == target && a!=b) {
return new int[] { first, second };
}
}
}
throw new IllegalArgumentException("there has to be a matching pair");
}

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);

Categories