Printing to Console Does Nothing in For Loops - java

I've tried several programs that involve printing to the console in for loops, but none of them have printed anything. I can't work out the problem, and I've boiled it down as simply as possible here:
for (int x=0; x==10; x++)
{
System.out.print("Test");
}
Like I said, absolutely nothing is printed to the console. Things outside of the for loop will print, and things affected by the for loop will print.
Perhaps it's something very simple, but I wouldn't know considering I'm relatively new to programming and Eclipse gives me no errors. Any help would be much appreciated, as this is plaguing my class files at the moment.
Thanks,
Daniel

Your for loop condition is wrong. You want the condition to be true to continue looping, and false to stop.
Try
for (int x=0; x < 10; x++)
For more information, here's the Java tutorial on for loops.

#rgettman gave the reason your code didn't work above.
The way the for loop works is in the brackets the first variable is where the loop starts (i.e. 'x=0'), the second variable is the condition (i.e. 'x<= 10'), and the third is what to do for each loop (i.e. 'x++').
You had "x==10" for the condition, so for the first scenario where x was equal to "0", the loop ended because it was NOT equal to "10". So you want it to be "x<=10" (x is less than or equal to 10); this will go through 11 loops.

rgettman is completely correct. A for loop should be used as so:
for is a type of loop in java that will take three parameters separated by semicolons ;
The first parameter will take a variable such as int i = 0; to create a simple integer at 0.
The second parameter will take a condition such as i < 10, to say while the i integer is less than
The third and final parameter will take an incrementing value like, i++, i--, i +=5, or something to that effect.
This part should like like for(int i = 0; i < 10; i++) so far.
Now you need the brackets { and }. Inside of the brackets you will perform an action. Like you wanted to print "test" to the console.
for(int i = 0; i < 10; i++) {
System.out.println("test");
}
This would print "test" 10 times into the console. If you wanted to see what number i was at, you could simply say,
for(int i = 0; i < 10; i++) {
System.out.println(i); // Current value of i
}
Hope this was of use to you!

Related

Why is this for loop only printing out once? What is values.length

I'm just getting started so this is going to be a beginner question :)
I've had this lesson but there is something in the code I don't understand.
int[] values;
values = new int[3];
values[0] = 10;
values[1] = 20;
values[2] = 30;
System.out.println(values[0]);
System.out.println(values[1]);
System.out.println(values[2]);
This is the basic array lesson I understand. But he said that there is another way to print out the values. By using a for loop.
for(int i=0; i<values.length; i++)
System.out.println(values[i])
This is the part I don't understand.
What is values.length? Is it 3 or 2?
Why doesn't it print out the values more than once?
Thnx
Since arrays in Java are zero-indexed, so an array that has [10, 20, 30] i.e. 10 at index 0, 20 at index 1, and 30 at index 2, has a length of 3. Simply the length is the number of elements in the array.
Now regarding why there is a single print statement here, it might be easier to visualise what the loop does.
The loop simply executes the code inside it, every time with a new value of i, as long as the loop condition is met.
So yo can think of this
for(int i=0; i<values.length; i++)
System.out.println(values[i])
to be translated to this
System.out.println(values[0])
System.out.println(values[1])
System.out.println(values[2])
But because as you can notice, the same function is used multiple times, only with a different input, we can only write the function once, and run it multiple times with different inputs through a loop.
On a side note, you should almost always use a BLOCK with a for statement, even if it only has one line within it.
So instead of:
for(int i=0; i<values.length; i++)
System.out.println(values[i]);
You'd do:
for(int i=0; i<values.length; i++)
{
System.out.println(values[i]);
}
By default, a for loop only runs the line immediately following it inside the loop. The indentation is merely aesthetic. If you want more than one line to be run, then you'd include them all within the brackets.
Many beginners skip the brackets and then later add a line to it...looking something like below, but expecting both lines to be run within the loop:
for(int i=0; i<values.length; i++)
System.out.println("Value: "); // only this line is within the loop
System.out.println(values[i]); // this line is simply indented, and stands alone
You can avoid some lost time troubleshooting weird problems from code like above by starting with good habits and always add brackets to your for loops.

Nothing is being output to the console! (Java, Eclipse Mars)

So basically I am experimenting with writing a path finding program that find a path from some point in a 10*10 grid to another, that is fine.
I have a class Path that is an ArrayList of GridSquares (which are just glorified co-ordinates).
I have written a small method within the Path class to display the path, and this is where the problem, which is so minor but so very infuriating, arises.
When I try to run the code, and call displayPath, nothing is output to the console and the program terminates with no errors.
Here is the code for displayPath:
public void displayPath(){
System.out.println("This is displayPrint"); //This line is included to make sure the program calls the method correctly.
for(int i=1; i==10; i++){
for(int j=1; j==10; j++){
if(this.includesSquare(i, j)){
System.out.print("[x]");
} else {
System.out.print("[ ]");
}
}
System.out.print("\n");
}
}
I included the first line to ensure that the console/System.out.print() was working correctly and this gets displayed every time the method is called.
Here is the code for includesSquare:
public boolean includesSquare(int x, int y){
for(GridSquare square : this.path){
if(square.getX()==x && square.getY()==y){
return true;
}
}
return false;
}
I have uninstalled and re-installed Eclipse, copied the java files into a new project ect and nothing seems to make any difference. I know the console is working fine as it displays the first line of displayPath correctly.
Any help is greatly appreciated!
for(int i=1; i==10; i++) and for(int j=1; j==10; j++) will not work.
The middle condition (i==10) is supposed to say when the loop is supposed to be executed. As it is, you are saying you only want the loop to execute when i is equal to 10. Since i is initially equal to 1, it will skip right over the loop.
What you will likely want is
for(int i=1; i<10; i++)
This way, when i is equal to 1, it satisfies the condition that it is less than 10, so the loop will get executed and i will increment. This will keep happening until i is equal to 10, at which point the condition i<10 fails, so the loop will exit.
In less words, you want your condition to say "loop while this is true" as opposed to "loop until this is true".
for(int i=1; i==10; i++){ is where your problem lies.
The syntax for the for loop is as follows:
for(<initial condition>; <checking condition>; <incrementing>)
So what you have is
Staring from i = 1, increment by 1 while i == 10. Well since i starts at 1, you've already failed at the first step!
Turn your for loop into while loop to understand this better:
int i = 1;
while(i == 10) {
doSomething();
i++;
}
So of course that won't work.

How do I branch into a specified part of a loop?

int a = 0;
int b = 0;
int c = 0;
Scanner sc = new Scanner(System.in);
for (int i = 0; i < 6; i++) {
b = sc.nextInt();
a =+ b;
c =+ (a + 1);
if (c < 20) {
i = 2;
}
}
if I have lines numbered from 0 to 6 inside the loop, the loop would be
so if c is less than 20, it repeats the operation "c=+(a+1);" until it breaks out of the loop by c>=20.
this is a simplified code from my program, mine is GUI. every time I run the code, it freezes.
use c+= instead of c=+. try that, cheers!
and b+= instead ofb=+.
You can tag a loop and do break or continue instructions, but you need design the flow, it is not possible to go into specified line, because java don't use goto instruction. You can only switch the flow inside loops by those instructions.
myloopTag:
for (...; ...; ...) {
// and you can break current loop by:
break;
// or specific (outer) loop by
break myloopTag;
// you can also use 'continue' to go to the start of the loop and increment again
continue;
// or to 'continue' at a label:
continue myloopTag;
}
You're probably very new to the language. Welcome!
If I understand your description of your intent properly, you want your code to exit the loop when c>=20. Based on your description of numbering your lines and the fact that you have the statement:
if(c<20){
i=2;
}
it seems that you think that the iterator i in the for loop is related to the line that will be executed*. This is not the case. The iterator i is a variable that simply holds an integer (just like a, b, and c in your code).
I suggest you take a look at a tutorial on for loops. It might be helpful for you to review other language basics as well, like how control flow works (this may be a better one to start with, actually).
*This guess at your intent is further supported by you counting that there are 6 lines and that your loop goes up to 6.

JAVA for loop: all except a specified number

I need this for an array, but basically the idea is that a for loop will run, and whatever number you tell it to skip, it won't do. So for(int x=0; x<50; x++) if I want 1-50 except 22, how would I write that?
This would give me the ability to skip a certain number in my array.
Sorry if this is an extremely simple question, I am not too familiar with Java.
Make use of continue, something like this:
for(int x=0; x<50; x++) {
if(x == 22)
continue;
// do work
}
Suggested reading: http://docs.oracle.com/javase/tutorial/java/nutsandbolts/branch.html
public static final void doSkippedIteration(final int[] pArray, final int pSkipIndex) {
for(int i = 0; i < pSkipindex; i++) {
// Do something.
}
for(int i = pSkipIndex + 1; i < pArray.length; i++) {
// Do something.
}
}
You would have to do some basic check to see whether pIndex lies within the confines of the array. This saves you from having to perform a check for every single iteration, but does require you to duplicate your code in this specific example. You could of course avoid this by wrapping the code in a wider control block which handles the two iterations in a cleaner manner.

Printing a square of stars in Java

Hi I have been given a task for my course and it is to create an algorithm to make a 5 by 5 square like below:
*****
*****
*****
*****
*****
I've spent hours attempting to do it and read tutorials and books. It's so frustrating as I know it must be so easy if you know what you are doing. Can anyone give me any guidance as to where to start?
You probably know and understand how to create a "Hello World" style program in Java.
Now think - how would you go about having that same program print 5 times "Hello World"?
After that, think about how you would make it write N times "Hello World".
After that, think about how you would output a series of N stars.
Good luck!
Seems like you should have a variable x equal to the dimension (5). A for loop i that loops from 1-x. In it a for loop j that loops from 1-x. The j loops outputs *, or appends * to a string. After the j loop, the i loop does a new line.
This solution will allow for a square grid of any size.
int size = input;
for (i=0; i<size; i++){
for (j=0; j<size; j++){
// output a single "*" here
}
// output a new line here
}
If I got you right, then it's about a NxN square with a given N. Your question is just about N := 5, but your comments let me assume that you've to program a more general solution.
Split the work that have to be done into more basic and smaller problems:
create a String that contains * N times.
call System.out.println() with the generated String N times
This will work for you as well, but the professor will frown that you found the answer online and did not think of it yourself.
System.out.println("*****\n*****\n*****\n*****\n*****");
Here's how I did it:
class Main {
public static void main(String[] args) {
int size = 25;
int pos = 0;
for(int i = 0; i<size; i++){
if(pos % 5 == 0){
System.out.println();
}
System.out.print("*");
pos++;
}
}
}
If I understood correctly, what you need is a console output with 5 lines of stars.
You can outpt text to console with System.out.print() or System.out.println() with the second option making a line break.
As you have to repeat the output, it is advisable to do enclose the output statement in a loop. Better in a nested loop to separate the x and the y axis.
In order to make the output modifiable - for the case you will need to output a 6x6 or 12x15 square tomorrow without any code modification, I would make the limits of the loop parametrized.
All in all, something like this :
public void printStartSquare(int width, int height){
for(int i = 0; i < height;i++){
for(int j = 0; j < width;j++){
System.out.print("*");
}
System.out.println("");
}
}

Categories