Java Square Class [closed] - java

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 8 years ago.
Improve this question
Here is what I am asked to do:
1. Create a class called Square that takes a width parameter in the constructor. The Square class should have a draw() method that will draw the square on the screen. Create a class called TestSquare that will take width from the user, create an object of Square, and invoke the draw() method on the square object.
Here is what I have, but the problem I am having is passing the draw() method to the test method. I know see that I need to move the for loops from the test to the class, so that i can call it in the test main method.
public class Square {
/** the width of square*/
int width;
/** construct the square*/
Square(){
}
/**construct a square */
Square(int newWidth){
width = newWidth;
}
/**show the square*/
void draw(){
for (int i=0; i<width; i++)
{
for (int j=0; j<width; j++)
{ System.out.print("* ");}
System.out.println();
}
}
}
import java.util.Scanner;
public class TestSquare {
/** Main method */
public static void main(String[] args) {
// Create a scanner input
Scanner input = new Scanner(System.in);
// prompt user to enter width
System.out.println("Creating a Square ...");
System.out.print("Please enter its width:");
int width = input.nextInt();
Square square = new Square(width);
System.out.println("Here is the Square:");
square.draw();
}
}

Change your loop into this:
for (int i=0; i<width; i++)
{
for (int j=0; j<width; j++)
{ System.out.print("*"); }
System.out.println();
}
As said, remove semicolons after loops because this makes your loop end immediately without arguments. i should be set to 1 so that it would reiterate in the correct number of times
And edit your getWidth() method into this:
int getWidth() {
return width;
}
Using width*width would make the method return n^2 of the width. It's supposed to be width not area.
Edit: I'm not sure if this is what you're trying to do but try putting this inside Square class:
void draw() {
for (int i=0; i<width; i++)
{
for (int j=0; j<width; j++)
{ System.out.print("*"); }
System.out.println();
}
}
Remove the getWidth() method completely. Then replace your getWidth() invocation with this:
square.draw();

There are a few problems.
Either rename this method to "getArea" or return width only:
int getWidth() {
return width*width;
}
Do not put a semicolon at the end of the for loop declarations. That makes the for loop do nothing. Also, the outer for loop should start at 0 (not 1):
for (int i=1; i<width; i++); //remove this trailing semicolon
{
for (int j=0; j<width; j++); //remove this trailing semicolon
System.out.print("*");
System.out.println();
}

Related

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.

How to draw an inverse pyramid with asterisks in Java

Code
public static void main(String[] args) {
String text=JOptionPane.showInputDialog("Introduce height");
int height=Integer.parseInt(text);
drawInversePiramid(height);
}
public static void drawInversePiramid(int height){
for(int numberasterisks=(height*2)-1,numberspaces=0;numberasterisks>0;numberspaces++,numberasterisks-=2){
//we draw spaces
for(int i=0;i<numberspaces;i++){
System.out.println(" ");
}//we draw the asterisks
for(int j=0;j<numberasterisks;j++){
System.out.println("*");
}//to jump the line
System.out.println("");
}
}
I'm having a trouble compiling the pyramid correctly. Instead it simply prints a vertical pattern with the correct number of asterisks.
Your code is actually correct, except for one minor detail. You are calling println everywhere, which will always print to a newline. Instead, only call println at the end of each line, but use just print when you want to build out a given line with stars and spaces. Using this version of your code:
public static void drawInversePiramid(int height) {
for (int numberasterisks=(height*2)-1,numberspaces=0;numberasterisks>0;numberspaces++,numberasterisks-=2){
// we draw spaces
for (int i=0; I < numberspaces; i++) {
System.out.print(" ");
}
// we draw the asterisks
for (int j=0; j < numberasterisks; j++) {
System.out.print("*");
}
// to jump the line
System.out.println("");
}
}
drawInversePiramid(3);
I get the correct output:
*****
***
*
Demo

Printing a Triangle

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);
}

Very basic java program doesnt run [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
So I am a java newb, started last week and have been reading a book. In the book at the end of a chapter it gives a challenge to make a program that will output
*
**
***
I am trying to get it so that it outputs is the number of lines as args (That is correct right?). The issue i am having is it the program will only output a page of asterisks as in:
***************...
The code is
public class Rektifier {
public static void main(String[] args) {
int Lines = 1; // amount of lines i want
int stars = 0; //asterisk i want
int X = 0; //Counter for the asterisks for loop
while (Lines <= Integer.parseInt(args[0])){ //I think I found this on stack overflow, it is to search through the arguments for integers
Lines =+ 1; // increase by 1 for the while loop
stars =+ 1; // do this to increase by 1 for the amount of stars i want, could be any number
for (X = 0; X >= stars; X =+ 1){ // forloop, if x is less than stars it should add * to the end of the line. Then increase x by 1 to add another star until x is equal to star then it should continue
System.out.print("*");
}
System.out.println(); //creates a new line to add on too
}
}
}
You have two loops. The outer while() loop uses Lines as its control variable. This loop decides how many stars are to be printed in each line – therefore Lines should take the values: 1, then 2, then 3, etc... (as for now it does not due to a small typo: so you should replace Lines=+1 with Lines+=1)
Your inner for loop uses X as its control variable. This loop actually prints the number of stars dictated by the Lines variable, so you should correct it to the form:
for (X = 0; X < Lines; X++)
Your variable stars is not necessary in such case.
(btw. refrain from starting variable names with capital letters; this works perfectly but is against tradition).
Or you can simply use for loops. You have nested 2 iterations. For loop is better for this case. Use while when execution count depends on some mutable condition.
public static void main(String[] args) throws IOException {
int lines = 3;
// lines loop
for(int i=0; i<lines; i++){
// stars loop
for(int j=0; j<=i; j++) {
System.out.print("*");
}
System.out.println();
}
}
For this easy learning example you could do string operation to get the result you want
public static void main(String[] args) {
int lineCount = Integer.parseInt(args[0]));
String stars = "";
for (int index = 0; index < lineCount; ++index) {
stars += "*";
System.out.println(stars);
}
}
This will produce the following output for arg = 10:
*
**
***
****
*****
******
*******
********
*********
**********
Every iteration the stars string will append a star to the existing stars.
There's answers here but they aren't pointing out the actual bugs in your code. I'll point out the bugs in your code. First and foremost:
What you need to do is first think of what the pseudocode looks like. It should look like this.
for (line_number ... number of lines):
for(0...line_number)
print star
print newline.
Here's the bugs in your code with comments in the lines:
public class Rektifier {
public static void main(String[] args) {
int Lines = 1;
int stars = 0; //This is not useful. The number of stars will always be equal to the number of lines. Why not just use the number of lines?
int X = 0; //Would rather that you utilize the for loop for declaring X, it is only used there.
while (Lines <= Integer.parseInt(args[0])){
Lines =+ 1; // Increment at the end of the while loop. Otherwise, you print two stars on the first line.
stars =+ 1; // Again not used.
for (X = 0; X >= stars; X =+ 1){ // your for loop is wrong; it reads like this. for x = 0 and x is bigger than stars, do blah. then you don't actually increment X because it should be X += 1 not X =+ 1.
System.out.print("*");
}
System.out.println(); //creates a new line to add on too
}
}
}
Here's a working implementation of your code using the same structure you are using.
public static void main(String[] args) {
int lines = 1;
while (lines <= Integer.parseInt(args[0])){
for (int x = 0; x < lines; x += 1){
System.out.print("*");
}
lines += 1;
System.out.println();
}
}

Tic Tac Toe in Java [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 9 years ago.
Improve this question
I am writing a tic tac toe game in java. Right now I am currently stuck on the display board method. The board I am trying to create has lines in which the X's and O's will go into. The error I am currently getting is
TicTac2.java:56: error: illegal start of type
return result;
^
TicTac2.java:56: error: ';' expected
return result;
I will update this code as I go along it with little problems I encounter. I love this site because it helps so much! Anyway here is my code:
import java.util.*;
public class TicTac2{
//declare a constant variable
public enum Cell {E, X, O}; //this is an O, not 0
public Cell[][] board;
public static final int SIZE = 3; //size of each row and each column
public static void main(String[] args) {
displayBoard a = new displayBoard();
System.out.println(a);
}
//displayBoard method
public static void drawLine() {
for (int i = 0; i <= 4 * SIZE; i++) {
System.out.print("-");
}
System.out.println();
}
public static void displayBoard(char[][] board) {
drawLine();
for (int i = 0; i < SIZE; i++) {
for (int j = 0; j < SIZE; j++) {
SIZE[i][j] = Cell.E;
System.out.print("| " + board[i][j] + " ");
}
System.out.println("|");
drawLine();
}
System.out.println();
}
public String toString(){
String result = "";
for(Cell[] row : board) {
for(Cell col : row)
result += col;
}
result =+ "\n";
}
return result;
}
You are missing a { bracket
for(Cell col : row) { // <--- add this guy
result += col;
}
Consider learning to use an IDE. An IDE will point out these errors almost immediately. It will also find all other syntax errors.
displayBoard a = new displayBoard();
System.out.println(a);
I'm confused by these lines.
You are defining DisplayBoard as a method that takes in a two-dimensional array of Cells, but in the code above you are treating it like a class.
You don't want to create a displayBoard object (as it isn't a class), you just want to call the methods (and pass in board!).

Categories

Resources