I have been unable to get my for loop to run right number of times with my "figure" when scaling.
The LINES constant here is the scaling "number".
The problem i am facing lies here i think:
for(int k = 0; k < LINES; k++){
System.out.print("*******");
}
It is supposed to make a line of * at the bottom.
This is my whole code which produces a stairs figure of some kind
public class PP5 {
public static int j;
public static final int LINES = 5;
public static void main(String[] args) {
for(j = 0 ; j < LINES; j++){
fSpaces();
System.out.print(" o *******");
bSpaces();
System.out.println("*");
fSpaces();
System.out.print(" /|\\ *");
bbSpaces();
System.out.println("*");
fSpaces();
System.out.print(" / \\ *");
bbSpaces();
System.out.println("*");
}
for(int k = 0; k < LINES; k++){
System.out.print("*******");
}
}
public static void fSpaces(){
for(int i = (LINES-1); i > j; i--){
System.out.print(" ");
}
}
public static void bSpaces(){
for(int i = 0; i < j; i++){
System.out.print(" ");
}
}
public static void bbSpaces(){
for(int i = 0; i < j+1; i++){
System.out.print(" ");
}
}
}
Any optimizations is highly appreciated.
Thanks
you require 38 stars and you are printing 35
38=(6(Every increment) * 6 (No of times) )+2 (first increment is of 8[6+2])
No of times =6 Because indexing starts from 0 (0,1,2,3,4,5) so in actual counting is 6
so use
for(int k = 0; k <(LINES+1)*6; k++){
System.out.print("*");
}
System.out.print("**");// last star
Output:
o ********
/|\ * *
/ \ * *
o ******* *
/|\ * *
/ \ * *
o ******* *
/|\ * *
/ \ * *
o ******* *
/|\ * *
/ \ * *
o ******* *
/|\ * *
/ \ * *
**************************************
To get effect similar to this
o ********
/|\ * |*
/ \ * |*
o ******* |*
/|\ * | |*
/ \ * | |*
o ******* | |*
/|\ * | | |*
/ \ * | | |*
o ******* | | |*
/|\ * | | | |*
/ \ * | | | |*
o ******* | | | |*
/|\ * | | | | |*
/ \ * | | | | |*
**************************************
|_____|_____|_____|_____|_____|_____|_
you need to notice that each of this part |_____
has six characters so you will need to use six * and print them LINES + 1 times since there are LINES + 1 |_____ parts.
This will generate
************************************|_
from
|_____|_____|_____|_____|_____|_____|_
so you will need to add last two * manually so change your last loop to
for (int k = 0; k <= LINES; k++) {
System.out.print("******");//reduce star numbers by one
}
System.out.print("**");//and add this line
In your implementation just replace
for(int k = 0; k < LINES; k++){
System.out.print("*******");
}
with
for(int k = 0; k < STEPS+1; k++){
System.out.print("******");
}
System.out.print("**");
The motivation is that each step you add 7 * with one overlapping. This means that you need to add 6 * not 7. You add 1 time more to match the top part (but 2 * are missing: 1 because the top line is made of 7* and one for the column).
Related
I need a bit of help with a project, I want to create a java program that creates a kind of histogram in the shape of triangles, its hard to explain so look at the following example
input : 3 1 12 0 7
output:
_
/|\
/ | \
/ | \
/ | \
/ | \ _
/ | \ /|\
/ | \ / | \
/ | \ / | \
_ / | \ / | \
/|\ / | \ / | \
/ | \ _ / | \ / | \
/ | \ /|\ / | \ _ / | \
<=======><===><=========================><=><===============>
| | | | | | | | |
in my code I've managed to create the input part, and the generator of the base, but the triangles/piramides generator doesnt make the correct spaces, anyone can help me?
here is my code to make the triangles (assuming the input is what is in the array numbers and numbers2):
public class Spires{
public static void main(String[] args){
int[] numbers = {3,1,12,0,7};
int counter = 6, max = 12;
int[] numbers2 = {3,1,12,0,7};
for(int row = max+1; row >= 0; --row) {
System.out.println();
for(int col = 0; col < counter-1; ++col) {
if(numbers2[col] >= row){
for(int spacesleft = 1; spacesleft < (numbers2[col] + col)+row-1; ++spacesleft){
System.out.print(" ");
}
if(numbers2[col] != row){
System.out.print("/");
for(int c3 = 0; c3 < numbers2[col]-row-1; ++c3) {
System.out.print(" ");
}
System.out.print("|");
for(int c3 = 0; c3 < numbers2[col]-row-1; ++c3) {
System.out.print(" ");
}
System.out.print("\\");
}else{
System.out.print("_");
}
// for(int spacesright = 1; spacesright < numbers2[col] + col + row -1; ++spacesright){
// System.out.print(" ");
// }
}
}
}
System.out.println();
//base generator
for(int i = 0; i<counter-1; ++i) {
System.out.print("<");
for(int i2 = 0; i2 < 2*numbers[i]+1; ++i2) {
System.out.print("=");
}
System.out.print(">");
}
System.out.println();
for(int i = 0; i<counter-1; ++i) {
if(numbers[i] != 0){
System.out.print(" |");
for(int i2 = 0; i2 < 2*numbers[i]-1; ++i2) {
System.out.print(" ");
}
System.out.print("| ");
}else{
System.out.print(" | ");
}
}
}
}
My output comes out like this:
_
/|\
/ | \
/ | \
/ | \
/ | \ _
/ | \ /|\
/ | \ / | \
/ | \ / | \
_ / | \ / | \
/|\ / | \ / | \
/ | \ _ / | \ / | \
/ | \/|\ / | \ _ / | \
<=======><===><=========================><=><===============>
| | | | | | | | |
I need some help figuring out how to add the missing spaces and remove some
You're almost there! Just a couple tweaks that need to be made.
The calculation for number of outside spaces on the left and right side of the triangle legs is actually very simple: row + 1. Because each triangle is being built from the bottom up, triangles shown on row 0 (bottom row) need 1 space, row 1 need 2 spaces, etc.
If the current row is "above" the triangle column you are displaying, you still need to output spaces to mark a placeholder for that triangle. So the if (numbers2[col] >= row) needs a corresponding else to display spaces instead.
Applying these two changes gets something like:
if(numbers2[col] >= row){
// corrected calculation \-------/
for(int spacesleft = 0; spacesleft < row + 1; ++spacesleft){
System.out.print(" ");
}
if(numbers2[col] != row){
System.out.print("/");
for(int c3 = 0; c3 < numbers2[col] - row - 1; ++c3) {
System.out.print(" ");
}
System.out.print("|");
for(int c3 = 0; c3 < numbers2[col] - row - 1; ++c3) {
System.out.print(" ");
}
System.out.print("\\");
}else{
System.out.print("_");
}
// corrected calculation \-------/
for(int spacesright = 0; spacesright < row + 1; ++spacesright){
System.out.print(" ");
}
// output spaces to fill area for that column and shift everything over properly
} else {
for (int spaces = 0; spaces < numbers2[col] * 2 + 3; spaces++)
System.out.print(" ");
}
This should output the histogram as expected.
Now I'd like you to consider why this code is challenging to work with. There is a direct relationship to the number of variables and ideas you have to hold in your head at once, to the difficulty of reading and understanding a piece of code.
One way you could make this code easier to reason about is by breaking it up into different functions that handle different aspects of the problem individually. For example, we might add methods for:
printing a certain number of spaces
printing one row of a triangle
Also it helps to use more variables with intuitive names, so you don't have to keep reasoning through the entire calculations. Here is an example that should demonstrate:
// output 'count' spaces
public static void printSpaces(int count) {
for (int spaces = 0; spaces < count; spaces++) System.out.print(" ");
}
// output one row of a triangle based on supplied height
// and current display row, starting at 0=top row.
public static void printTriangleSection(int triangleHeight, int rowOfTriangle) {
int triangleWidth = triangleHeight * 2 + 3; // total width taken up by this triangle
int halfWidth = triangleHeight + 1; // total width taken up by one side (excluding the middle)
int spacesOutside = halfWidth - rowOfTriangle; // total spaces outside of triangle hypotenuse
int spacesInside = rowOfTriangle - 1; // total spaces inside triangle hypotenuse
if (rowOfTriangle < 0) { // above the first row of the triangle
printSpaces(triangleWidth);
} else if (rowOfTriangle == 0) {
printSpaces(spacesOutside);
System.out.print("_");
printSpaces(spacesOutside);
} else {
printSpaces(spacesOutside);
System.out.print("/");
printSpaces(spacesInside);
System.out.print("|");
printSpaces(spacesInside);
System.out.print("\\");
printSpaces(spacesOutside);
}
}
Then the relevant part of your main method would simplify to this:
for(int row = max+1; row >= 0; --row) {
System.out.println();
for(int col = 0; col < counter-1; ++col) {
printTriangleSection(numbers2[col], numbers2[col] - row);
}
}
Introduction
The reason that I'm providing this answer is to write about how to reason through a coding problem. The triangle histogram was interesting enough for me to work out a solution.
Here's one test run:
Enter the heights of the triangles: 3 1 12 0 7
-
/|\
/ | \
/ | \
/ | \
/ | \ -
/ | \ /|\
/ | \ / | \
/ | \ / | \
- / | \ / | \
/|\ / | \ / | \
/ | \ - / | \ / | \
/ | \ /|\ / | \ - / | \
<=======><===><=========================><=><===============>
| | | | | | | | |
Enter the heights of the triangles:
Reasoning
The heights of the triangles are input, and the histogram triangles are output. Pressing the Enter key without typing any numbers lets the program know to exit.
When I looked at the histogram, I noticed 3 things.
I could create a Java class to form the triangle, and create an instance of the class for each triangle I needed to draw. In the example test run, I create 5 triangles, so I create 5 instances of the class.
If I create the base row first, I can use positioning of the < and > signs to calculate where to start the triangle sides.
The histogram is much easier to create from the bottom up than from the top down.
Now, it helps a lot that I know I can use a StringBuilder to create a blank string and place characters within the blank string using the setCharAt method. This way, I don't have to calculate the number of blanks in between and in the middle of the triangles.
It also helps a lot that I know I can use a List to store the output strings, and print them in the reverse order of their creation.
So, here' the first hint I can give you for solving coding problems.
If something seems real hard to accomplish, ask someone if there's an easier way.
There may not be an easier way. Some coding problems are that hard. But sometimes, you may not be aware of an easier solution.
So, here's the code that produces the histogram.
package com.ggl.testing;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class TriangleHistogram implements Runnable {
public static void main(String[] args) {
new TriangleHistogram().run();
}
#Override
public void run() {
Scanner scanner = new Scanner(System.in);
List<TriangleModel> triangleHistogram = readInput(scanner);
while (triangleHistogram.size() > 0) {
String baseString = createBaseString(triangleHistogram);
String bottomString = createBottomString(triangleHistogram,
baseString.length());
List<String> histogramStrings = new ArrayList<>();
histogramStrings.add(bottomString);
histogramStrings.add(baseString);
createTriangleStrings(triangleHistogram, histogramStrings);
displayHistogram(histogramStrings);
triangleHistogram = readInput(scanner);
}
scanner.close();
}
private List<TriangleModel> readInput(Scanner scanner) {
List<TriangleModel> triangleHistogram = new ArrayList<>();
System.out.print("Enter the heights of the triangles: ");
String inputLine = scanner.nextLine();
if (!inputLine.trim().isEmpty()) {
String[] triangleSizes = inputLine.split("\\s");
for (int i = 0; i < triangleSizes.length; i++) {
TriangleModel triangleModel = new TriangleModel(
Integer.parseInt(triangleSizes[i]));
triangleHistogram.add(triangleModel);
}
}
return triangleHistogram;
}
private String createBaseString(List<TriangleModel> triangleHistogram) {
StringBuilder builder = new StringBuilder();
for (TriangleModel triangleModel : triangleHistogram) {
triangleModel.setColumns(builder);
triangleModel.createBase(builder);
}
return builder.toString();
}
private String createBottomString(List<TriangleModel> triangleHistogram,
int length) {
StringBuilder builder = createStringBuilder(' ', length);
for (TriangleModel triangleModel : triangleHistogram) {
triangleModel.createBottom(builder);
}
return builder.toString();
}
private void createTriangleStrings(List<TriangleModel> triangleHistogram,
List<String> histogramStrings) {
String histogramString = "";
do {
String baseString = histogramStrings.get(1);
StringBuilder builder = createStringBuilder(' ',
baseString.length());
for (TriangleModel triangleModel : triangleHistogram) {
triangleModel.createTriangle(builder);
}
histogramString = builder.toString();
histogramStrings.add(histogramString);
} while (!histogramString.trim().isEmpty());
}
private StringBuilder createStringBuilder(char c, int length) {
StringBuilder builder = new StringBuilder(length);
for (int i = 0; i < length; i++) {
builder.append(c);
}
return builder;
}
private void displayHistogram(List<String> histogramStrings) {
for (int i = histogramStrings.size() - 1; i >= 0; i--) {
String line = histogramStrings.get(i);
System.out.println(line);
}
System.out.println();
}
public class TriangleModel {
private final int height;
private int leftColumn;
private int centerColumn;
private int rightColumn;
public TriangleModel(int height) {
this.height = height;
}
public void setColumns(StringBuilder builder) {
this.leftColumn = builder.length() + 1;
this.centerColumn = leftColumn + height;
this.rightColumn = centerColumn + height;
}
public void createBase(StringBuilder builder) {
builder.append('<');
for (int i = 0; i < getBaseWidth(); i++) {
builder.append('=');
}
builder.append('>');
}
public void createBottom(StringBuilder builder) {
builder.setCharAt(leftColumn, '|');
builder.setCharAt(rightColumn, '|');
}
public void createTriangle(StringBuilder builder) {
if (leftColumn < rightColumn) {
builder.setCharAt(leftColumn, '/');
builder.setCharAt(centerColumn, '|');
builder.setCharAt(rightColumn, '\\');
leftColumn++;
rightColumn--;
} else if (leftColumn == rightColumn) {
builder.setCharAt(centerColumn, '-');
leftColumn++;
rightColumn--;
}
}
private int getBaseWidth() {
return height + height + 1;
}
}
}
Explanation
I made the main TringleHistogram class implement Runnable so that I could put the main code in the run method. I don't like to put a lot of code in the constructor of the class.
The run method is a synopsis of what happens in the code. I get the heights from the user, and I create the histogram. I create the base line first, then the bottom line, then the triangles in reverse order.
The while loop in the run method uses a priming read. I call the readInput method once before the while loop and once again at the end of the while loop. That way, I don't have to skip any part of the while loop when the user just presses the Enter key.
The readInput method doesn't do any error checking. Error checking could be added in the readInput method.
I broke up the code in the TriangleHistogram class into multiple methods. Each method does what the name of the method says it does. Naming methods is important to do descriptively. Generally, I use a verb - noun construction.
The TriangleModel class draws a triangle. Looking in the class, there's not much math involved. As I create the base line, I set the columns of the left center, and right parts of the triangle. As I create each line of the histogram, I adjust the left and right columns until they meet at the top of the triangle.
You can see in the TriangleModel methods that placing characters on a blank StringBuilder is much simpler than appending blanks and characters.
Development
I didn't write the entire program in one shot. I wrote small pieces of the program and tested them. The advantage to writing a little and testing a little is that when you find a problem, you have a good idea where in the code the problem lies.
I wrote the readInput method and enough of the run method to exercise the while loop. I wrote just enough of the TriangleModel class to hold the height. The program didn't do anything but process the input, create a List of TriangleModel objects, and not crash. The not crashing part was the most important.
I added the rest of the fields to the TriangleModel class and created the base line of the histogram. Finally, some output I could look at! Yay!
I created the bottom line of the histogram. This allowed me to veriy that the left column and right column of the triangle were defined correctly.
I created one line above the base of the histogram. This allowed me to verify the center column of the triangle was defined correctly and the List of output strings was created and printed in reverse order.
I wrote the rest of the code. This is where my program crashed first. I forgot to adjust the left and right columns when they were equal. I found the problem quickly because I knew the problem was in the new code.
Then I was done. I spent some time cleaning up some of the code and making field names and method names more descriptive.
You can learn these techniques for writing code. Here's the last hint I can give you.
You're not writing code for a compiler. You're writing code so that other people, including yourself 3 months later, can read and easily understand the code.
Start with broad ideas, and dive into more and more detail as you move further down the code.
I hope this answer is helpful.
I've run into a bit of a conundrum in a personal Java project I've been working on. I want to print a two-dimensional array of Strings in the form of a table. Not the Strings by themselves, but with row and column labels as well (think Microsoft Excel). This is what I envision the finished product to be, with asterisks representing where the Strings should go.
| A | B | C | D | E | F | G |
----+---------+---------+---------+---------+---------+---------+---------+
1 | * | * | * | * | * | * | * |
----+---------+---------+---------+---------+---------+---------+---------+
2 | * | * | * | * | * | * | * |
----+---------+---------+---------+---------+---------+---------+---------+
3 | * | * | * | * | * | * | * |
----+---------+---------+---------+---------+---------+---------+---------+
4 | * | * | * | * | * | * | * |
----+---------+---------+---------+---------+---------+---------+---------+
5 | * | * | * | * | * | * | * |
----+---------+---------+---------+---------+---------+---------+---------+
6 | * | * | * | * | * | * | * |
----+---------+---------+---------+---------+---------+---------+---------+
7 | * | * | * | * | * | * | * |
----+---------+---------+---------+---------+---------+---------+---------+
8 | * | * | * | * | * | * | * |
----+---------+---------+---------+---------+---------+---------+---------+
9 | * | * | * | * | * | * | * |
----+---------+---------+---------+---------+---------+---------+---------+
10 | * | * | * | * | * | * | * |
----+---------+---------+---------+---------+---------+---------+---------+
I know that this will use a nested forward loop, and that the logical process would be to put the String values in the inner loop, like "example[i][j]" type format. I'm just so confused as to how I go about getting the design around the cells in the right format, limiting each String to 10 characters like how Excel limits their cell size when shrunken down. Do I use substring for that? Do I use printf to get the 10th row correctly spaced?
Any pointers are greatly appreciated, I've never been stumped quite like this before.
The first line should be easy enough, assuming you don't exceed 26 columns, i.e. column name is just A to Z.
The even lines are all a lead-in of ----+, followed by columnCount repeats of ---------+.
The odd lines (except first), are a lead-in of 999 |, where 999 is a row number, right-justified, with leading spaces. That can be done with printf() or String.format() with a format string of
"%3d |".
Following the lead-in are columnCount repeats of a string value, trimmed and center-aligned to 9 characters, followed by a |.
To center-align to 9 characters, do the following:
If length > 9, trim to 9 (yes, using substring()).
Otherwise, calculate spaces needed, i.e. spacesTotal = 9 - trimmedLength.
Calculate spaces on left: spaceBefore = spacesTotal / 2.
Calculate spaces on right: spaceAfter = spacesTotal - spaceBefore.
By doing it that way, an odd number of spaces such as 5, becomes 2 before and 3 after.
Now print spaceBefore spaces, the (trimmed) text value, then spaceAfter spaces, and a |.
public static void printStringGrid(String[][] array){
System.out.print(" |");
for (int i = 0; i < array[0].length; i++){
System.out.print(" ");
System.out.print((char)('A' + i));
System.out.print(" |");
}
System.out.println();
for (int i = 0; i < array.length; i++){
System.out.print("----+");
for (int j = 0; j < array[0].length; j++){
System.out.print("---------+");
}
System.out.println();
System.out.print(" " + (i + 1) + " |");
for (int j = 0; j < array[0].length; j++){
if (array[i][j].length() < 10){
int spaces = (9 - array[i][j].length()) / 2;
for (int k = 0; k < spaces; k++){
System.out.print(" ");
}
System.out.print(array[i][j]);
for (int k = 0; k < (9 - array[i][j].length()) - spaces; k++){
System.out.print(" ");
}
}
else{
System.out.print(array[i][j].substring(0, 9));
}
System.out.print("|");
}
System.out.println();
}
}
Ok, so I recently tried to create a java program in eclipse that basically takes an infinite amount of numbers that are 1-100, and stores them in an arraylist. Once this is done, it is supposed to print them out in a horizontal bar graph.
import java.util.ArrayList;
import java.util.Scanner;
/*
* 1-10
* 11-20
* 21-30
* 31-40
* 41-50
* 51-60
* 61-70
* 71-80
* 81-90
* 91-100
*
* Created by Peter browning, PBdeveloping, 2015
*/
public class Asterisks {
public static ArrayList<Integer> array = new ArrayList<Integer>();
public static Scanner reader = new Scanner(System.in);
public static void main(String[] args)
{
System.out.println("Enter some numbers, 1-100, 0 to stop.");
int input = reader.nextInt();
while (input != 0)
{
if ((input >= 1) && (input <= 100))
{
array.add(input);
input = reader.nextInt();
}
else
{
System.out.println("Error: Number must be 1-100");
input = reader.nextInt();
}
}
for (int i = 1; i <= 10; i++)
{
int firstNumber = ((i - 1) * 10) + 1;
int secondNumber = (i * 10);
int count = 0;
System.out.println(firstNumber + " - " + secondNumber + " |" );
for (int nInsideArray : array)
{
if ((nInsideArray >= firstNumber) && (nInsideArray <= secondNumber))
{
count++;
}
}
for (int x = 0; x < count; x++)
System.out.print("*");
System.out.println();
}
}
}
So the problem that I am having is, whenever I keep on trying to run this program, (lets use the user input "1", "21", then "0" as an example, it should print out:
1-10 | *
11-20 |
21-30 | *
31-40 |
41-50 |
51-60 |
61-70 |
71-80 |
81-90 |
91-100 |
but instead it prints out....
1 - 10 |
*
11 - 20 |
21 - 30 |
*
31 - 40 |
41 - 50 |
51 - 60 |
61 - 70 |
71 - 80 |
81 - 90 |
91 - 100 |
Note: the asterisks are not beside the |'s for some reason, any help would be appreciated. Also if you have a more efficient way to code something like this, I would love to hear your input. I usually learn alot on this website, so please help me with my issue, thanks!
This is because you are printing the pipe with a println(). Change that to print(). When you are done printing asterisks do a println for a new line.
I am working on a little program to calculate and draw a parabola. But I'm stuck at a little part in the program where I need to calculate the valuetable.
The quadratic function is the following one: y = a * (x - alpha)² + Beta.
So if I fill in the following values for this function: y = 2 * (x - 1)² + (-12). I need to become this value table:
x | -4.0 | -3.0 | -2.0 | -1.0 | 0.0 | 1.0 | 2.0 | 3.0 | 4.0 |
y | 38.0 | 20.0 | 6.0 | -4.0 |-10.0|-12.0|-10.0|-4.0 | 6.0 |
I managed to get the first row right, but the second row (the one that calculates te values), is totally wrong.
public double[][] berekenWaardentabel(int input[], int AANTALKOLOMMEN, double startWaarde) {
double[][] waarden = new double[RIJEN][AANTALKOLOMMEN];
System.out.println(waarden.length);
System.out.println(startWaarde + "\n");
for(int i = 0; i < RIJEN; i++) {
for(int j = 0; j < AANTALKOLOMMEN; j++) {
waarden[0][j] = startWaarde++; //value of first row (start from -4.0, counts upwards)
waarden[1][j] = input[0] * (Math.pow((startWaarde - input[1]), 2)) + input[2];
System.out.print(waarden[i][j] + " ");
}
System.out.println();
}
return waarden;
}
This is the output I get:
-4.0 -3.0 -2.0 -1.0 0.0 1.0 2.0 3.0 4.0 5.0 6.0
86.0 | 116.0 | 150.0 | 188.0 | 230.0 | 276.0 | 326.0 | 380.0 | 438.0 | 500.0 | 566.0
Anyone an idea how to solve this problem? Thanks!
You have to mistakes :
you want to fill two lines of your array (the 0-th (x) and the first(y)). Then you store the value of x in the first row and compute y(x+1) in the second row.
you need to fill your array with :
for (int j = 0; j < AANTALKOLOMMEN; j++) {
waarden[0][j] = startWaarde; // value of first row (start from -4.0, counts upwards)
waarden[1][j] = input[0] * (Math.pow((startWaarde - input[1]), 2)) + input[2];
startWaarde++;
}
Then you can display your values :
for (int i = 0; i < 2; i++) {
for (int j = 0; j < AANTALKOLOMMEN; j++) {
System.out.print(waarden[i][j] + " ");
}
System.out.println();
}
First error is this:
waarden[0][j] = startWaarde++; //value of first row (start from -4.0, counts upwards)
waarden[1][j] = input[0] * (Math.pow((startWaarde - input[1]), 2)) + input[2];
You put the value of startWaarde in waarden[0][j]. And then you increment it by one.
Then you calculate the value of the function for the updated startWaarde.
So your waarden[0][j] is, perhaps, 4.0, but you calculate the value waarden[1][j] for 5.0 rather than 4.0.
Your other problem is that you are looping with this line:
for(int i = 0; i < RIJEN; i++) {
I don't know what the value of RIJEN is. But your waarden array is only supposed to have two rows. Once you go through the loop again and again, startWaarde keeps growing and growing. Because you print the second row only after this loop iterates the second time, you see the wrong values.
You shouldn't have this loop at all.
| * |
| * |
| * |
| * |
| * |
| * |
| * |
| * |
| * |
| * |
| * |
| * |
|* |
I need to print something like the above ASCII plot for a Gambler's Ruin problem. Where the stake & goal are taken as args. The left most | represents 0 dollars, the right most | represents the goal and the * represents the cash on hand. My program is below:
public class RuinPath {
public static void main(String[] args) {
// TODO - Your solution
int stake = Integer.parseInt(args[0]); // gambler's stating bankroll
int goal = Integer.parseInt(args[1]); // gambler's desired bankroll
{
int i = 0;
if (i == 0) {
System.out.print("|");
i++;
while (i < stake) {
System.out.print(" ");
i++;
if (i == stake) {
System.out.print("*");
i++;
while (i > stake && i < goal) {
System.out.print(" ");
i++;
if (i == goal) {
System.out.print("|");
i = 0;
System.out.println();
{
if (Math.random() < 0.5) {
stake++; // win $1
} else {
stake--; // lose $1
}
if (stake == 1 || stake == goal - 1);
break;
}
}
}
}
}
}
}
}
}
what this program prints though is:
| * |
* |
* |
* |
* |
* |
* |
* |
* |
* |
* |
* |
* |
* |
*
Why does my program not loop so that i can get the left most | to appear to represent 0 dollars all the way through? I have it so i = 0; at the end of the loop so that when it goes back around it should re-loop until the stake is 1 or less than the goal. Instead it re-loops from the middle of the program.
Your logic is a little too complicated. Also, your indentation will make any sort of debugging extremely difficult.
Just take it one step at a time:
public class RuinPath {
public static void main(String[] args) {
int stake = Integer.parseInt(args[0]); // Starting bankroll
int goal = Integer.parseInt(args[1]); // Desired bankroll
while (stake > 0 && stake < goal) {
System.out.print("|");
// Print out the spaces. Using a for loop and
// printing a "*" if the counter variable
// is equal to stake is good way to do it.
// Flip a coin and increment/decrement the stake
System.out.print("|\n");
}
}
}
Here is a broken out solution that might be easier to reason about:
import java.io.PrintStream;
public class SO {
private static int gambleWithCaution(int stake) {
if (Math.random() < 0.5) {
return stake+1; // win $1
} else {
return stake-1; // lose $1
}
}
private static void renderStanding(int stake, int goal) {
System.out.print('|');
for(int dollar = 1; dollar< goal; dollar++) {
if(dollar == stake) {
System.out.print('*');
} else {
System.out.print(' ');
}
}
System.out.println('|');
}
public static void main(String ... args) {
int stake = Integer.parseInt(args[0]); // gambler's stating bankroll
int goal = Integer.parseInt(args[1]); // gambler's desired bankroll
while(stake > 0 && stake < goal) {
renderStanding(stake, goal);
stake = gambleWithCaution(stake);
}
System.out.println((stake > goal) ? "You Won!" : "You Lost");
}
}
With the values 3 and 5 you get this output:
| * |
| * |
|* |
| * |
| * |
| *|
| * |
| *|
You Won!
Now that this is seperated out you can have some fun with it like creating a gamble function like this:
private static int gambleWithReclessAbandon(int stake, int goal, double abandon) {
int onTheLine = (int)(Math.random() * (int)(stake * abandon));
if(stake < (0.5)*goal) {
//If you are at less than 50% of your goal then just put it all on the line
//and let it ride :)
onTheLine = stake;
}
if (Math.random() < 0.5) {
return stake+onTheLine; // win $
} else {
return stake-onTheLine; // lose $
}
}
Which can be invoked like this:
//Gamble up to 80% of your current stake
stake = gambleWithReclessAbandon(stake, goal, 0.80);
With the same two values this is what I saw on my first pass (I was sooo close :)):
| * |
| * |
| *|
| * |
| *|
You Lost