Java Bean Drop, Only Going to The Right - java

I have this game where a ball drops on the screen. The problem is, the ball only goes to right.
I believe the issue is in the transition from The LR method to the main game loop. I created a variable and it takes the LR method and runs it inside the loop that refreshes and clears the canvas every second.
Here is the code:
package cats;
public class BeanDrop {
public static void main(String[] args) throws InterruptedException {
mainGameLoop();
}
public static void mainGameLoop() throws InterruptedException{
double x = .5;
double y = .9;
while (true){
int choice = LR();
arena();
ball(x , y);
if (choice == 1){
// right outcome
x = x + .1;
}
else if(choice == 2){
//left outcome
x = x -.1;
}
y = y - .1;
Thread.sleep(1000);
StdDraw.clear();
}
}
public static void arena(){
StdDraw.picture(.5, .5, "balldrop.jpeg");
}
private static int LR(){
int choice = ((int) Math.random() * 2 + 1);
return choice;
}
public static void ball(double x , double y){
StdDraw.picture(x, y, "ball.jpeg",.05,.05);
}
}

Take a look at this:
How do I generate random integers within a specific range in Java?
What it says basically is to use this to get a random number:
Random rand;
// nextInt is normally exclusive of the top value,
// so add 1 to make it inclusive
int randomNum = rand.nextInt((max - min) + 1) + min;
return randomNum;
So for you, you could use this:
private static int LR(){
int choice = rand.nextInt(2) + 1;
return choice;
}
EDIT: You must make an instance of Random and name it rand at the top of your code:
private Random rand;
And have this before you initialize the game loop:
rand = new Random();

Related

How to print each number of a given number separately?

I have a code is written that is supposed to print each of the numbers separately. Heres an example.
printDigits(1362) prints
2
6
3
1
printsDigits(985) prints
5
8
9
You can pull apart a number into its digits using / 10 and % 10.
I have started some code the way I was taught but I am not sure what to do with the other variables.
Please have a look:
public class Main {
public static void main(String[] args) {
System.out.println(printDigits(1362));
System.out.println(printDigits(985));
}
public static int printDigits(int x){
int y = x % 10;
while (x > 0){
x = y;
System.out.println(x);
x = x / 10;
}
return x;
}
}
Why don't you convert the parameter x to String then read each Char in the String since a String is array of Char. If the output must be an int you convert the Char to int.
printDigits method should be like this:
public static void printDigits(int x) {
int y;
while (x > 0) {
y = x % 10;
System.out.println(y);
x = x / 10;
}
}
And the calling of the method will be like this:
printDigits(1362); // without the System.out.println()
There are various ways to achieve such results. You can better understand all solutions in these answers.
public static void printDigits(int num) {
while(num>0) {
int remainder = num%10;
num = num/10;
System.out.println(remainder);
printDigits(num);
}
}
You can use recursion to make it even more efficient.
You need to write int y = x % 10; inside the loop to "pull apart" every digit and print the digit y you have "pulled out".
Remove the System.out.println around your function calls.
You don't need to return a number, so you can change your return type to void:
public class Main {
public static void main(String[] args) {
printDigits(1362);
System.out.println();
printDigits(985);
}
public static void printDigits(int x) {
while (x > 0) {
int y = x % 10;
System.out.println(y);
x = x / 10;
}
}
}

Not getting right output for natural log formula

I'm trying to get my program to out the first 500 values for this formula: -12*ln(1-x) where x is the return of double next(). I don't know what I'm doing wrong because I can't get the right output. The random number uses this formula x(i+1) = (a * x(i) + c) mod k
public class myRnd {
// Linear values for x(i+1) = (a * x(i) + c) % k
final static int a = 7893;
final static int c = 3517;
final static int k = 8192;
// Current value for returning
int x;
int y;
int z;
public myRnd() {
// Constructor simply sets value to half of k
x = (125*k) /1024;
//y = (125*k) /1024;
}
double next() {
// Calculate next value in sequence
x = (a * x + c) % k;
// Return its 0 to 1 value
return (double)x / k;
}
public static void main(String[] args) {
int situation;
double sec_answer;
// Create a new myRnd instance
myRnd r = new myRnd();
// Output 53 random numbers from it
for (int i = 0; i < 53; i++) {
System.out.println (r.next());
}
System.out.println("random variable");
for(int b = 0; b < 500; b++){
sec_answer = (-12)*Math.log(1- r.next());
System.out.println(sec_answer);
}
}
}
I suppose these are the first 5 values you're expecting from your program in each loop!
0.9302978515625
0.270263671875
0.6204833984375
0.90478515625
0.8985595703125
random variable
31.962289651479345
3.78086405322487
11.626283246646423
28.21943313114782
27.45940262908609
In your main method you have only one instance of the class:
// Create a new myRnd instance
myRnd r = new myRnd();
This initialization is propagated to both for loops.
Simple Solution: Add another instance / initialization of myRnd for the second for loop, as an example you could reuse the same variable as r = new myRnd(); before the second loop.

Calculate third side of a triangle using methods

Ask the user for 2 sides of a triangle and then print out the length of the third side, as calculated by a method. Write a method to find the length of the third side using the Pythagorean theorem.
I'm new to java and I am suck with the following code which may be way off...
import java.util.*;
public class Tri8 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter two numbers:");
int a = input.nextInt();
int b = input.nextInt();
System.out.println(pythagoraen(a, b));
}
//Method goes here
public static int pythagoraen(int x, int y) {
Math.pow(x, y);
int z = Math.sqrt(x, y);
Math.sqrt(x, y);
}
}
Assuming you meant to find the hypotenuse of a right-angled triangle using the pythagorean theorem, you need to return the root of the sum of squares of both other sides:
public static double pythagoraen(int x, int y) {
return Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2));
}
private static double pythag(double x, double y){
return Math.sqrt(x*x + y*y);
}
or if you want to use math.pow, you can replace x*x with Math.pow(x, 2)
in java calling math.sqrt and math.pow dont directly edit the variables, they actually return a value that you can use, for instance math.pow takes in two double, the first is the base and the second is the exponent, so Math.pow(2,3) would be the same to you and me as 2^3
Here's the fixed code:
import java.util.*;
public class Tri8 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter two numbers:");
int a = input.nextInt();
int b = input.nextInt();
System.out.println(pythagoraen(a, b));
}
//Method goes here
public static int pythagoraen(int x, int y) {
return Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2));
}
}

Reusing variable from a different class?

This is probably quite simple, but i just dont know how to do it?
How do i reuse this from a class file:
int randomNum = 5 + (int)(Math.random() * ((10 - 5) + 1));
To then use the same result that this procures in another class file?
My CityWall Class (The Class containing the int i want to use.)
public class CityWalls extends Thing {
int randomNum = 5 + (int)(Math.random() * ((10 - 5) + 1));
public CityWalls(City c, int st, int av, Direction d) {
super(c, st ,av ,d);
int oddIncrement = 0;
if (randomNum % 2 == 0)
{
oddIncrement = 1;
}
for (int i = 0; i < randomNum; i++) {
new Wall(c, i+(7-randomNum/2), (7-randomNum/2), Direction.WEST);
new Wall(c, i+(7-randomNum/2), (7+randomNum/2) - oddIncrement, Direction.EAST);
new Wall(c, (7-randomNum/2), i+(7-randomNum/2), Direction.NORTH);
new Wall(c, (7+randomNum/2)-oddIncrement, i+(7-randomNum/2), Direction.SOUTH);
}
}
public int getRandomNum() {
return randomNum;
}
}
Here is my World Class (The Class where i want to reuse the variable).
public class World {
public static void main (String[] args) {
int height = 0, width = 0, top = 5, left = 5, thingCount = 20;
World b = new World();
Random rand = new Random();
// int RandomNumber = rand.nextInt(9);
CityWalls cw = new CityWalls(Gothenburg, 5 , 5, Direction.NORTH);
int RandomNumber = cw.getRandomNum();
height = (int)(Math.random() * 0.5) + RandomNumber; // I want to use the variable here.
width = (int)(Math.random() * 0.5) + RandomNumber; // And here to replace the RandomNumber. then it should be correct.
City Gothenburg = new City(16,16);
Thing[] things = ThingSpawnCity(Gothenburg, width, height, top, left, thingCount);
RobotFinder terminator = new RobotFinder(Gothenburg, 7, 7, Direction.NORTH, 0);
terminator.run();
}
public static Thing[] ThingSpawnCity(City Gothenburg, int width, int height, int top, int left, int objects){
Thing things[] = new Thing[objects];
int avenue = 0, street = 0;
for (int i = 0; i < objects; i++){
avenue = (int)(Math.random() * width) + left;
street = (int)(Math.random() * height) + top;
things[i] = new Thing(Gothenburg, street, avenue);
}
return things;
}
}
You need a reference to an instance of the class you want to use. You need need to access the field you want to use in that class. e.g.
class A {
int randomNum = 5 + (int)(Math.random() * ((10 - 5) + 1));
}
class B {
public void printNum(B b) {
System.out.println("Random Num " + b.randomNum);
}
}
public static void main(String... ignored) {
A a = new A();
B b = new B();
b.printNum(a);
}
Have a read about encapsulation and getters and setters, and you could do it like this:
int randomNum = 5 + (int)(Math.random() * ((10 - 5) + 1));
MySuperOtherClass other = new MySuperOtherClass();
other.setX(randomNum);
// now you can get it back with other.getX();
Add a getter for it in your class and make it public
public int getRandomNum() {
return randomNum;
}
EDIT
Class containing your random number:
public class ClassHavingARandomNumner {
int randomNum = 5 + (int)(Math.random() * ((10 - 5) + 1));
public int getRandomNum() {
return randomNum;
}
}
Another class that wants to access the random number
public class ClassWantingARandomNumber {
public static void main(String[] args) {
// create an instance of the class containing the random number
ClassHavingARandomNumner c = new ClassHavingARandomNumner();
// call the getter method to retrieve the random number
System.out.println(c.getRandomNum());
}
}
EDIT 2
first move
int randomNum = 5 + (int)(Math.random() * ((10 - 5) + 1));
outside of the constructor the make randomNumber a member variable of the class CiytWalls
Second, add the getter to CityWalls
Then in main assign the result of the constructor call to a local variable
CityWalls cw = new CityWalls(Gothenburg, 5 , 5, Direction.NORTH);
after that you can acces the random number of the CityWalls object you have created using:
int rn = cw.getRandomNumber();
You can do so by making member variable randomNum as static variable of class CityWalls. And use that variable to your World class. By doing so you will get the same value as specified in CityWalls class. But you actually want to reuse or I would say use the variable with the same name & don't want to allocate memory for it or any other reason you find it useful for your case then you should extend CityWalls class to your World class.
Hope this clarified your doubt.

Using loops to compute factorial numbers, Java

I'm trying to compute the value of 7 factorial and display the answer, but when I tried to look up a way to do this I kept finding code that was written so that a number first had to be put in from the user and then it would factor whatever number the user put in. But I already know what number I need, obviously, so the code is going to be different and I'm having trouble figuring out how to do this.
I tried this at first
public class Ch4_Lab_7
{
public static void main(String[] args)
{
int factorial = 7;
while (factorial <= 7)
{
if (factorial > 0)
System.out.println(factorial*facto…
factorial--;
}
}
}
But all it does is display 7*7, then 6*6, then 5*5, and so on, and this isn't what I'm trying to do.
Does anyone know how to do it correctly?
import java.util.Scanner;
public class factorial {
public static void main (String[] args) {
Scanner input = new Scanner(System.in);
//Gives Prompt
System.out.print("Enter a number to find the factorial of it");
//Enter the times you want to run
int number = input.nextInt();
//Declares new int
int factor = 1;
//Runs loop and multiplies factor each time runned
for (int i=1; i<=number; i++) {
factor = factor*i;
}
//Prints out final number
System.out.println(factor);
}
}
Just keep multiplying it and until it reaches the number you inputted. Then print.
Input:5
Output:120
input:7
Output:5040
You need to have two variables, one for the factorial calculation and other for the purpose of counter. Try this, i have not tested it but should work:
public static void main(String[] args)
{
int input = 7;
int factorial = 1;
while (input > 0)
{
factorial = factorial * input
input--;
}
System.out.println("Factorial = " + factorial);
}
int a=7, fact=1, b=1;
do
{
fact=fact*b;//fact has the value 1 as constant and fact into b will be save in fact to multiply again.
System.out.print(fact);
b++;
}
while(a>=b); // a is greater and equals tob.
1st reason:
The methods you seen are probably recursive, which you seem to have edited.
2nd:
You are not storing, ANYWHERE the temporal results of factorial.
Try this
//number->n for n!
int number = 7;
//We'll store here the result of n!
int result = 1;
//we start from 7 and count backwards until 1
while (number > 0) {
//Multiply result and current number, and update result
result = number*result;
//Update the number, counting backwards here
number--;
}
//Print result in Screen
System.out.println(result);
Try this:
public static void main(String args[]) {
int i = 7;
int j = factorial(i); //Call the method
System.out.println(j); //Print result
}
public static int factorial(int i) { //Recursive method
if(i == 1)
return 1;
else
return i * factorial(i - 1);
}
This would print out the factorial of 7.
public class Factorial {
public static void main(String[] args) {
int result = factorial(5); //this is where we do 5!, to test.
System.out.println(result);
}
public static int factorial(int n) {
int x = 1;
int y = 1;
for (int i = 1; i <= n; i++) {
y = x * i;
x = y;
}
return y;
}
}
/*so, for 3! for example, we have:
i=1:
y = x * i, where x = 1, so that means:
y = 1*1 ; y= 1; x = y so x = 1. Then i increments =>
i = 2:
y = x * i. x is 1 and i is 2, so we have y = 2. Next step in code: x=y, means x = 2. Then i increments =>
i = 3:
y = x *i so we have y = 2*3. y=6. */

Categories

Resources