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("");
}
}
Related
This question already has answers here:
Elegantly Insert Spaces During Loop Between Values Without Trailing Space
(3 answers)
Java: join array of primitives with separator
(9 answers)
Closed 6 months ago.
I'm trying to get the console to output 100 random numbers between 0 and 50, all on the same line with a space between each. I have everything but the formatting for the space. I know I need to use the printf function, but am completely lost on how to properly impliment it. This is what I have so far, but the output formatting is incorrect.
public static void main(String[] args) {
Random rand = new Random();
for (int count = 0; count <=100; count++)
{
int randomNum = rand.nextInt(51);
System.out.printf("%1d %1d", randomNum, randomNum);
}
}
Here's a version neither using a condition or a separate first print but avoiding any leading or trailing space.
public static void main(String[] args) {
Random rand = new Random();
String delim="";
for (int count = 0; count <100; count++)//fixed as per comments elsewhere.
{
int randomNum = rand.nextInt(51);
System.out.printf("%s%1d", delim,randomNum);
delim=" ";// Change this to delim="," to see the action!
}
}
It's a classic faff to print out n items with n-1 internal separators.
PS: printf feels like overkill on this. System.out.print(delim+randomNum); works just fine.
[1] Your code actually prints 101 numbers. Embrace the logic computers (and java) applies to loops and 'the fences' (the start and end): The first number is inclusive, the second is exclusive. By doing it that way, you just subtract the two to know how many items there are. so, for (int count = 0; count < 100; count++) - that loops 100 times. Using <= would loop 101 times.
[2] You're making this way too complicated by focusing on the notion of 'there must be a space in between 2', as if the 2 is important. What you really want is just 'after every random number, print a space'. The only downside is that this prints an extra space at the end, which probably doesn't matter:
for (int count = 0; i < 100; count++) {
System.out.print(randomNum + " ");
}
is all you actually needed. No need to involve printf:
I know I need to use the printf function
No, you don't. No idea why you concluded this. It's overkill here.
If you don't want the extra space.. simply don't print it for the last number:
for (int count = 0; i < 100; count++) {
System.out.print(randomNum);
if (count < 99) System.out.print(" ");
}
[3] You mention that the code shuold print it all 'on one line', which perhaps suggests the line also needs to actually be a line. Add, at the very end, after the loop, System.out.println() to also go to a newline before you end.
public class Assignment1{
/* This piece of the code will print out a triangle
orientated to the left and will increase by one
asterik every time there is a new line */
public static void main(String[] args){
// declaring the integer variables x and y
int x,y;
// if 1 is greater than or equal to 11, runt he for loop and add 1.
for(x=1; x<=11; x++){
// if x is greater than y print add 1 and print out the next lines
for(y=1; y<x; y++){
// prints out the actual * in the code.
System.out.print("*");
}
System.out.println();
}
// number of spaces
int i, j, k=2*n-2;
// outer loop to handle number of rows
// n in this case
for(i=0; i<n; i++){
// inner loop to handle number spaces
// values changing acc. to requirement
for(j=0; j<k; j++){
// printing spaces
System.out.print(" ");
}
// decrementing k after each loop
k = k - 2;
// inner loop to handle number of columns
// values changing acc. to outer loop
for(j=0; j<=i; j++){
// printing stars
System.out.print("* ");
}
// ending line after each row
System.out.println();
}
int n = 5;
printStars(n);
}
}
So I am only getting the the first part of the code in the output, I was wondering what i was doing wrong and why the second half of the code does not output, fairly new to java programming. I have been trying multiple ways but cant seem to get it, If anyone could possibily guide me. I would greatly appreciate it.
First thing I notice is that you put in curly braces where you don't need them. You only need to put in curly braces around code used in functions, loops, and if statements. It would be a good idea to use a program like eclipse to keep track of your curly braces, plus it will warn you of other errors
Secondly you have to declare the variable n before you use it, along with the method printStars()
You have to declare the n variable before you use it at k=2*n-2;
Here's what I am trying to replicate:
Currently, my code is as follows:
public void boxes() {
setLocation(20,20);
for(int j =0; j < 5; j = j+1) {
setLocation(20+50*j,20+50*j);
for (int i= 0; i<4; i= i+1) {
move(600-(50*j));
turn(90);
}
}
}
and the result is:
PLEASE do not write me any code, I'd highly prefer just a general explanation as to how I can make it so that the boxes being drawn do not end at the same point. I've been trying to figure it out for the past two hours with no luck and what I currently have is so far the best I've gotten. Thank you!
This is based on http://www.greenfoot.org/scenarios/3535
the problem is with the value you pass to the move() function, it should be:
move(600-(50*j*2));
the reason is that the length of each edge of the square should be shorter by twice the offset from the previous square, as it starts offset units deeper and ends offset units sooner (offset=50 in this case).
The j selects a next square.
Ask yourself:
nice to know: end point of drawing is identical with begin point
you start by (50, 50) more inside. How do you come there from the prior end point
the new length to draw is how much smaller
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.
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!