drawString in loop writes only once instead of multiple times [closed] - java

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

Related

Can anyone please tell me why my flood fill is causing stackoverflow error? [closed]

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.

If else loop not adding valuing to variable using +=? [closed]

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.

sort integer array in java class fairly basic from 2 to 18 [closed]

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 4 years ago.
Improve this question
i need to sort an array of the type intgere in a basic way (nothing too complex) for a school computer science project. It would be nice if sb could give me not only a one sentence answer waht to consider but also some code i can work with.
thanks a lot.
You could've either googled it but since you didn't, use this bubblesort method:
boolean swapped; // to notice swaps during a pass
do {
swapped = false;
for (int i=1; i<a.length; i++)
if (a[i-1] > a[i]) {
// Swap!
int swap = a[i];
a[i] = a[i-1];
a[i-1] = swap;
swapped = true;
}
} while (swapped); // another pass if swaps happened
It swaps the ints next to each other until you have them sorted from the smallest to the greatest number. If you want it the other way around simply swap the ">" with a "<".
I hope that will help you.

Logic errors within java segment [closed]

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 8 years ago.
Improve this question
The following Java code segment is supposed to print, as a double, the mean average of a sequence of non-negative integers entered by the user. A negative input signals the end of the sequence (it is not itself part of the sequence). However, the code is not working. I am supposed to find 4 logic errors within this segment. Please help me find the 4 logic errors?? I know one is its integer division.
public class practice
{
public static void main (String[]args)
{
int sum = 0;
int numVals = 0;
Scanner scan = new Scanner(System.in);
System.out.println(("enter next integer (-ve to stop): "));
int i = scan.nextInt();
while (i > 0)
{
sum = sum + i;
numVals = numVals + 1;
}
System.out.println("average = " + sum / numVals);
}
}
I won't give you full solution, however, it'll be helpful if you pay attention to:
int division as you said,
does your loop terminate? Is someone changing i? Hint: No, and
how do you ask for input? Do you see any loops there? Why it's asking you for only one input?
Not an error, but pay attention to Java Naming Conventions, class name should begin with upper case
Since the homework is for logic errors, I could point out other errors.
the class name should start with upper case letter.
the println doesn't need two nested parenthesis.
the sum should be a long rather than an int to avoid overflows.

int A does not equal int B [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
I have two integers that I want to compare. The first integer is created from a byte of utf-8 and the second integer is the one I want to check to see if it equals.
int a = 106;
int b = (int)byteArray[0]; //which actually equals 106 when you printstatement it
but....
(a==b) //always equals false
int i = 0; While(b != i) { println(i); i++;} //eventually escapes the loop and is true
Are primitives also referenced when created? And why does a never equal b unless I count all the way up to 106?
Is there a better way to compare bytes? because I've tried all forms of variables and they do not work either.
The problem is somewhere else in your code (in the part that you are not showing). This is why you are being suggested to provide an SSCCE.
The following works as expected (i.e. prints true):
public class Test
{
public static void main(String[] args) throws Exception
{
byte[] byteArray = new byte[] { 106 };
int a = 106;
int b = (int) byteArray[0];
if (a == b)
System.out.println("true");
}
}
Most probably, in your code byteArray[0] does NOT contain 106. An SSCCE would show this.

Categories