Java loops - making a "V" - java

This might sound like a slightly odd question, so bear with me.
What I'm tasked to do, is to make a simple Java class that forms a "V" based on whatever height the user would desire, made out of stars "*", and spaces " ".
For example, if a user desires a "V" with a height of 3, it would look print out something like;
* *
* *
*
Where a "V" with a height of 5 would look something like:
* *
* *
* *
* *
*
(That one didn't look too good, but you get the point, it's suppose to be 5 "high" and shaped like a "V")
The problem I have, is that I don't see what loops within loops within loops I would need to build something like this.
All the easy stuff like asking the user what height they want and such, I can handle, but I don't see how this thing is suppose to be coded, to print out a decent-looking and right-sized "V" in the console.
Can anyone assist me in this odd matter?
UPDATE
So in order to not come off as lazy, I tried poking around a little to see what I could come up with. Thanks to that and some help from the comments section, I came up with something like this.
public static void main(String[] args) {
int height = 3;
for (int i = 0; i < height; i++) {
for (int j = 0; j < 2*(height-1)+1; j++) {
if(j == i) {
System.out.print("*");
} else {
System.out.print(" ");
}
}
}
Looked like something of a good start, and it drew me half of the "V" in the size I wanted.
Am I on to it here, or am I on the moon in terms of progress?
I would love a poke in the right direction, and I do appreciate your comments guys!

Here is a code that draws V.
Look at it, you will understand why it works....
void drowV(int hight){
int rowLen = (hight-1)*2;
for(int i=0; i<hight; i++){
int start = i;
int end = rowLen-i;
for(int j=0;j<=rowLen; j++){
if(j==end){
System.out.println("*");
break;
}
else if(j==start){
System.out.print("*");
}
else{
System.out.print(" ");
}
}
}
}

Related

How can I use 2 Dimensional Arrays to create a tictactoe board? (not full game)

The goal of this assignment was for me to use a 2 Dimensional Array that prints a 3x3 tic tac board. While the instructions say it can have any arrangements on "x", "o", and blank spaces, it turns out it can't all be blank spaces (which my teacher had to specify after a cheeky attempt). Anyways, an example of a sample output would be like this:
Anyways, I decided that maybe I should randomize what fills up the grid (I was told that just doing it is easier and simpler but I can't figure out how to code that). Unfortunately, I'm stuck on how to fulfill the proper format and what fills up inside is mostly blanks and Os. Can someone perhaps suggest a better way to do this or help a bit? Thanks.
public class test {
public static void main(String[] args) {
String[][] tictactoe = new String[3][3];
for(int i = 0; i < 3; i++){
for(int j = 0; j < 3; j++){
int onetwo =(int)(3*Math.random())+1;
if (onetwo == 1){
tictactoe[i][j] = "x";
}
if (onetwo == 2){
tictactoe[i][j] = "o";
}
else{
tictactoe[i][j] = " ";
}
if ( i < 3)
System.out.print(tictactoe[i][j] + " | ");
}
}
System.out.println();
System.out.println("---------");
}
}
}
Thanks again!
Try to declare a string like:
String alphabet = "nxo";
And in your randomise function:
String letter = alphabet.charAt(r.nextInt()); // not sure about the syntax but that would be the logic for getting a random value
Just fill that in your array with your already existing for loops

Print triangle with width and height parameters

I am quite new to programming and Java. I need to print an asteriks and dot triangle with respect to width and height parameters.
So far, I can print only asteriks triangle with an only one parameter (height). (Assume 6 is given as parameter to the function)
Here is my code:
public static void main(String[] args)
{
for(int i=0; i<6; i++)
{
for(int j=6; j>=i; j--)
{
System.out.print(".");
}
for(int x=0; x<=(2*i); x++)
{
System.out.print("*");
}
for(int k=6; k>=i; k--)
{
System.out.print(".");
}
System.out.print("\n");
}
}
I want to give two parameters(width and height) to the function. However, I cannot manage adding a second parameter.
The expected output is (with width -11- and height -8- parameters):
triangle 11 8
.....*.....
....**.....
...****....
...*****...
..******...
.********..
.*********.
***********
However, I got the following output (with one parameter which only height -6-):
triangle 6
.......*.......
......***......
.....*****.....
....*******....
...*********...
..***********..
Could you please help me? How can I add a second parameter to my function and fix my problem?
Thank you very much!
Your code is doing several things which do not match your example.
First, you aren't using the arguments at all. You said to assume 6 is passed to your main method as an argument, but all I see is hardcoded 6's in your code. You should be calling args[0] and args[1] to use the two arguments.
Second, your loop logic is off if you want to get the result given with the arguments provided in the example. Your outer loop is fine for the number of lines, but your inner loops don't build the individual lines exactly right. The tricky part here is that the contents of each line need to consider the ratio of the width to the height.
Here is an example which should fix both issues:
public static void main(String[] args) {
int width = Integer.parseInt(args[0]);
int height = Integer.parseInt(args[1]);
for(int i=0; i<height; i++) {
int starsThisLine = (int) Math.round(width * ((i+1) / (double) height));
int dotsBeforeStars = (int) Math.round((width - starsThisLine) / 2.0);
for(int j=0; j<width; j++)
{
if (j < dotsBeforeStars)
System.out.print(".");
} else if (j < dotsBeforeStars + starsThisLine) {
System.out.print("*");
} else {
System.out.print(".");
}
}
System.out.print("\n");
}
}
Note that this may not print the result exactly, but should look close enough. If you need it to be exact, you may need to tune the ratios a bit.

For() loop with constant variable isn't printing any output

The problem is that there is no output happening, not an extra println(). This is odd, because doing this programming without a static SIZE var, it works just fine.
public class SlashFigure2
{
public static final int SIZE = 4;
public static void main(String[] args)
{
for(int i = 1; i <= SIZE; i++)
{
for(int j = 1; j <= 2 * i - (2 * SIZE + 2); j++)
{
System.out.print("\\");
}
for(int j = 1; j <= -4 * i + (-4 * SIZE + 2); j++)
{
System.out.print("!");
}
for(int j = 1; j <= 2 * i - (2 * SIZE + 2); j++)
{
System.out.print("/");
}
System.out.println();
}
}
}
In case anyone needs it, here's what the program prints:
!!!!!!!!!!!!!!
\\!!!!!!!!!!//
\\\\!!!!!!////
\\\\\\!!//////
EDIT: Here's what the site keeps saying is the error
EDIT 2:
The site is practiceit.csu.washington.edu
Here is the question's wording:
Modify your DollarFigure program from the previous exercise to become
a new program called DollarFigure2 that uses a global constant for the
figure's height. (You may want to make loop tables first.) The
previous output used a constant height of 7. The outputs below use a
constant size of 3 (left) and 5 (right)
Here are the outputs below they are talking about
(You must solve this problem using only ONE public static final
constant, not multiple constants; and its value must be used in the
way described in this problem.)
Simply do this:
if (i != SIZE) {
System.out.println();
}
Because i will be equal to SIZE in the last iteration, and you want to skip the println() in that case.
UPDATE
From the comments and the image, it's clear that you're not supposed to define SIZE as a constant, apparently you should be able to pass n as a parameter to your program, it's not a hardcoded value. Check the rules of the "site" you keep referring to, how's the input supposed to be received?
You can make this change in your code to make it work.You should not execute the statement when i is equal to SIZE
if(i<SIZE){
System.out.println();
}
Somewhat Jeopardy to find out the actual problem/quest you want to solve by algorithmically print a specific ASCII-art only denoted by a constant ROW-size (e.g. 4 or 6 as depicted on the attached image).
Tests & sample output
Derived specification
Draw a specific figure varying only in its height:
only single parameter is passed: rows of ASCII-art to draw
figure to draw should resemble a downward-arrow
bordered by double-slashes left and right, i.e. \\ respective //
no border/slashes on the first row
inner/rest of the rows filled with exclamation-marks !!
at least 2 exclamation-marks !! on the inner last row
Java method with single parameter: ROWS
private static void drawAsciiArt(int rows) {
int columns = (rows-1)*4+2;
for(int i = 1; i <= rows; i++) {
int borderSize = (i-1)*2;
int fillSize = columns - borderSize*2;
for(int j = 1; j <= borderSize; j++) {
System.out.print("\\");
}
for(int j = 1; j <= fillSize; j++) {
System.out.print("!");
}
for(int j = 1; j <= borderSize; j++) {
System.out.print("/");
}
if (i < rows) {
System.out.println();
} // if not last row
} // end of row-loop
}
Try this online
Figured it out! It turns out that for both the '\' and '/' characters, I didn't need to use that (x * SIZE + y) formula after all. They both needed the regular formula while the '!' is the only character that needed the SIZE formula
public class SlashFigure2
{
    public static final int SIZE = 4;
//program works no matter what value SIZE holds
    public static void main(String[] args)
    {
        for(int i = 1; i <= SIZE; i++)
        {
            for(int j = 1; j <= 2 * i - 2; j++)
            {
                System.out.print("\\");
            }
            
            //note the SIZE formula in here
            for(int j = 1; j <= -4 * i + (4 * SIZE + 2); j++)
            {
                System.out.print("!");
            }
            
            for(int j = 1; j <= 2 * i - 2; j++)
            {
                System.out.print("/");
            }
            
            System.out.println();
        }      
    }  
    
}

String Method and loops

I have a program I'm working on that I'm stuck on and can't really figure out. Basically, I'm supposed to input a word, and have the word be encased in a box of asterisks, which is the main objective. The actual prompt says: Read a string from the keyboard. Output the string centered inside of a box as shown below. The box needs to be resized on each run to assure that it has the correct spacing.
Ex.
Here is my code:
import java.io.*;
import java.util.*;
public class Prog600a
{
public static void main(String[] args)
{
for(int i = 1; i<=3; i++)
{
Scanner kbReader = new Scanner(System.in); //Allows input
System.out.print("Enter a string: ");
String word1 = kbReader.nextLine();
int len1 = word1.length();
for(int x = 0; x<=len1; x++)
{
System.out.print("*");
}
System.out.println();
System.out.print("*");
for(int x = 0; x<len1; x++)
{
System.out.print("\t");
}
System.out.print("*");
System.out.println();
System.out.println("* " + word1 + " *");
System.out.print("*");
for(int x = 0; x<len1; x++)
{
System.out.print("\t");
}
System.out.print("*");
System.out.println();
for(int x = 0; x<len1; x++)
{
System.out.print("*");
}
System.out.println();
}
}
}
I'm using the string method length to determine how long the string is, and print asterisks according to that. However, I can't seem to get the spacing, and my output looks nothing like the one shown. I've been experimenting with the code for a few hours (which is why it's a bit long and may be inefficient ), but can't really seem to get it. The spacing isn't right, and I don't really know how to correctly resize the box on each run. Can someone please provide some guidance? Thanks for all the help!
I spot only tiny problems:
You don't print enough asterisks in the top and the bottom (make it < len1 + 4)
You print tabs instead of spaces (change "\t" to " ").
You don't print enough spaces, change those loops to < len + 2
That's all. My output for input test:
********
* *
* test *
* *
********
Stack Overlow isn't for doing your homework for you. But, I will give you some pointers:
Look at repeat.
A tab character is 4-8 characters long, depending on how you're viewing it. '*' is one character long.

JAVA: If/Else/For Methods?! WHAT?

I can't even do the basics. What am I doing wrong?
I need to:
Draw a "X" made up of stars (*). I must prompt for the width of the X in stars.
My requirements for this assignment is:
+1 - prompt for size of X
+4 - draw X of stars (receive +2 if can draw solid square of stars)
I'm using Eclipse by the way!
import java.util.Scanner;
/*
*
*
* Description: Draws a X.
*/
public class Tutorial1
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
int i,j;
System.out.print("Enter size of box: 4 ");
int size = sc.nextInt();
for (i=0; i < size; i++)
{
for (j=0; j < size; j++)
{
if ( (i == 0) // First row
|| (i == size-1) // Last row
|| (j == 0) // First column
|| (j == size-1) ) // Last column
System.out.print("*"); // Draw star
else
System.out.print(" "); // Draw space
}
System.out.println();
}
}
} //
Your program draws a box correctly.
Enter size of box: 4 7
*******
* *
* *
* *
* *
* *
*******
You need to change your code so it draws a cross instead. The code is actually simpler as you have just two lines instead of four.
I would remove the 4 from the prompt as it confusing.
Enter size of box: 7
* *
* *
* *
*
* *
* *
* *
You already know you problem. You stated it yourself: "I can't even do the basics".
Then learn the basics. There is no way around THAT.
This site is not a "write me a piece of code that does X" service. People will help you only with specific questions on a specific problem. Your task is actually beginner stuff that is pretty simple once you grasped the basic concepts. Failing that, any solution we may provide here will be useless to you, since you don't even understand how the problem was solved. Worse, your teach will most likely notice pretty fast that you did not write that on your own. That screws you double - you get charged of cheating and still haven't learned anything.
Here is the skeleton of what you need. The for loops will iterate through the table. The hard part is coming up with the algorithm for deciding which character to print.
public class Tutorial1
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
int i,j;
System.out.print("Enter size of box: ");
size = sc.nextInt();
Tutorial1 t = new Tutorial1();
t.printX(size);
}
private int _size = 0;
public void printX(int size) {
_size = size;
for(int row = 0; row < _size;row++) {
for(int col = 0; col< _size;col++) {
System.out.print(getChar(row,col));
}
System.out.println();
}
}
private String getChar(int row, int col) {
//TODO: create char algorithm
//As a pointer, think about the lines of the X independently and
//how they increment/decrement with the rows
}
}

Categories

Resources