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
}
}
Related
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.
I am new to programming and I have an exercise that's killing me. How can you print a grid (5-by-6) which consists of asterisks alone? [Later on, these asterisks will have to be replaced by letters which are read in with StdIn.readInt() and a switch statement, but for now I at least need to understand how to print the grid]. I would appreciate any help so much!
More specifically, the grid should look like this:
//THIS ISN'T THE CODE; JUST AN ILLUSTRATION OF WHAT SHOULD BE PRINTED
0 1 2 3 4 5
0 * * * * * *
1 * * * * * *
2 * * * * * *
3 * * * * * *
4 * * * * * *
//I AM SUPPOSED TO START WITH SOMETHING LIKE THIS:
public class Grid {
static int X = 6;
static int Y = 7;
public static void main(String[]args) {
int [][] grid = new int [X][Y];
This could have been done in many ways, but this is my way of doing it:
When you want to print a grid, you have to use 2 nested for loops.
Let's see what happens when you use 2 nested for loops:
for(int i = 0; i < 6; i++){
for(int j = 0; j < 7; j++){
}
}
We start with the first loop:
for i = 0, we will enter the second loop and iterate from 0 to 6.
for i = 1, we will enter the second loop and iterate from 0 to 6.
...
for i = 5, we will enter the second loop and iterate from 0 to 6.
What you should notice is that j will iterate and take values from 0 to 6 with each value of i.
Going back to your question, and comparing it by what i just showed, you should notice that for each line, you are printing 7 values (of a column).
Let's assume i is the number of lines, and j is the index of each value in that line (column).
public static void printGrid() {
for (int i = 0; i < 6; i++) {
System.out.println();
for (int j = 0; j < 7; j++) {
System.out.print("*");
}
}
}
This code prints on each line (i), 7 asterixes (j).
And each time i is incrementing, we are going back to the next line System.out.println(). That's why we put it inside the for loop with i.
In your situation, we have to tweak this code a little bit to be able to print the numbers on the sides, and that space at the top left corner.
The explanation is in the comments in my code.
public class Question_55386466{
static int X = 6;
static int Y = 7;
public static void printGrid() {
System.out.print(" "); // Printing the space on the top left corner
for (int i = 0; i < X; i++) {
if (i > 0) { // Printing the numbers column on the left, taking i>0 to start from the second line (i == 1)
System.out.println(); // Going to the next line after printing the whole line
System.out.print(i - 1);//Printing the numbers of the column. Taking i-1 because we start the count for i == 1 not 0
}
for (int j = 0; j < Y; j++) {
if (i == 0)
System.out.print(j + " ");//Print the first line numbers.
else
System.out.print(" * "); //if the line isn't the first line(i == 0), print the asterixes.
}
}
}
You can always edit the values of X and Y and get the desired result.
And later you can give this method your array as a parameter and print each element instead of the asterixes.
I am having trouble printing a triangle. Using 2 loop statements in the printTriangle method, I have to make a triangle that looks like this.
If user entered 3
*
**
***
**
*
Using 2 loops in the triangle method that must use the printLine method to print this triangle. I cannot print anything at all in the triangle method and cannot change anything in the line method. Any help with a small explanation would be awesome, thanks!
import java.util.Scanner;
public class Triangle {
//Global declaration of the keyboard
public static Scanner kbd = new Scanner(System.in);
public static void main(String[] args) {
int triSize = 0;
System.out.println("What size triangle would you like to be printed?");
triSize = kbd.nextInt();
printTriangle(triSize);
}
/**
* printLine is used to calculate how many asterisks should be printed
* #param astNum the number given by the user
* #param x is used to count the number of asterisks that have not and need to be printed
*/
public static void printLine(int astNum){
int x;
for (x = 0;astNum > x; x++){
System.out.print("*");
}
System.out.println("");
}
public static void printTriangle(int triSize){
int x = 0;
for (int i=1; i<=triSize; i++) {
printLine(triSize);
}
}
}
Using two loops in the printTriangle() method to generate the output is exactly how I would approach this problem. The first loop can print from 1 star to N stars, where N is the size of the triangle. Then, use a second loop to print the other half of the triangle. This is really an exercise in your ability to articulate clean loop boundary conditions in both loops.
public static void printTriangle(int triSize) {
// print stars from 1 to triSize, top to bottom
for (int i=1; i <= triSize; ++i) {
printLine(i);
}
// print starts from triSize-1 to 1, from top to bottom
// note carefully that the loop counter here begins at triSize - 1
for (int i=triSize-1; i >= 1; --i) {
printLine(i);
}
}
Add these loops:
for (int i=1; i<=triSize; i++) {
printLine(i);
}
for (int i=triSize; i>=1; i--) {
printLine(i);
}
Before asking my question I want to make some things clear. First, I am new to Java and programming in general. Second, This is my second post so please go easy on me if I did something wrong. Finally, I would like an explanation as to why what I did was wrong instead of just a pasted solution in any responses to this post. To better understand the issue I will write the assignment information, then the Driver class that is given, then my class code that is accessed by the Driver class.
My question:
How can I get the bottom left of my 'building' to be [0][0] on my 2D array? Here's an example of a for loop that works in changing the bottom left of a 2D array to [0][0], but I tried implementing this into my searchRoom method (where the player character is set to myHidingPlaces index) and I can't get myHidingPlaces[0][0] to be the bottom left of my 2D Array. I believe that i need to edit the toString method somehow with for loops, but I can't figure out how I should do it.
The following is the assignment:
You are to design a class “LostPuppy.java” which represents a puppy lost in a multi-floor building that
contains the same number of rooms on each floor. During instantiation (or creation) of an object of this class,
each room on each floor will be initialized as empty (you will actually use the space ‘ ‘ character for this
purpose) and a random room will be chosen where the puppy is lost. For this purpose, the character “P” will
be placed in this random location. Further details on the constructor is listed below.
An object of this class is used as a game for two players to take turns searching for the puppy, one room at a
time until the unfortunate little canine is found. The instantiation of this object and the search will be performed
by a “driver” program which has been provided to you allowing you to only have to concentrate on developing
the class (the driver program is in the file “PuppyPlay.java”)
Fields (of course, all fields are private):
A character (char) array named myHidingPlaces. This represents the building where the rows are floors
and the columns are rooms on each floor (this building has an unusual numbering system; the floors and
rooms both start at zero).
Two integers that will hold the floor and room where the puppy is lost, named myFloorLocation and
myRoomLocation.
A char named myWinner which will be assigned the player’s character when a player finds the puppy
(the driver program uses digits ‘1’ and ‘2’ to more clearly distinguish the players from the puppy).
A boolean named myFound which is set to true when the puppy is found.
Constructor:
Receives two integer parameters as the user’s input for the number of floors and rooms of the building
in which the puppy is lost.
The constructor instantiates the 2D array “myHidingPlaces” as a character array with the first parameter
for the rows (theFloors) and the second parameter as the columns (theRooms).
Initialize myHidingPlaces’ cells, each to contain a space ‘ ‘ (done with single quotes)
Set myFloorLocation (floor puppy is on) randomly based using the first parameter
Set myRoomLocation (room puppy is in) randomly based using the second parameter
Set myHidingPlaces[myFloorLocation][myRoomLocation] to the char ‘P’
Set myWinner to a single space
Set myFound to false
Methods:
roomSearchedAlready receives the floor and room to be searched and returns true if the room has
already been searched, false otherwise.
puppyLocation receives the floor and room to be searched and returns true if the floor and room are
where the puppy is lost, false otherwise. This method should NOT change any of the fields.
indicesOK receives the floor and room to be searched and returns true if the floor and room values are
within the array indices range, false otherwise (used to check that these indices will not cause an error
when applied to the array).
numberOfFloors returns how many floors are in the building (the first floor starts at zero).
numberOfRooms returns how many rooms are on each floor of the building (the first room starts at
zero and all floors have the same number of rooms).
searchRoom receives the floor and room to be searched and also the current player (as a char type)
and returns true if the puppy is found, false otherwise. If the puppy is NOT found searchRoom also
sets the myHidingPlaces array at the received floor and room location to the received player value (a ‘1’
or a ‘2’) OR, when found, sets the myWinner field to the current player AND sets myFound to true.
toString displays the current hidingPlaces array and it’s contents EXCEPT the location of the puppy
which remains hidden until he/she is found at which point toString will be called (by the driver) and both
the player who found the puppy and a ‘P’ will be displayed in the same cell….
NOW, and perhaps the awkward portion of the toString output. Normally, when displaying a 2D array,
the [0][0] cell is displayed in the upper left corner as with matrices. However, because the puppy
decided to get lost in a building and not a matrix, it would make more visual sense to have the first floor
(row 0) displayed on the bottom, second floor above it… and finally the top floor, well… on top! To
save words, look closely at the sample run provided on the next page. Your output should look the
same as what is seen on the next page in the sample run.
Here is the Driver program:
import java.util.Random;
import java.util.Scanner;
/**
* This program is used as a driver program to play the game from the
* class LostPuppy. Not to be used for grading!
*
* A puppy is lost in a multi-floor building represented in the class
* LostPuppy.class. Two players will take turns searching the building
* by selecting a floor and a room where the puppy might be.
*
* #author David Schuessler
* #version Spring 2015
*/
public class PuppyPlay
{
/**
* Driver program to play LostPuppy.
*
* #param theArgs may contain file names in an array of type String
*/
public static void main(String[] theArgs)
{
Scanner s = new Scanner(System.in);
LostPuppy game;
int totalFloors;
int totalRooms;
int floor;
int room;
char[] players = {'1', '2'};
int playerIndex;
boolean found = false;
Random rand = new Random();
do
{
System.out.print("To find the puppy, we need to know:\n"
+ "\tHow many floors are in the building\n"
+ "\tHow many rooms are on the floors\n\n"
+ " Please enter the number of floors: ");
totalFloors = s.nextInt();
System.out.print("Please enter the number of rooms on the floors: ");
totalRooms = s.nextInt();
s.nextLine(); // Consume previous newline character
// Start the game: Create a LostPuppy object:
game = new LostPuppy(totalFloors, totalRooms);
// Pick starting player
playerIndex = rand.nextInt(2);
System.out.println("\nFloor and room numbers start at zero '0'");
do
{
do
{
System.out.println("\nPlayer " + players[playerIndex]
+ ", enter floor and room to search separated by a space: ");
floor = s.nextInt();
room = s.nextInt();
//for testing, use random generation of floor and room
//floor = rand.nextInt(totalFloors);
//room = rand.nextInt(totalRooms);
} while (!game.indicesOK(floor, room)
|| game.roomSearchedAlready(floor, room));
found = game.searchRoom(floor, room, players[playerIndex]);
playerIndex = (playerIndex + 1) % 2;
System.out.println("\n[" + floor + "], [" + room + "]");
System.out.println(game.toString());
s.nextLine();
} while (!found);
playerIndex = (playerIndex + 1) % 2;
System.out.println("Great job player " + players[playerIndex] +"!");
System.out.println("Would you like to find another puppy [Y/N]? ");
}
while (s.nextLine().equalsIgnoreCase("Y"));
}
}
Finally, here is my test code:
import java.util.Random;
import java.util.Scanner;
public class LostPuppy
{
int value;
char[][] myHidingPlaces;
int myFloorLocation;
int myRoomLocation;
char myWinner;
boolean myFound;
Random random = new Random();
public LostPuppy(int theFloors, int theRooms)
{
myHidingPlaces = new char[theFloors][theRooms];
for (int i = theFloors - 1; i >= 0; i--)
{
for (int j = 0; j <= theRooms - 1; j++)
{
myHidingPlaces[i][j] = ' ';
}
}
myFloorLocation = random.nextInt(theFloors);
myRoomLocation = random.nextInt(theRooms);
myHidingPlaces[myFloorLocation][myRoomLocation] = 'P';
myWinner = ' ';
myFound = false;
}
public boolean roomSearchedAlready(int floor, int room)
{
return (myHidingPlaces[floor][room] == '1' ||
myHidingPlaces[floor][room] == '2');
}
public boolean puppyLocation(int floor, int room)
{
return (myHidingPlaces[floor][room] == 'P');
}
public boolean indicesOK(int floor, int room)
{
return (floor <= myHidingPlaces.length && room <= myHidingPlaces[0].length);
}
public int numberOfFloors()
{
return myHidingPlaces.length - 1;
}
public int numberOfRooms()
{
return myHidingPlaces[0].length - 1;
}
public boolean searchRoom(int floor, int room, char player)
{
if (puppyLocation(floor, room))
{
myFound = true;
myWinner = player;
return true;
}
else
{
myHidingPlaces[floor][room] = player;
return false;
}
}
public String toString()
{
int rooms = myHidingPlaces[0].length;
int floors = myHidingPlaces.length;
System.out.print(" ");
for (int x = 0; x < rooms; x++)
{
System.out.print("___");
}
for (int y = 0; y < rooms - 1; y++)
{
System.out.print("_");
}
System.out.print("\n");
for (int r = 0; r < floors; r++)
{
System.out.print("| ");
for (int c = 0; c < rooms; c++)
{
if (myHidingPlaces[r][c] == 'P' && myFound)
{
System.out.print("" + myWinner + "" + myHidingPlaces[r][c] + "| ");
}
else if (myHidingPlaces[r][c] == 'P' && !myFound)
{
System.out.print(" | ");
}
else
{
System.out.print(myHidingPlaces[r][c] + " | ");
}
//System.out.print(myHidingPlaces[r][c] + " | ");
}
System.out.print("\n");
for (int i = 0; i < rooms; i++)
{
System.out.print("|___");
}
System.out.print("|\n");
}
return "";
}
}
There is no way you can make a reversed array in Java, but you don't need it. You need to think of the building and operate with it just like you would do it with matrices. However you need to print it upside-down. Also there is no changing of position in array by the link you provided, it is just an array traversal from last index to first.
So you need to print array upside-down and this is pretty easy. You need to change one line in your toString method, change
for (int r = 0; r < floors; r++)
to
for (int r = floors - 1; r >= 0; r--)
And you will get correct result!
Also in this case you don't need to fill array from last to first (at least because you fill it with the same value), like you do
for (int i = theFloors - 1; i >= 0; i--) {
for (int j = 0; j <= theRooms - 1; j++) {
...
}
}
It will be better if you do it like this (just better to read your code)
for (int i = 0; i < theFloors; i++) {
for (int j = 0; j < theRooms; j++) {
...
}
}
As #Dante said you also need to correct indicesOK method because last index of array is its length - 1, so when you access myHidingPlaces.length or myHidingPlaces[i].length element the exception ArrayIndexOutOfBoundsException will be thrown.
public boolean indicesOK(int floor, int room) {
return (floor < myHidingPlaces.length && room < myHidingPlaces[0].length);
}
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(" ");
}
}
}
}