Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
As I was working through practice problems I came across this one where I am not sure how I got the wrong answer. I tried increasing the value of "i" by 1 and printing that value. This should print the output "5 6 7" but for some reason does not. I tried to google my answer but can't phrase the question correctly or get good results.
//assuming that the value of 'i' is 4
public static void test(int i) {
if (i < 8) {
test(i + 1);
System.out.print (i + “ “);
}
}
You call test before you print the value. If you originally invoke test with 5, the machine does this in pseudocode:
test(5)
test(5 + 1)
test(5 + 1 + 1)
test(5 + 1 + 1 + 1)
print 5 + 1 + 1 // 7
print 5 + 1 // 6
print 5
test is called; but before printing anything, it calls itself again with i + 1. This repeats until i is 8, and then it starts printing in the "most inside" function.
You should print first, and then call test again.
Since you are printing the value of i after the recursive call, the code will wait until the recursive function returns before printing the value. Which cause the number to be printed backward.
To prevent this, you might want to call the print statement before going into the recursive call.
public static void test(int i) {
if (i < 8) {
System.out.print (i + "");
test(i + 1);
}
}
You can test it with this anyfiddle
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 months ago.
Improve this question
public static int flood(int x, int y) {
if(x<0||y<0||x>101||y>101||went[x][y]) return 0;
System.out.println(x + " " + y);
went[x][y] = true;
if(grid[x][y] == 1) return 1;
int result = 0;
result += flood(x+1,y);
result += flood(x,y+1);
result += flood(x-1,y);
result += flood(x,y-1);
return result;
}
The code never came back to the same coordinate, but it is still somehow crashing.
P.S. went is a 2d boolean array.
What you wrote is a recursive function, it calls itself.
At first sight, it looks ok, but it "expands very fast".
In the first call to flood(0,0), it will "stack" flood(1,0) which will then "stack" flood(2,0) ... which will then stack flood(100,100) and only at this point will the method return for the first time!
That means that the stack size is roughly 10000 before the stack (of methods to continue processing once the current one is done) starts to "shrink back" after that point.
The basics of your method is correct, and I suppose it will work for a small array size, it's just a too big stack for a default JVM.
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I'm not sure why, but the code stops when it reaches the loop portion. I waited for 10 minutes...but still, absolutely nothing changed. It's not an infinite loop.
PrintWriter out = new PrintWriter(new File("CollectingTheData.txt"));
File dataCollection = new File("CollectingTheData.txt");
Scanner inF = new Scanner(dataCollection);
System.out.println("\nSimulating Trials Now...One Moment Please...");
RandomSquirels = (int)(Math.random() * 11 + 1);
while (RunCount <= TrialNumber) {
while (RandomSquirels != 10) {
out.println(RandomSquirels);
}
out.close();
RunCount++;
}
while (inF.hasNextLine()) {
NumRead = Integer.parseInt(inF.nextLine());
SquirelTotal += NumRead;
}
inF.close();
CalculationsForAv = (double)SquirelTotal / (double)TrialNumber;
System.out.println("The results! \nThe Average Number of \nSquirels Observed until Observing a Fox Squirrel: " + CalculationsForAv);
I only included the relevant portion of code. Everything necessary is imported and all the variables are defined.
while (RandomSquirels != 10) {
out.println(RandomSquirels);
}
You never change RandomSquirels value inside the while, I guess that what you wanted to do is:
while (RandomSquirels != 10) {
out.println(RandomSquirels);
RandomSquirels = (int)(Math.random() * 11 + 1);
}
I also noticed that you run out.close() inside a while, so you will try to close it over and over again... You shouldn't close a stream more then once.
Java is an imperative language. You appear to think that this:
RandomSquirels = (int)(Math.random() * 11 + 1);
is like a macro, you think it means: "Everytime I write RandomSquirels, assume I wrote (int)(Math.random() * 11 + 1). That is not how java works.
It means: Run the expression (int)(Math.random() * 11 + 1) right now, once, and assign the result of this to the variable RandomSquirels.
You then loop while RandomSquirels is not 10 and print it to the file. Forever, except once in every 11 runs, when the value so happens to resolve to 10.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I'm a newbie to programming and today i came across this program. How did i get the output as 3? and the jargon used here is quite confusing.
class Demo
{
public static void main(String args[])
{
Demo d = new Demo(); // what does this really mean?
System.out.println(d.someMethod(124));
}
public int someMethod(int x)
{
if(x<=0)
return 0;
return 1 + someMethod(x/10);
}
}
below is the answer
1 + someMethod(12)
1 + 1+ someMethod(1)
1 + 1+ 1+ someMethod(0)
1 + 1+ 1+ 0
= 3
Reformatted class with comments:
class Demo {
// static method used to start a Java application
public static void main(String args[]) {
// create a new instance of the Demo class
Demo demo = new Demo();
// call instance method someMethod and print the return value
System.out.println(d.someMethod(124));
}
// someMethod is a recursive function, that is a function which
// calls itself until a stop condition is reached
public int someMethod(int x) {
// stop condition
if(x <= 0) {
return 0;
}
// recursive call
return 1 + someMethod(x/10);
}
}
What happens:
1 call someMethod(124/10)
2 call someMethod(12/10)
3 call someMethod(1/10)
4 return 0 (because 1/10 == 0 the stop condition is reached)
3 return 1 + 0
2 return 1 + 1 + 0
1 return 1 + 1 + 1 + 0
so the return value is 3.
Note that 1/10 == 0 because the result is floored (the remaining decimals are removed to make it an int).
Well first of all you create a Demo object with name d.Via this object you call a method named someMethod(x).
This method returns 0 if the input parameter is <=0 or in any other case 1 + someMethod(x/10).
Demo d = new Demo();
This line means that you are initialising a new object with name 'd' from a class called Demo (which is also your main class). If you don't understand what objects and classes are, read up on it elsewhere, because it is a very major topic in Java.
Personally this has helped me the most: https://docs.oracle.com/javase/tutorial/java/concepts/index.html
public int someMethod(int x) {
if(x<=0)
return 0;
return 1 + someMethod(x/10); }
This method is acting kind of like a loop. You are passing a value of 124 from:
System.out.println(d.someMethod(124));
here. 124 gets checked if it is smaller of equal to zero. It is not so it gets passed to:
return 1 + someMethod(x/10);
124/10 is 12.4, but as x is an int it will round it to 12. And the program carries on until x <= 0, which loops over 2 times like:
1 + someMethod(12)
1 + 1+ someMethod(1) // 12/10 is 1.2, but gets rounded to 1
1 + 1+ 1+ someMethod(0) // 1/10 is 0.1, but gets rounded to 0
And the program ends as the passed value is 0. So you get 3 as an output.
Demo d = new Demo() will call the Constructor of Demo Class. If there is not any constructor present in the class then JVM will create a default one. That's how the concept behind the object creation in Java.
and look the previous answer how the someMethod(args) will execute.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
So I started the Euler Project and the first problem was very easy, however I cannot get the answer because the program I created is not running. It compiles fine but when I run it, it never runs. Project Euler says that the problems " with efficient implementation will allow a solution to be obtained on a modestly powered computer in less than one minute." Which leads to my question. Am i stuck in an infinite loop or does my computer not have the power to run my program?
The problem is: If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
Find the sum of all the multiples of 3 or 5 below 1000.
public class Euler1
{
public static void main(String[] args)
{
double x = 1;
int count = 0;
int total = 0;
while( x < 1000)
{
if((x/3 == (int)x) || (x/5 == (int)x))
{
count++;
x++;
total += x;
}
}
System.out.println(total);
}
}
Your program is wrong.
while( x < 1000)
{
if((x/3 == (int)x) || (x/5 == (int)x))
{
count++;
x++;
total += x;
}
}
Notice that x is only incremented if the condition is true. x starts at 1, so the condition is not true, so x never gets incremented and stays at 1.
Also, x/3 == (int)x and x/5 == (int)x are not correct tests for divisibility. Neither of them are ever true unless x is 0.
The problem is that if your if condition is false in the while loop, x never gets incremented...
(and it will always be false unless x is 0)
You are getting stuck in an infinite loop. Your if-statement is never being called because it will never return true unless x is 0, and thus your x variable is never being incremented. I would suggest looking into the % (modulus) operator for this problem.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
What would this code do?
for(int i = 0; i < enemysno; i++){
g.drawString("\nArray size: " + i, 200, 200);
}
enemysno is a random number between 0 and 10, and works fine. Problem is, it loops once, but then stops adding new lines after the first iteration.
As Psuedo code, I though the i starts as 0. Then compares the condition, if its false, does the code, then makes the ++ iterations, then repeats the loop?
Ultimatly, I want to add n objects to an array, but I can quite get this to work simple array to work!
A simple test proves the loop indeed works as intended:
public static void main(String[] args)
{
int enemysno = 5;
for (int i = 0; i < enemysno; i++)
{
System.out.println("lalala " + i);
}
}
this works fine producing
lalala 0
lalala 1
lalala 2
lalala 3
lalala 4
It was kind of obvious, but via debugging or such a test you could determine that the loop itself is entered the desired numer of times. The problem must be in your string display: most probably your drawString method overwrites the printed string each time.
It should be obvious if you checked the numbers on your output.
The solution?
use a string builder to concatenate the partial strings and then draw the final string using your drawString method