If statement not running correctly - java

What I'm trying to do is get my program to run a method to make lemonade (makeLemonade) if and only if I have enough ingredients to make the lemonade, but I keep getting an error from the tests provided for me that tells my lemonade is being made even when I don't have enough ingredients.
Here's the code I have right now for the if statement that's giving me some trouble. I've tried using && and || along with different mixes of >= and > to no avail so far.
public int makeLemonade() {
if (lemons >= 6 && gallonsOfWater >= 1 && cupsOfSugar >= 1 && emptyGlasses >= 8) {
lemons = lemons - 6;
gallonsOfWater = gallonsOfWater - 1;
cupsOfSugar = cupsOfSugar - 1;
emptyGlasses = emptyGlasses - 8;
glassesOfLemonade = glassesOfLemonade + 8;
return glassesOfLemonade;
} else {
return 0;
}
}
This is the error my test is giving me right now
"Test of method makeLemonade failed for activty 3.
The following code was executed:
LemonadeStand ls = new LemonadeStand(5, 2, 2, 16, 1.1);
ls.makeLemonade();
Fields were modified even though there was not enough lemons available to make lemonade."
Here is the entire code so far
/**
* LemonadeStand.java
*
*/
//Put any imports below this line.
/**
* Short, one-line description of LemonadeStand class here.
*
* Optionally, include a paragraph that provides a more
* detailed description.
*
* #author Nicholas Thomas
* #version 2/19/2018
*/
public class LemonadeStand
{
//Put instance variables below this line.
private int lemons;
private int gallonsOfWater;
private int cupsOfSugar;
private int emptyGlasses;
private double price;
private double income;
private int glassesOfLemonade;
/** No arg constructor.
* LemonadeStand Constructor
*
*/
public LemonadeStand()
{
lemons = 0;
gallonsOfWater = 0;
cupsOfSugar = 0;
glassesOfLemonade = 0;
emptyGlasses = 0;
price = 0;
income = 0;
}
/** Contructor.
* LemonadeStand Constructor
*
* #param newLemons A parameter
* #param newGallonsOfWater A parameter
* #param newCupsOfSugar A parameter
* #param newEmptyGlasses A parameter
* #param newPrice A parameter
*/
public LemonadeStand(int newLemons, int newGallonsOfWater,
int newCupsOfSugar, int newEmptyGlasses, double newPrice)
{
setLemons(newLemons);
setGallonsOfWater(newGallonsOfWater);
setCupsOfSugar(newCupsOfSugar);
setEmptyGlasses(newEmptyGlasses);
setPrice(newPrice);
glassesOfLemonade = 0;
income = 0;
}
/** Main method of the program.
* Method main
*
* #param args A parameter
*/
public static void main(String[] args)
{
LemonadeStand lemonadeStand = new LemonadeStand(15, 3, 4, 20, 1.5);
lemonadeStand.makeLemonade();
System.out.println(lemonadeStand.getLemons());
System.out.println(lemonadeStand.getGallonsOfWater());
System.out.println(lemonadeStand.getCupsOfSugar());
System.out.println(lemonadeStand.getGlassesOfLemonade());
}
/** Mutator to change the amount of lemons.
* Method setLemons
*
* #param newLemons A parameter
* #return newLemons
*/
public int setLemons(int newLemons)
{
if (lemons < 0)
{
lemons = newLemons;
return newLemons;
}
else
{
return 0;
}
}
/** Mutator to change gallons of water.
* Method setGallonsOfWater
*
* #param newGallonsOfWater A parameter
* #return gallonsOfWater
*/
public int setGallonsOfWater(int newGallonsOfWater)
{
if (gallonsOfWater < 0)
{
gallonsOfWater = newGallonsOfWater;
return gallonsOfWater;
}
else
{
return 0;
}
}
/** Mutator to set cups of sugar.
* Method setCupsOfSugar
*
* #param newCupsOfSugar A parameter
* #return cupsOfSugar
*/
public int setCupsOfSugar(int newCupsOfSugar)
{
if (cupsOfSugar < 0)
{
cupsOfSugar = newCupsOfSugar;
return cupsOfSugar;
}
else
{
return 0;
}
}
/** Mutator to modify the number of empty glasses.
* Method setEmptyGlasses
*
* #param newEmptyGlasses A parameter
* #return emptyGlasses
*/
public int setEmptyGlasses(int newEmptyGlasses)
{
if (emptyGlasses < 0)
{
emptyGlasses = newEmptyGlasses;
return emptyGlasses;
}
else
{
return 0;
}
}
/** Mutator to modify the glasses of lemonade.
* Method setGlassesOfLemonade
*
* #param newGlassesOfLemonade A parameter
* #return glassesOfLemonade
*/
public int setGlassesOfLemonade(int newGlassesOfLemonade)
{
if (glassesOfLemonade < 0)
{
glassesOfLemonade = newGlassesOfLemonade;
return glassesOfLemonade;
}
else
{
return 0;
}
}
/** Mutator to change the price.
* Method setPrice
*
* #param newPrice A parameter
* #return price
*/
public double setPrice(double newPrice)
{
if (price < 0)
{
price = newPrice;
return price;
}
else
{
return 0;
}
}
/** Mutator to set the income.
* Method setIncome
*
* #param newIncome A parameter
* #return income
*/
public double setIncome(double newIncome)
{
if (income < 0)
{
income = newIncome;
return income;
}
else
{
return 0;
}
}
/** Accessor to make lemonade.
* Method makeLemonade
*
* #return The return value
**/
public int makeLemonade()
{
if (lemons >= 6 && gallonsOfWater >= 1 && cupsOfSugar >= 1
&& emptyGlasses >= 8)
{
lemons -= 6;
gallonsOfWater -= 1;
cupsOfSugar -= 1;
emptyGlasses -= 8;
glassesOfLemonade += 8;
return glassesOfLemonade;
}
else
{
return 0;
}
}
/** Accessor to lemonade selling.
* Method sellLemonade
*
* #return The return value
*/
public int sellLemonade()
{
if (glassesOfLemonade <= 1)
{
makeLemonade();
return 0;}
else
{
glassesOfLemonade = glassesOfLemonade - 1;
income = income + price;
return glassesOfLemonade;
}
}
/** Accessor to get number of lemons.
* Method getLemons
*
* #return The return value
*/
public int getLemons()
{
return lemons;
}
/** Accessor to return gallons of water.
* Method getGallonsOfWater
*
* #return The return value
*/
public int getGallonsOfWater()
{
return gallonsOfWater;
}
/** Accessor to return cups of sugar.
* Method getCupsOfSugar
*
* #return The return value
*/
public int getCupsOfSugar()
{
return cupsOfSugar;
}
/** Accessor to return the value of empty glasses.
* Method getEmptyGlasses
*
* #return The return value
*/
public int getEmptyGlasses()
{
return emptyGlasses;
}
/** Accessor to return glasses of lemonade.
* Method getGlassesOfLemonade
*
* #return The return value
*/
public int getGlassesOfLemonade()
{
return glassesOfLemonade;
}
/** Accessor to return the price.
* Method getPrice
*
* #return The return value
*/
public double getPrice()
{
return price;
}
/** Accesor to return the income rate.
* Method getIncome
*
* #return The return value
*/
public double getIncome()
{
return income;
}
/** Accessor for lemonade selling.
* Method sellMoreLemonade
*
* #param requestedGlasses A parameter
* #return The return value
*/
public int sellMoreLemonade(int requestedGlasses)
{
return 0;
}
}

The main issue with the code is the setter-usage. For example:
if (gallonsOfWater < 0) {
gallonsOfWater = newGallonsOfWater;
return gallonsOfWater;
} else {
return 0;
}
The gallonsOfWater field of LemonadeStand is initialized e.g. in the 2nd constructor by the call setGallonsOfWater(newGallonsOfWater);.
Let us assume that you pass the value 3 to this constructor, so it will be setGallonsOfWater(3);. In the setter this leads to 3 < 0 and hence
the return value of 0 for the setter.
not setting the value for the field gallonsOfWater.
(I assume that debugging would have helped here also)

Related

How do I move the star into the place it belongs

That is my homework assignment in the link above. This is what I did so far:
import java.util.Scanner;
public class Bowling {
public static void recursionPins(int n, int t) {
if (n == 1) {
System.out.print("\t\t");
for (int i = 1; i <= t - 1; i++)
System.out.print(" ");
System.out.println("*");
} else {
recursionPins(n - 1, t);
for (int i = 1; i <= t - n; i++)
System.out.print(" ");
for (int i = 1; i <= n; i++)
System.out.print("* ");
System.out.println();
}
}
// main method
public static void main(String args[]) {
Scanner scan = new Scanner(System.in);
System.out.print("Enter number of rows of pins: ");
int n = scan.nextInt();
recursionPins(n, n);
}
}
When I run it, the first * is out of place and I'm not sure what the error is. The link below is a sample run of the program.
Enter number of rows of pins: 10
*
* *
* * *
* * * *
* * * * *
* * * * * *
* * * * * * *
* * * * * * * *
* * * * * * * * *
* * * * * * * * * *
I'm not sure how to move the star over.
Here in the base case:
if (n == 1) {
System.out.print("\t\t");
for (int i = 1; i <= t - 1; i++)
System.out.print(" ");
System.out.println("*");
}
You are printing two tabs and the required number of spaces. You need to remove System.out.print("\t\t");:
if (n == 1) {
for (int i = 1; i <= t - 1; i++)
System.out.print(" ");
System.out.println("*");
}
Output:
Enter number of rows of pins: 5
*
* *
* * *
* * * *
* * * * *

Eight Queens Algorithm for Different Starting Points

I am trying to find a solution to the Eight Queens problem regardless of the starting point. Below is my Solver class, however it doesn't work for some reason when I place the queen in a row other than the first one.
import java.util.*;
public class Queens {
private static int x;
private static int y;
private static ArrayList<Integer> rows = new ArrayList<Integer>();
public Queens(int index, int row, int pos) {
for (int i = 0; i<index; i++)
rows.add(i);
rows.remove(row);
x = pos;
y = row;
}
public static boolean solve(int row, int[][] board, int N, int pos) {
board[y][x] = 1;
System.out.println("row: " + row);
for(int i = 0; i < 8; i++) {
for(int j = 0; j < 8; j++) {
if(board[i][j]==1) System.out.print("Q ");
else System.out.print("* ");
}
System.out.println();
}
System.out.println();
if(row>=N-1) return true;
for(int position = pos; position < N; position++) {
if(isValid(board, rows.get(row), position, N)) {
board[rows.get(row)][position] = 1;
if(!solve(row+1, board, N, 0)) {
board[rows.get(row)][position] = 0;
} else
return true;
}
}
return false;
}
public static boolean isValid(int[][] board, int y, int x, int N) {
int i, j;
for(i = 0; i < y; i++)
if(board[i][x]==1)
return false;
i = y - 1;
j = x - 1;
while((i>=0)&&(j>=0))
if(board[i--][j--]==1) return false;
i = y - 1;
j = x + 1;
while((i>=0)&&(j<N))
if(board[i--][j++]==1) return false;
return true;
}
}
For example, when I place the initial queen on board[2][2], this is the solution I get:
Q * * * * * * *
* * Q * * * * *
* * Q * * * * *
* * * * * Q * *
* * * * * * * Q
* Q * * * * * *
* * * Q * * * *
* * * * * * Q *
What is wrong with the code? Why does it disregard the initial piece? Thanks in advance.
What are the bounds for the for loop in isValid? Do they prevent you from placing a queen into a column where there's another queen below?
A similar question applies also to the while loops -- can they detect that there's a queen on the diagonal but below the one you're placing now?

Neural Network bad convergeance

I read a lot about NN last two weeks, I think i saw pretty much every "XOR" approach tutorials on net. But, i wasn't able to make work my own one. I started by a simple "OR" neuron approach. Giving good results. I think my problem is in backpropagation implementation. I did an object approach, so here are the main lines.
Three classes :
Neuron
public class Neuron {
/*
* Attributes
*/
double[] inputs;
double[] weights;
double output;
double error;
double delta;
double deltaWeight;
/*
* Constructors
*/
public Neuron(int nInputs)
{
inputs = new double[nInputs + 1];
inputs[inputs.length - 1] = 1; // bias
weights = new double[nInputs + 1];
}
/*
* Methods
*/
/**
* Reset all weights of the neuron to random values between -1 and 1
*/
public void reset()
{
Random random = new Random();
for (int i = 0; i < weights.length; i++)
weights[i] = (random.nextDouble() * ((0.5d - (-0.5d))) + (-0.5d));
}
/**
* Compute output for given inputs
* #param inputs
*/
public void computeOutput(double inputs[])
{
setInputs(inputs);
output = Sigmoid.activation(getDotProduct());
}
/**
* Compute error for given ideal
* #param ideal
*/
public void computeError(double ideal)
{
error = ideal - output;
delta = error;
}
/**
* Compute error for hidden neurons
*/
public void computeError(FeedForwardLayer previousLayer, int position)
{
double sum = 0;
for (int i = 0; i < previousLayer.neurons.length; i++)
sum += (previousLayer.neurons[i].delta * previousLayer.neurons[i].weights[position]);
delta = Sigmoid.derivative(getDotProduct()) * sum;
error = delta;
}
/**
* Adjust every weight of the neuron
*/
public void adjustWeights(double lambda, double momentum)
{
for (int i = 0; i < weights.length; i++)
{
double lastDeltaWeight = deltaWeight;
deltaWeight = lambda * (delta * inputs[i]) + momentum * lastDeltaWeight;
weights[i] += deltaWeight;
}
}
#Override
public String toString()
{
String str = "";
for (int i = 0; i < weights.length; i++)
str = str.concat(String.format("IN|W --> %.6f | %.6f \n", (float) inputs[i], (float) weights[i]));
str = str.concat("Output = " + output + "\n");
str = str.concat("Error = " + error + "\n");
return str;
}
/*
* Getters & Setters
*/
/**
* #return weights * inputs + bias
*/
public double getDotProduct()
{
double sum = 0;
for (int i = 0; i < inputs.length; i++)
sum += (weights[i] * inputs[i]);
return sum;
}
/**
* Set inputs (keep bias input)
* #param inputs
*/
public void setInputs(double[] inputs)
{
for (int i = 0; i < inputs.length; i++)
this.inputs[i] = inputs[i];
}
/**
* Set every weight to a single value
* #param weight
*/
public void setWeights(double weight)
{
for (int i = 0; i < weights.length; i++)
this.weights[i] = weight;
}
}
FeedForwardLayer (which contain neurons)
public class FeedForwardLayer {
/*
* Attributes
*/
Neuron[] neurons;
LayerTypes type;
/*
* Constructors
*/
/**
* First layer constructor
* #param nNeurons
*/
public FeedForwardLayer(int nInputs, int nNeurons, LayerTypes type)
{
neurons = new Neuron[nNeurons];
for (int i = 0; i < neurons.length; i++)
neurons[i] = new Neuron(nInputs);
this.type = type;
}
/*
* Methods
*/
/**
* Reset all weights of the layer's neurons to random values between -1 and 1
*/
public void reset()
{
for (Neuron neuron : neurons)
neuron.reset();
}
/**
* Compute output, if layer isn't input one, you can pass null into parameter
* #param inputs
*/
public void computeOutputs(double[] inputs)
{
for (int i = 0; i < neurons.length; i++)
neurons[i].computeOutput(inputs);
}
/**
* Compute error, if layer is output one
* #param ideals
*/
public void computeErrors(double[] ideals)
{
for (int i = 0; i < neurons.length; i++)
neurons[i].computeError(ideals[i]);
}
/**
* Compute error, if layer isn't output one
* #param layer n+1
*/
public void computeErrors(FeedForwardLayer next)
{
for (int i = 0; i < neurons.length; i++)
neurons[i].computeError(next, i);
}
/**
* Adjust weights for every neurons
*/
public void adjustWeights(double lambda, double momentum)
{
for (Neuron neuron : neurons)
neuron.adjustWeights(lambda, momentum);
}
#Override
public String toString()
{
String str = "";
for (int i = 0; i < neurons.length; i++)
str = str.concat("Neuron " + i + "\n" + neurons[i]);
return str;
}
/*
* Getters - Setters
*/
/**
* #return true if layer is input, false otherwise
*/
public boolean isInput()
{
if (type == LayerTypes.INPUT)
return true;
return false;
}
/**
* #return true if layer is input, false otherwise
*/
public boolean isOutput()
{
if (type == LayerTypes.OUTPUT)
return true;
return false;
}
/**
* #return an array of layer's outputs
*/
public double[] getOutputs()
{
double[] outputs = new double[neurons.length];
for (int i = 0; i < neurons.length; i++)
outputs[i] = neurons[i].output;
return outputs;
}
/**
* #return array of layer's errors
*/
public double[] getErrors()
{
double[] errors = new double[neurons.length];
for (int i = 0; i < neurons.length; i++)
errors[i] = neurons[i].error;
return errors;
}
/**
* Set all the weights of the layer to given weight
* #param weight
*/
public void setWeights(double weight)
{
for (int i = 0; i < neurons.length; i++)
neurons[i].setWeights(weight);
}
}
FeedForwardNetwork (which contain FeedForwardLayers)
public class FeedForwardNetwork {
static final double lambda = 0.1;
static final double momentum = 0;
/*
* Attributes
*/
private ArrayList<FeedForwardLayer> layers;
/*
* Constructors
*/
public FeedForwardNetwork()
{
layers = new ArrayList<FeedForwardLayer>();
}
/*
* Methods
*/
/**
* Init all the weights to random values
*/
public void reset()
{
for (int i = 0; i < layers.size(); i++)
layers.get(i).reset();;
}
/**
* Compute output for all the neurons of all the layers for given inputs
* #param inputs
*/
public void feedForward(double[] inputs)
{
//System.err.println("FeedForwardNetwork.feedForward(" + inputs[0] + ", " + inputs[1] +")");
for (int i = 0; i < layers.size(); i++)
{
//System.err.println("\n*** COMPUTING OUTPUT FOR LAYER " + i + "***\n");
if (layers.get(i).isInput())
layers.get(i).computeOutputs(inputs);
else
layers.get(i).computeOutputs(layers.get(i - 1).getOutputs());
}
}
/**
* Compute errors for all the neurons of all the layers starting by output layer
* #param ideals
*/
public void feedBackward(double[] ideals)
{
//System.err.println("FeedForwardNetwork.feedBackward(" + ideals[0] + ")");
// For each layers starting by output one
for (int i = layers.size() - 1; i > 0; i--)
{
//System.err.println("*** COMPUTING ERROR FOR LAYER " + i + "***");
if (layers.get(i).isOutput())
layers.get(i).computeErrors(ideals);
else
layers.get(i).computeErrors(layers.get(i + 1));
}
}
/**
* Adjust weights of every layer
*/
public void adjustWeights()
{
for (FeedForwardLayer feedForwardLayer : layers)
feedForwardLayer.adjustWeights(lambda, momentum);
}
/**
* Train the nn with given inputs and outputs
* #param inputs
* #param outputs
*/
public void train(double[] inputs, double... outputs)
{
feedForward(inputs);
feedBackward(outputs);
adjustWeights();
}
/**
* Add a layer to the network
* #param layer
*/
public void addLayer(FeedForwardLayer layer)
{
layers.add(layer);
}
#Override
public String toString()
{
String str = "";
for (int i = 0; i < layers.size(); i++)
str = str.concat("Layer " + LayerTypes.values()[i] + "\n" + layers.get(i));
str = str.concat("\n");
str = str.concat("OUTPUT = " + getOutputs()[0] + "\n");
str = str.concat("ERROR = " + getError(false) + "\n");
return str;
}
/*
* Getters & Setters
*/
public FeedForwardLayer getInputLayer()
{
return layers.get(0);
}
public FeedForwardLayer getOutputLayer()
{
return layers.get(layers.size() - 1);
}
public FeedForwardLayer getLayer(int index)
{
return layers.get(index);
}
public double getError(boolean abs)
{
if (abs)
return Math.abs(getOutputLayer().neurons[0].error);
return getOutputLayer().neurons[0].error;
}
public double[] getOutputs()
{
return getOutputLayer().getOutputs();
}
}
So i train the network by giving it epoch of the xor table
XOR table
X | Y | S
0 0 0
0 1 1
0 1 1
0 0 0
The network will output after thousands epoch approximately 0.5...
Interesting fact is, if i replace the training set by a AND table, a OR table or an NAND table, the nn will output the number of 1 in the S column of the training set.. (it will output 0.25 for AND and NAND table and 0.75 for OR table)
I just want to know if my implementation is good enough to make it work, ty !
So, after some research, i realized that my implementation was good, except that I didn't understand how the input layer works. That was it, the input layer works like In = Out

2 Dimensional Arrays (Java) - Printing a Triangle with Alphabets in Cyclic order

The query was to write a Java method which prints the following triangle based on the input given (of the number of alphabets, on each side of the triangle).
public void triangle(int side);
Output expected:
triangle(3)
* * A * *
* F * B *
E * D * C
triangle(4)
* * * A * * *
* * I * B * *
* H * * * C *
G * F * E * D
I've come up with a method which does just that, but the code that I've written with my limited experience is with more number of for loops. Can any of you can review my code and come up with suggestions or optimized code for the same problem?
public void triangle(int input) {
int x = input;
int y = 2 * input - 1;
int mid = y / 2;
char character = 'A';
String[][] partitionArray1 = new String[x][y];
\\Following for loop will add letters on the side-1
for (int i = 0; i < x; i++) {
for (int j = 0; j < y; j++) {
if (i + mid == j) {
partitionArray1[i][j] = "" + character++;
} else {
partitionArray1[i][j] = "*";
}
}
}
\\Following for loop will add letters on the side-2 (horizontal)
for (int j = y - 2; j >= 0; j--) {
j--;
if (j >= 0) {
partitionArray1[x - 1][j] = "" + character++;
} else {
break;
}
}
\\Following for loop will add letters on the side-3
for (int i = x - 2; i >= 0; i--) {
for (int j = 0; j < y; j++) {
if ((i == mid - j) && (j < mid)) {
partitionArray1[i][j] = "" + character++;
}
}
}
for (int i = 0; i < x; i++) {
for (int j = 0; j < y; j++) {
System.out.print(partitionArray1[i][j] + "");
}
System.out.println();
}
}
Is there an algorithm available to answer such problems?
Try:
public static void triangle(int n) {
for (int i = 0; i < n; ++i) {
if (i == n-1) {
for (int j = 0; j < 2*n-1; ++j)
if (j % 2 == 0)
System.out.printf("%c ", 'A' + 2*n-2-j/2);
else
System.out.printf("* ");
System.out.println();
break;
}
for (int j = 0; j < 2*n-1; ++j) {
if (j == n-1+i)
System.out.printf("%c ", 'A'+i);
else if (j == n-1-i)
System.out.printf("%c ", 'A'+3*n-i-3);
else
System.out.printf("* ");
}
System.out.println();
}
}
The idea is to print row #n separately from the other. The rest of the row have exactly two element(except the first one which is a degenerated case) symmetrical with respect the center.
triangle(9);
* * * * * * * * A * * * * * * * *
* * * * * * * X * B * * * * * * *
* * * * * * W * * * C * * * * * *
* * * * * V * * * * * D * * * * *
* * * * U * * * * * * * E * * * *
* * * T * * * * * * * * * F * * *
* * S * * * * * * * * * * * G * *
* R * * * * * * * * * * * * * H *
Q * P * O * N * M * L * K * J * I
I was bored so i did it with one array
public static void mimi(int size){
int sizetab=size*size*2;
char res[] = new char[sizetab];
Arrays.fill(res,'*');
int pos=size-1;
int JumpGoRight=(2*size)+1;
int JumpGoLeft=2;
char letter='A';
boolean changed = false;
int nbLetters = size -1;
for (int s=size;s>1;s--)
nbLetters+=2;
int i=0;
while(i<(size-1)){
res[pos]=letter++;
pos+=JumpGoRight;
i++;
}
int limit=(sizetab-(size*2))+1;
while(i<nbLetters){
res[pos]=letter++;
pos-=JumpGoLeft;
if( !changed && (pos<limit) ){
JumpGoLeft=(size*2)-1 ;
changed=true;
}
i++;
}
int index = 0;
int doublesize=size*2;
for(char c: res){
if( ((++index)%doublesize)==0)
System.out.print('\n');
else
System.out.print(c);
}
}

I'm not sure how to add spaces to the small triangles to make it into a larger triangle

So basically my program will print this type of triangle when user input a number that module 8 and equal to 0. So a larger triangle is made out of smaller triangle with a base of 4. This is how a triangle look like when i input number 16:
* * * * * * * * * * * * * * * *
* * * * * * * * * * * *
* * * * * * * *
* * * *
* * * * * * * * * * * *
* * * * * * * * *
* * * * * *
* * *
* * * * * * * *
* * * * * *
* * * *
* *
* * * *
* * *
* *
*
but mine turned out like this:
* * * * * * * * * * * * * * * *
* * * * * * * * * * * *
* * * * * * * *
* * * *
* * * * * * * * * * * *
* * * * * * * * *
* * * * * *
* * *
* * * * * * * *
* * * * * *
* * * *
* *
* * * *
* * *
* *
*
I'm not so sure how to add the spaces. Can someone help me out? Here is my code:
...
System.out.println("Please enter the length:");
int length = scan.nextInt();;
//length must be longer than 2
if (length <= 1){
System.out.println("Sorry :(! Length must be 2 or higher");
}
//if user enter a number that can divide by 8 and has no remainder, then
//loop to print out a beautiful triangle
else if(length%8==0) {
int numOfTriangle = length/4;
System.out.println("Here is your beautiful triangle :D \n");
for (int rowOfTri = numOfTriangle; rowOfTri > 0; rowOfTri--){
for(int i = 0; i < rowOfTri; i++){
printBase();
}
System.out.println();
for(int i = 0; i < rowOfTri; i++){
printThree();
}
System.out.println();
for(int i = 0; i < rowOfTri; i++){
printTwo();
}
System.out.println();
for(int i = 0; i < rowOfTri; i++){
printOne();
}
System.out.println();
}
System.out.println();
}
//any other number will print a normal triangle
else{
System.out.println("Here is your beautiful triangle :D \n");
for (int i = 1; i <= length; i++){
for (int j = 1; j <= length; j++){
if (j < i){
System.out.print(" ");
} else {
System.out.print("*");
System.out.print(" ");
}
}
System.out.println();
}
}
//asking users if they want to print again
System.out.println("\nDo you want to print another triangle? Type Yes or No.");
//scan for string answer
String againChoice = scan.next();
//if answer start with Y or y then answer is Yes.
if(againChoice.startsWith("Y") || againChoice.startsWith("y")){
printAgain = true;
}
//if answer start with N or n then answer is No.
else if(againChoice.startsWith("N") || againChoice.startsWith("n")){
printAgain = false;
System.out.println("Bye!");
}
// set input to none again
} while (printAgain == true);
}
//methods to print a triangle
public static void printBase(){
System.out.print("* * * * ");
}
public static void printThree(){
System.out.print(" * * * ");
}
public static void printTwo(){
System.out.print(" * * ");
}
public static void printOne(){
System.out.print(" * ");
}
public static void printSpace(){
System.out.print(" ");
}
}
I've changed your printing code like this and it works properly:
else if (length % 8 == 0) {
int layer = 0;
int numOfTriangle = length / 4;
System.out.println("Here is your beautiful triangle :D \n");
for (int rowOfTri = numOfTriangle; rowOfTri > 0; rowOfTri--) {
for (int i = 0; i < layer; i++) {
printSpace();
}
for (int i = 0; i < rowOfTri; i++) {
printBase(layer);
}
System.out.println();
for (int i = 0; i < layer; i++) {
printSpace();
}
for (int i = 0; i < rowOfTri; i++) {
printThree(layer);
}
System.out.println();
for (int i = 0; i < layer; i++) {
printSpace();
}
for (int i = 0; i < rowOfTri; i++) {
printTwo(layer);
}
System.out.println();
for (int i = 0; i < layer; i++) {
printSpace();
}
for (int i = 0; i < rowOfTri; i++) {
printOne(layer);
}
System.out.println();
layer++;
}
System.out.println();

Categories