Java Excercis 16 RandomWalk - java

I am running a program that starts someone in the middle of a 7 foot bridge and you have to generate 1s and 0s to simulate forward and backward steps. It is supposed to calculate how many steps it took the person to fall off either forwards or backwards, and i am not done but when i run it, it never stops generating numbers. this is what i have so far:
import java.util.Scanner;
import java.lang.Math;
public class RandomWalk {
public static void main(String[] args){
int forwardstep=4;
int backwardstep=4;
int average;
int randomnum=0;
int attemptnum=0;
Scanner input=new Scanner(System.in);
while(forwardstep<7||backwardstep<7){
randomnum=(int)(2*Math.random()+0);// random number generator//
System.out.println(randomnum);
attemptnum+=1;
if(randomnum==1){
forwardstep+=1;
backwardstep-=1;
}
else if(randomnum==0){
backwardstep+=1;
forwardstep-=1;
}
}
input.close();
}
}

while (forwardstep<7 || backwardstep<7)
You are looking for a fall off one side of the bridge so one of these will always be true. You want to check rather if one of these if false therefore;
while (forwardstep<7 && backwardstep<7)

Because when you add one to one of your variables you always quit one on the other. For example, look at this:
forwardstep=4;
backwardstep=4;
5-3,6-3,7-3
But when the other variable enter in the if, then you will have this:
6-4,5-4,4-6,3-7
So, it's impossible that in the same time both variables will be equals to 7. Maybe you have to change the condition of your while to && (AND operator).

Related

What is the reason for these two for loop acting differently?

Hi can anyone help me with this?
First block of codes gives the output as intended.
But second one goes for infinite loop.
What is the reason?
Thank you.
1.
import java.util.Scanner;
class Numbers
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Enter a starting number: ")
int start = scan.nextInt();
for(int a = start;a<=(start+10);a++)
{
System.out.println(a);
}
}
}
2.
import java.util.Scanner;
class Numbers
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Enter a starting number: ")
for(int start = scan.nextInt();start<=(start+10);start++)
{
System.out.println(start);
}
}
}
In the first block, start is a constant variable which has fixed value and the condition is between a and start (a keeps increasing a++ and start won't change its value).
While in second block, the condition is between start and start+10, but start keeps increasing with start++ in the loop function, which makes the loop is infinite (start keeps changing its value so start<=(start+10) is always true).
This for(int start = scan.nextInt();start<=(start+10);start++) compares the changing variable to a changing value, which keeps the same distance ahead.
I.e. the value of start will always be lower than start+10, what you get is at first an endless loop. It can only terminate when values get so high that they cannot be represented anymore an strange things occur. At that point start+10 might appear to be lower than 0 for example and hence seem also lower than start which not yet is past that weird border.
In your second snippet of code
for(int start = scan.nextInt();start<=(start+10);start++)
{
System.out.println(start);
}
You're comparing start to itself plus 10. Regardless what operation you're going to perform, nothing can't be equals to itself plus 10. start will always be lower than itself plus 10 and therefore producing an infinite loop. It's a semantic error. You should use a different variable to keep track of the loop, as you did in your first snippet, and a second one for the confrontation (start in your case).

How to unreverse this method in java?

I wrote some code:
public class digitShow {
public static void main(String[] args) {
System.out.println(digitShow(98198187));
}
public static int digitShow(int num) {
if (num != 0) {
System.out.print(num % 10);
return digitShow(num / 10);
} else
return num;
}
}
The code works perfectly fine, but I am trying to make it so instead of printing the numbers in reverse order one by one, the output rather would display each digit one by one in the order that they are entered in the parameter.
So in this case:
1
2
3
4
I've been trying to un-reverse it, but I've had no luck.
Ok, some people on comments are suggesting using arrays or similar. This is correct, however this seems like a question made by someone who is learning recursion (and, as a teacher, I can smell a homework question here).
I will not post the answer because I'd be doing your homework for you and we need good programmers in this world. If I (or anyone else) do your homework you'll never understand the basic concepts of programming, and never becoming a good programmer.
Now, building on top of smac89's comment:
Your code to reverse has an issue: it prints 0 after it reverses the digits. Why? because you are returning an integer and then printing it in your main function but you are not really using the return value anywhere else.
Try calling your method without the System.out.println in main and see what happens.
So, basically, evaluate if you really need to return an integer and, if you don't, you can now evaluate how you are calling the recursion (again, read smac89's comment).
I wish you the best in your studies!
You need to reduce the number by successive divisions first. Then process the values as they are unwound from the stack. This will print the most significant to least significant digit. Then return the starting number.
public static int digitShow(int num) {
if (num > 10) {
digitShow(num/10);
}
System.out.println(num%10);
return num; // returns the starting number.
}
prints
9
8
1
9
8
1
8
7
98198187

Jave error: reached end of file while parsing (Not typical)

Im trying to create a method to find the common factors of 2 given numbers but I can not get the file to compile. All of my curly brackets are closed as I'm aware thats usually almost always the cause of this error. Hopefully someone can help me out!
import java.util.Scanner;
public class E1{
public static void main (String [] args){
Scanner kb = new Scanner(System.in);
double n1,n2;
System.out.println("Enter two numbers");
n1=kb.nextDouble();
n2=kb.nextDouble();
printCommonFactors(n1,n2);
}
//call a method that prints the positive shared factors of the 2 inputed numbers
public static void printCommonFactors(int n1,int n2){
//determining the max/min of the two inputed variables
int max,min;
max=Math.max(n1,n2);
min=Math.min(n1,n2);
//setting up 2 arrays to store the factors
int [] maxFactors = new int [max];
int [] minFactors = new int [min];
int counter1;
for (inti=0;i>max;i++)
if (i%max=0)
counter1++;
maxFactors[counter1]=i;
for (int i=0;i>min;i++)
if (maxFactors[i]%min=0)
maxFactors[i]=
}
}
This is the error I receive:
The reason you are seeing the "reached end of file while parsing" is that the parser expects to find a right-hand-side operand for the equals operator but fails to do so. You end your method with maxFactors[i]=. Binary operators always require right-hand-side operands. In this case, you must place a value after the equals-sign.
Also, it looks like you are trying to apply some principles to Java that you probably pulled from another language. The most obvious one here is that you use replace explicit blocks with white-space. This works for languages like Python, but does not work in Java. Indentation is not significant in Java and only has the effect of improving readability.
This is relevant for your for statements. Because you are not actually using blocks, these statements are actually equivalent:
for (inti=0;i>max;i++)
if (i%max=0)
counter1++;
maxFactors[counter1]=i;
for (inti=0;i>max;i++) {
if (i%max=0) {
counter1++;
}
}
maxFactors[counter1]=i;
This will cause issues with i being referenced out of its scope. The other issue with this is that the for initializer (inti=0;) is missing a space and should be int i = 0.
Other issues include trying to allocate arrays with a non-integer size (must be of type int) and using bad test expressions for your for-loops (i>min will invariably remain true if it is ever true due to your incrementor until an integer overflow is reached).

Game of dice in java

The requirements of the program are:
Antonia and David are playing a game.
Each player starts with 100 points.
The game uses standard six-sided dice and is played in rounds. During one round, each player rolls one die. The player with the lower roll loses the number of points shown on the higher die. If both players roll the same number, no points are lost by either player.
Write a program to determine the final scores.
I came up with the following code:
import java.util.*;
public class prob3
{
public static void main(String[]args)
{
Random g=new Random();
int a,b,c;
int rounds;
int antonio=100;
int david=100;
Scanner s=new Scanner(System.in);
System.out.println("Please enter the no. of rounds you want to play(1-15): ");
rounds=s.nextInt();
for(int d=1;d<=rounds;d++)
{
a=g.nextInt(6)+1;
b=g.nextInt(6)+1;
System.out.println("Round "+d+":"+a+" "+b);
if(a<b)
antonio=100-b;
else if(a>b)
david=100-a;
}
System.out.println("Total for Antonio: "+antonio);
System.out.println("Total for David: "+david);
}
}
The program fails to calculate the right sum at the end.
What am I doing wrong?
Any help would be appreciated.
Thanks.
You are doing this.
antonio=100-b;
When you probably want
antonio = antonio - b;
The first code simply subtracts the dice roll from 100 every time, which is pointless. You want to subtract the dice roll from the players totals. Do this for both players.
As stated above the "100 - b" was your main problem. But there is no reason in your problem statement to set a number of rounds.
I whould rather use a loop like this:
while(antonio >= 0 && david >= 0){
//do the same stuff here
}
System.out.println...
Since it looks as some exercise for some java course.. This may sound useless but:
Format always your code.. Spaces, brakets and tabs
Use descriptive variable mames. a b c d are not quite intuitive in a larger program.
Remover unused variables
Y mucha suerte tío!

Using a while loop to generate random numbers until a certain number is reached

I'm learning about while loops. In my Java class currently I'm trying to modify a program to use a basic while loop to generate random numbers until a certain number is reached. In this particular case I want it to print until it goes below .0001. I've gotten myself confused while trying to do it and am not getting any output. I'm looking for any hints or tips that anyone might have to help me along with this or help further my understanding. Here's what I have for code so far:
import java.util.Random;
public class RandomNumbers {
public static void main(String[] args) {
Random rand = new Random();
double val = 1;
while(val < .0001){
val = rand.nextDouble();
System.out.println(val);
}
}
}
The while conditions says:
"While x condition is true, do this"
In this case, you have val=1 that is grather then 0.0001. So the while gets never executed.
So setting while(val>0.001), means:
"While my val is grater then 0.001, print it out. If is less then 0.001, return"
In code:
import java.util.Random;
public class RandomNumbers {
public static void main(String[] args) {
Random rand = new Random();
double val=1;
while(val>.0001){
val=rand.nextDouble();
System.out.println(val);
}
}
}
Simple logic error. Based on your current code the while loop will never run because val<.0001 will always be false (1 > .0001). You need to modify that line to this:
while(val > 0.0001){
Also it's usually better to write decimals with a 0 in front of the . for improved readability.
Your error is just simple to correct. You didn't tell your code to increase or decrease (++ or --) you should set your variable to increase or decrease base in what you want it to do.

Categories

Resources