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.
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 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
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 2 years ago.
Improve this question
I'm new to Java and wanted to learn a few basics about coding.
I got stuck on the while loop! It seems like my compiler is just not executing the loop and I suspect it has something to do with my variables, but I genuinely do not know what to do.
I've already looked through similar problems but none of them could help me so far.
System.out.println("Ist die gesuchte Zahl größer als die angegebene Zahl?");
while (ja) {
System.out.print("Wir haben die Zahl gefunden!");
}
while (nein) {
System.out.print("Ist die gesuchte Zahl größer oder kleiner?");
if (kleiner) {
int nummer2 = 1 + (int)(100 * Math.random()) - nummer;
System.out.println("Ist " + nummer2 + "die gesuchte Zahl?");
} else if (größer) {
int nummer3 = 1 + (int)(100 * Math.random()) + nummer;
System.out.println("Ist " + nummer3 + "die gesuchte Zahl?");
}
}
In a while cycle you must put a condition. While that condition is true the cycle loop continue.
An easy example should be:
int a = 0;
while(a<5){
System.out.println(a);
a++;
}
This cycle will be executed untill a is lower than 5. Each time that this cycle is executed the variable increase. The output will be:
0
1
2
3
4
So you should place a condition in your while loop that should not be always true (that cause an infinite loop) or always false (that will never execute your code).
First of all, don´t be discouraged because you might not understand everything at the first instance, this all comes with time and a lot of practice. I will do my best to explain the while loop for you.
A while-loop executes everything inside of the curly braces over and over again until the condition inside the parentheses evaluates to false. If your condition is always true, the loop will continue forever. Here is an example:
public static void main(String[] args) {
int i = 0;
while(i < 5) {
System.out.println("Looping...");
i = i + 1;
}
}
This loop would print "Looping..." five times, since i isn´t smaller than 5 after 5 iterations.
You can basically put any expression inside the parentheses that evaluates to a boolean. I would love to get more specific, but for that, it would be nice to know where your variables ja and nein are defined.
I would recommend you to go and practice the basics again, here is a good example that I used a while ago:
http://openbook.rheinwerk-verlag.de/javainsel/
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 have a 1D matrix with data and another with scores. I'm trying to loop across all of the elements in the data and find the element in the same position in the score matrix, and keep adding these values together during each loop. For some reason, my script keeps starting from sum = zero instead of retaining and adding to the sum from the previous loop. For the below example, I expect sum = 1 in the first loop, 3 after the second loop (since 1+2=3) and 6 after the third loop (3+3=6). Instead, sum just yields the last value retrieved from scores. What am I doing wrong here?
public static int calc_score( )
{
String [] dat = {"A", "B","C"};
int [][] scores = new int [1][3];
scores[0][0] = 1;
scores[0][1] = 2;
scores[0][2] = 3;
int sum = 0;
for (int i = 0; i < dat[0].length(); i++)
{
if (dat[i].equals("A")) {
sum = sum + scores[i][0];
// scores[i][0] returns the expected value of 1 in the first loop
}
else if (dat[i].equals("B")) {
sum = sum + scores[i][1];
}
else if (dat[i].equals("C")) {
sum = sum + scores[i][2];
}
}
System.out.println(sum);
return sum;
}
I tried modifying sum = sum + scores[i][1]; to sum+=scores[i][1] but that doesn't fix this. I have to be missing something simple.
Learn to debug. Add println statements, or use a debugger, and track, on paper if you prefer, what you think the program should do. Where the computer does something different from what you thought: Voila. You found a bug; there may be more.
If you can't figure out why something is happening, go back and re-check assumptions.
Had you done that here, for example, you might have eventually noticed: Huh, that for loop really is only running exactly once, that's bizarre. Eventually you'd check what dat[0].length() returns and then realized it returns, mysteriously, 1, and perhaps then you'd have one of those slap yourself on the forehead moments: dat[0] refers to the first entry in the dat array, so, the string "A". Then you ask that string about length, which dutifully returns 1.
I assume you wanted dat.length instead.
Note that scores[1][0] is 0 too, you have more than one problem here.
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
I have a jqgrid, with pagination. User can enter data by themselves to neviaget between pages.
I am getting error if user enter more than available pages on line 199 as shown in the above example. How to solve this issue?
if(noOfRows != null && !recipeList.isEmpty())
if ((noOfRows * pageNo) < recipeList.size()) {
recipeList = recipeList.subList((noOfRows * (pageNo - 1)),
(noOfRows * pageNo));
} else {
recipeList = recipeList.subList((noOfRows * (pageNo - 1)),
recipeList.size()); //line 199: giving error
}
for (Recipe recp : recipeList) {
..............
..............
I tried to change the else part of code where on line 199 :
int totalCustomPagesNums=noOfRows * (pageNo - 1);
int firstIndex=totalCustomPagesNums < recipeIdList.size()?totalCustomPagesNums:1;
recipeList = recipeList.subList(firstIndex,
recipeList.size());
I would simplify it to:
Work out the lower bound, which must be at least 0 and at most recipeList.size()
Work out the exclusive upper bound, which must be at least 0 and at most recipeList.size()
Take the sublist
So:
int start = Math.min(Math.max(noOfRows * (pageNo - 1), 0), recipeList.size());
int end = Math.min(Math.max(noOfRows * pageNo, start), recipeList.size());
recipeList = recipeList.subList(start, end);
Now you know for sure that 0 <= start <= end <= recipeList.size(), so it'll be fine, even if the user specifies bizarre row counts or page numbers.
You are trying to create a sublist that starts at index 100 and ends at index 72. Since the beginning of your list is behind the end, you are getting the IllegalArgumentException.
Add another check, if (noOfRows*pageNo < recipeList.size()).
I would add two extra blocks, to the beginning of your code.
if (pageNo < 1) {
pageNo = 1;
}
if ((pageNo - 1) * noOfRows >= recipeList.size()) {
pageNo = 1 + ( recipeList.size() - 1 ) / noOfRows;
}
The first block fixes things if the page number is too low. The second block fixes things if the page number is too high.
The check at the beginning of the second block is making sure that the index of the first recipe to be displayed (which is (pageNo - 1) * noOfRows) is within the range of recipeList. The assignment inside is setting pageNo to the highest value for which this is true.
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.