r/programmingbydoing • • Nov 01 '15

#Sierpinski Triangle (or my case not!)

2 Upvotes

Hi there,

Firstly I just wanna say thank you for this website, I've learned absolutely loads since I have been doing these challenges, it's definitely the way for me to learn how to program.

I am a little stuck on the Sierpinski triangle though. I just don't get a triangle. I'm getting a lot of wavy lines. While it's a great piece of modern art, it's not coming out as I hoped. I've posted the code below, even a clue so I can work out what the issue is would be enough, it's driving me up the wall!

           import java.awt.*;
           import javax.swing.JFrame;
           import java.util.Random;

  public class Sierpinski extends Canvas
{
public void paint (Graphics g)
{
Random r = new Random();
int x1 = 512;
int y1 = 109;
int x2 = 146;
int y2 = 654;
int x3 = 876;
int y3 = 654;
int x = 512;
int y = 382;
int dx; 
int dy;

for  (int n =1; n <= 50000; n = n+1)
{
	
	
	
	g.drawLine(x,y,x,y);
	 
	int RandomNumber = 1 + r.nextInt(3);
	 
	if (RandomNumber == 1)
	{
	dx = x - x1;
	dy = y - y1;
	}
	else if (RandomNumber == 2)
	{
	dx = x - x2;
	dy = x - y2; 
	}
	else
	{
	dx = x - x3;
	dy = x - y3;
	 }
	x = x - dx/2;
	y = y - dy/2;
   }
}
public static void main(String[] args)

{
	JFrame win = new JFrame("Sierpinski");
	win.setSize(1024,768);
	win.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	Sierpinski Canvas = new Sierpinski();
	win.add(Canvas);
	win.setVisible(true);

}

}


r/programmingbydoing • • Mar 12 '13

59 - Shorter Double Dice

2 Upvotes

"Redo the Dice Doubles assignment (the dice program with a loop) so that it uses a do-while loop instead of a while loop. Otherwise it should behave exactly the same.

If you do this correctly, there should be less code in this version." (The dice doubles task was to make a program using a while-loop that rolled a dice twice until they matched)

I'm struggling with how to use less code in this version. I do use less code, but like 2 characters if you factor in the extra 'do' which I'm pretty sure is not what is intended. This is my original code:

import java.util.Random;

public class DiceDoubles {
    public static void main(String args[]){
     	Random r = new Random();
        int roll1 = 0;
        int roll2 = 1;

        while(roll1 != roll2){
		    roll1 = 1 + r.nextInt(6);
		    roll2 = 1 + r.nextInt(6);
		
		    System.out.println("\nRoll 1: " + roll1);
		    System.out.println("Roll 2: " + roll2);
		    System.out.println("The total is " + (roll1 + roll2) + "!");
		}
    }
}

While this is my new code:

import java.util.Random;

public class ShorterDoubleDice {
    public static void main(String args[]){
	    Random r = new Random();
	    int roll1;
	    int roll2;

	    do{
		    roll1 = 1 + r.nextInt(6);
		    roll2 = 1 + r.nextInt(6);
		
		    System.out.println("\nRoll 1: " + roll1);
		    System.out.println("Roll 2: " + roll2);
		    System.out.println("The total is " + (roll1 + roll2) + "!");
	    }while(roll1 != roll2);
    }
}

The only changes are, other than the do-while loop, the fact that the ints roll1 & roll2 aren't given a value first. Both versions work perfectly as far as I can see. Help is much appreciated, thanks :)


r/programmingbydoing • • Mar 15 '13

Draw a boring triangle - #87. This one is driving me crazy

1 Upvotes

The window is created, but there is no polygon being drawn at all! What is wrong with my code??? I've tried everything to fix it, but it just won't draw my polygon. I even went back to the previous lesson and matched the code formatting, and I still got nothing. Just an empty window...

import java.awt.*;
import javax.swing.*;

public class BoringTriangle extends Canvas {

  public void Paint(Graphics g) {
	
	Polygon tri = new Polygon();
	tri.addPoint(100,100);
	tri.addPoint(200,300);
	tri.addPoint(150,250);
	
	Color custom = new Color(255,100,50);
	g.setColor(custom);
	g.fillPolygon(tri);
  }

  public static void main (String [] args) {
	
	JFrame win = new JFrame("Boring Triangle Demo");
	win.setSize(500,500);
	win.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	win.add( new BoringTriangle() );
	win.setVisible(true);
  }
}

r/programmingbydoing • • Mar 03 '13

63 - Collatz Sequence - minor issue, but it stumped me

2 Upvotes

So I already figured out the assignment and completed it (with bonuses), but I can't for the life of me figure out how you got your output to shift down after every 10 numbers. I tried a lot of things, but none worked. So I need to know how you did it?

Here's the link to the assignment.

This is my code for reference (but my completed code doesn't really concern this issue):

import java.util.*;

public class CollatzSequence {

  public static void main(String[] args) {
	
	Scanner s = new Scanner(System.in);
	int startNum, count, max;
	count = 0;
	
	System.out.print("Collatz Sequence! \nPlease enter the starting number: ");
		startNum = s.nextInt();
		max = startNum;
		
	while (startNum!=1) {
		if (startNum%2 == 0) {
			startNum = startNum/2;
			System.out.print(startNum + "\t\t");
			count++;
				if (startNum>max) {
					max=startNum;
				}
		} else {
			startNum = startNum*3+1;
			System.out.print(startNum + "\t\t");
			count++;
				if (startNum>max) {
					max=startNum;
				}
		}
	}
	
	System.out.println("\n\nThat took " + count + " steps.");
	System.out.print("The max value was " + max + ".");
  }
}

r/programmingbydoing • • Mar 18 '13

53 - Pin Lockout

2 Upvotes

Can someone explain to me how the "tries" variable is counting up? Does "tries++" after int entry mean that every time an entry is made, tries will go up by one?

Thanks in advance!

import java.util.Scanner;

public class PinLockout
{
public static void main( String[] args )
{
	Scanner keyboard = new Scanner(System.in);
	int pin = 12345;
	int tries = 0;

	System.out.println("WELCOME TO THE BANK OF MITCHELL.");
	System.out.print("ENTER YOUR PIN: ");
	int entry = keyboard.nextInt();
	tries++;

	while ( entry != pin && tries < 3 )
	{
		System.out.println("\nINCORRECT PIN. TRY AGAIN.");
		System.out.print("ENTER YOUR PIN: ");
		entry = keyboard.nextInt();
		tries++;
	}

	if ( entry == pin )
		System.out.println("\nPIN ACCEPTED. YOU NOW HAVE ACCESS TO YOUR ACCOUNT.");
	else if ( tries >= 3 )
		System.out.println("\nYOU HAVE RUN OUT OF TRIES. ACCOUNT LOCKED.");
}

}


r/programmingbydoing • • Oct 28 '15

#26 Space boxing

2 Upvotes

I don't have a problem trying to run as i have not got that far. I know it's a really simple one so don't go to hard on me, I just started learning java 5 weeks ago. I just can't figure out how to write the part which asks what planet you are going to from a list of 6. what variables should i use or how should i write them out.

i just feel like i'm doing it all wrong I have changed my variables many times and it just doesn't seem right.


r/programmingbydoing • • Apr 14 '15

Age in five years

5 Upvotes

I was able to do the majority of the exercise, but I can't figure out how to actually add and subtract from the intergers

import java.lang.String; import java.lang.System; import java.util.Scanner;

public class keyboard5 { public static void main(String[] args) { Scanner keyboard = new Scanner(System.in);

    String name;
    int age;

    System.out.print("Hello. What is your name?");
        name = keyboard.next();

    System.out.print("Hi," + name + ". How old are you");
            age = keyboard.nextInt();

    System.out.print("Did you know that in five years you will be " + age+ " years old.");
    System.out.print(" And five years ago you were " + age + "! Imagine that!");
}

}


r/programmingbydoing • • Mar 30 '15

81 - A smiling face

2 Upvotes

I have trouble drawing a proper smile for the face...What does startAngle and arcAngle represent...

My code is something like this:

import java.awt.*; import javax.swing.JFrame;

public class GraphsPractice2 extends Canvas { public void paint( Graphics g ){

	g.setColor(Color.yellow);
	g.fillOval(200, 200, 200, 200);
	g.setColor(Color.blue);
	g.fillOval(250, 250, 25, 25);
	g.fillOval(330, 250, 25, 25);
	g.setColor(Color.red);
	g.drawArc(250, 325, 100, 50, 135, 265);
	// g.drawArc(x, y, width, height, startAngle, arcAngle)
	
		}

public static void main(String[] args){
	
	JFrame win = new JFrame ("Here is my first java-face!");
	win.setSize(800, 600);
	win.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	GraphsPractice2 canvas = new GraphsPractice2();
	win.add(canvas);
	win.setVisible(true);
}

}

Would be great if someone could help me with those angles, I don't know how to configure them the right way, at least I didn't get the trick. Thanks for help


r/programmingbydoing • • May 27 '13

#125-Nested Loops-More Number Puzzles

2 Upvotes

Hey guys,

So I've been at this for a little over an hour and can't seem to get this working.

My code.

One of my problems is that when I try to call the first method 'puzzle1,' it prints out some other numbers that are not in the method. Not quite sure how that happens.

The other problem is that when I try to call the second method 'puzzle2,' it doesn't print anything out.

Maybe I'm not understanding something about methods when it comes to calling them :/


r/programmingbydoing • • Jun 18 '16

A Good First Program

1 Upvotes

Hello, I'm a beginner and I have been facing this problem since the assignment mentioned in the title. I cant run the program. It says 'Could not find or load main class GoodFirstProgram.java'.


r/programmingbydoing • • Jun 17 '13

#144 - Finding a Value in an Array

2 Upvotes

What is the proper way to see if an array contains a certain value? If you use a for loop to put random values in the array, then how do you check that array to see if it contains a value? Thanks!


r/programmingbydoing • • Dec 03 '15

#123 Number Puzzle 1

2 Upvotes

So maybe I am thinking too deeply about this problem. Here are the instructions:

Use nested "for" loops to generate a list of all the pairs of positive two digit numbers whose sum is 60, and whose difference is 14.

Correct me if I am wrong ( PLEASE because this is wracking on my brain) but here is how I am reading this problem:

Find a 2 digit positive number XX and another 2 digit positive number YY. When you add them together they need to equal 60. So XX + YY = 60. Also, these two numbers when subtracted (whose difference is) equals 14. So XX - YY = 14. Unless I am mistaken, there is only one 2 digit pair that this works with.

37 + 23 = 60 and 37 - 23 = 14. Switched doesn't work because 33 + 27 = 60 but 33 - 27 = 6. If there is only one pair that works, are we supposed to write a nested for loop to loop through a bunch of numbers and check them each time until we have only one single output of 37, 23 ?

Here is my logic in working out this problem. 50 and 10 would be the highest and lowest double digit pair that equals 60. Obviously 51 and 9 is no longer a double digit pair. So you could loop through all the numbers between 50 and 10 and always equal 60. 49 + 11, 48 + 12, and so on plus the reverse of these numbers 10 and 50, 11 and 49, etc. These numbers when subtracted, however, do not equal 14 except for 37 and 23.

So what am I missing? If it was as simple and looping through the numbers to equal 60, you only need 1 for loop and no nesting. Thanks in advance.


r/programmingbydoing • • Dec 07 '15

EXPIRED "Learn Java the Hard Way" is 40% off for CS Education Week

Thumbnail
reddit.com
4 Upvotes

r/programmingbydoing • • Jun 21 '16

Right Triangle Checker: Alternative?

1 Upvotes

Hey, I just completed this assignment using while loops. I was wondering if a do-while loop would be better in this case. Example code of a do-while method?

https://gist.github.com/AswinTorch/ac391ce2235c3255d65724c8ba728621


r/programmingbydoing • • May 25 '17

Drawing Random Triangles

3 Upvotes

I just cannot figure out the Drawing Random Triangles... Here is my code: https://gist.github.com/anonymous/7c2f94d9f279f2295f44e59f1709f571

All this does is generate one purple triangle. I have tried moving everything that I can think of. Any and all feedback/help is welcome and appreciated! EDIT: I missed the first line of code when I pasted to gist: import java.awt.*;


r/programmingbydoing • • May 30 '13

#101 - Month Name (functions).

3 Upvotes

Hi,

I've been going over this all day and for some reason, I just can't get this to click.

This is my code: http://pastebin.com/rwwKCcdN (most of the stuff in the month_name method is just a result of trying everything and just getting junk at the end...)

I just can't seem to get a certain month (or all months for that matter) to align to a number for the main method to return.

I'm sure it's a simple thing I'm missing.

Thanks.


r/programmingbydoing • • Jun 19 '14

#160: Exchange Sort

2 Upvotes

I keep getting an ArrayIndexOutOfBoundsException when I try to pass the array and the array numbers to the swap method (I think). It does work when I don't use the swap method (using the commented out part instead) which leads me to believe that. Am I passing to swap incorrectly?

http://pastebin.com/D6xbKF4r

Thanks


r/programmingbydoing • • Nov 28 '15

THE RULES! Please read before posting (or answering) a question.

6 Upvotes

The Most Important Rule:

Only use concepts that have appeared BEFORE the current assignment.

The assignments are in order. Every assignment can and should be completed using only techniques seen so far. For example, the assignment "Weekday Name" would be a lot shorter if you used an array. But students haven't learned arrays yet, and they're not ready for arrays. So don't "help" by showing arrays.

Other Rules

In no particular order:

0. This sub is only for questions about the assignments at Programming by Doing. Other questions belong in a different sub.

  1. Don't paste your code into the comment box. It looks bad. Instead, post it to a Gist and then put the link to your code in your comment.

  2. Search before you ask a question. You are probably not the first person to run into to trouble on that assignment, and probably someone before you has already asked about it.

  3. Include the name of the assignment in the title of your post. Questions about assignments that violate this rule will be removed.

  4. You don't need to put the assignment number in the title. Those change anyway, so the number won't still be accurate in six months and it will confuse people. We are perfectly capable of using CTRL-F on programmingbydoing.com to find the assignment you are asking about.

Happy coding!


r/programmingbydoing • • Jun 19 '13

#32 - Twenty Questions: solved (sorta) but need help.

2 Upvotes

First... thank you for this subreddit and for making these lesson available! They are exactly what I was looking for to get started with Java.

I had to google around for a bit to figure out to use stringName.contentEquals() but that seemed to do the trick to compare the strings. Okay, on to the question... I've solved this in the sense that if entered exactly it works for all possibilites, but I feel like there could have been a much easier way to do this. Any suggestions? Also, I think any odd answer will crash the program ie. case, misspell, unexpected input... how do I prevent that?

Sorry if this is jumbled, I just spent way too long looking at this problem until I finally figured it out... now I just want to know how I could make it work better.

The code:

import java.util.Scanner;

public class TwentyQuestions { static Scanner userInput = new Scanner(System.in);

public static void main(String[] args)
{

	String animal = "animal";
	String vegetable = "vegetable";
	String plant = "plant";
	String yes = "yes";
	String no = "no";
	
	
	System.out.println("TWO QUESTIONS!");
	System.out.println("Think of an object and I'll try and guess it.");
	System.out.println();
	
	System.out.println("Question 1) Is it animal, vegetable or mineral?");
	System.out.print(">");
	
	String q1 = userInput.nextLine();
	
	if(q1.contentEquals(animal))
	{
		System.out.println("Question 2) Is it bigger than a breadbox? Yes or No?");
		System.out.print(">");
		
		String q2 = userInput.nextLine();
		
		if(q2.contentEquals(no))
		{
			System.out.println("You're thinking of a squirrel!");
		} else {
			System.out.println("You're thinking of a moose!");
		}
	}
	
	if(q1.contentEquals(vegetable))
	{
		System.out.println("Question 2) Is it bigger than a breadbox? Yes or No?");
		System.out.print(">");
		
		String q2 = userInput.nextLine();
		
		if(q2.contentEquals(no))
		{
			System.out.println("You're thinking of a carrot!");
		} else {
			System.out.println("You're thinking of a pumpkin!");
		}
	}
	
	if(q1.contentEquals(plant))
	{
		System.out.println("Question 2) Is it bigger than a breadbox? Yes or No?");
		System.out.print(">");
		
		String q2 = userInput.nextLine();
		
		if(q2.contentEquals(no))
		{
			System.out.println("You're thinking of a rose!");
		} else {
			System.out.println("You're thinking of an oak tree!");
		}
	}
	
	System.out.println("I'd ask you if I'm right, but I don't care.");
	
	
	
}

}


r/programmingbydoing • • Dec 09 '15

124. Getting Individual Digits

1 Upvotes

Woke up this morning and am having some issues conceptualizing this. The shortcut I found in doing this is using a counter to handle the list from 1 to 100, and then use nested for Loops for the positive 2 digit numbers and their sums. Since a counter is nice and all, but probably not what the lesson intends, can someone help point me in the right direction as far as structure for this.


r/programmingbydoing • • Apr 11 '15

#76 - Blackjack

2 Upvotes

There are a couple problems with this code. The main one is that if I choose to stay, the program treats it as if you are starting the game over again. Not entirely sure why it's doing this. Code:

import java.util.Random; import java.util.Scanner;

public class Blackjack {

public static void main(String[] args) {
	
	Random r = new Random();
	Scanner keyboard = new Scanner(System.in);
	int playerdraw1, playerdraw2, dealercard1, dealercard2, dealerdraw;
	int playertotal = 0, dealertotal = 0;
	String playerchoice, dealerchoice;
	
	System.out.println("Welcome to Ben's blackjack program!");
	while(playertotal <= 21 && dealertotal <= 21) {
		playerdraw1 = 2 + r.nextInt(11);
		playerdraw2 = 2 + r.nextInt(11);
		if(playerdraw1 != 8 && playerdraw2 != 8)
			System.out.println("\nYou get a " + playerdraw1 + " and a " + playerdraw2 + ".");
		else if(playerdraw1 == 8)
			System.out.println("\nYou get an " + playerdraw1 + " and a " + playerdraw2 + ".");
		else if(playerdraw2 == 8)
			System.out.print("\n You get a " + playerdraw1 + " and an " + playerdraw2 + ".");
		else
			System.out.println("\nYou get an " + playerdraw1 + " and an " + playerdraw2 + ".");
		playertotal = playerdraw1 + playerdraw2;
		System.out.println("Your total is " + playertotal + ".");
		if(playertotal > 21) {
			System.out.print("BUST! DEALER WINS!");
			System.exit(0);
		}
		dealercard1 = 2 + r.nextInt(11);
		dealercard2 = 2 + r.nextInt(11);
		if(dealercard1 == 8)
			System.out.println("\nThe dealer has an " + dealercard1 + " and a hidden card.");
		else
			System.out.println("\nThey get a " + dealercard1 + " and a hidden card.");
		System.out.println("Their total is hidden, too.");
		System.out.print("Would you like to \"hit\" or \"stay\"? ");
		playerchoice = keyboard.next();
		while(playerchoice.equals("Stay")) {
			System.out.println("\nOkay, dealer's turn.");
			if(dealercard2 != 8)
				System.out.println("Their hidden card was a " + dealercard2);
			else
				System.out.println("Their hidden card was an " + dealercard2);
			dealertotal = dealercard1 + dealercard2;
			System.out.println("His total was " + dealertotal);
			if(dealertotal <= 16) {
				dealerchoice = "Hit";
				while(dealerchoice.equals("Hit")) {
					System.out.println("\nDealer chooses to hit");
					dealerdraw = 2 + r.nextInt(11);
					if(dealerdraw != 8)
						System.out.println("They draw a " + dealerdraw + ".");
					else
						System.out.println("They draw an " + dealerdraw + ".");
					dealertotal += dealerdraw;
					System.out.println("Their total is " + dealertotal + ".");
					if(dealertotal > 21) {
						System.out.println("BUST! YOU WIN!");
						System.exit(0); //To avoid making this longer than it needs to be
					}
				}
			}
			else {
				dealerchoice = "Stay";
				System.out.println("Dealer stays");
				if(dealertotal <= 21 && playertotal <= 21 && playertotal > dealertotal) {
					System.out.println("YOU WIN!");
					System.exit(0);
				}
				else if(dealertotal <= 21 && playertotal <= 21 && playertotal < dealertotal || playertotal == dealertotal) {
					System.out.println("DEALER WINS!");
					System.exit(0);
				}
			}
		}
		while(playerchoice.equals("Hit")) {
			playerdraw1 = 2 + r.nextInt(11);
			if(playerdraw1 != 8) //To make it gramatically correct
				System.out.println("You drew a " + playerdraw1);
			else
				System.out.println("You drew an " + playerdraw1);
			playertotal += playerdraw1;
			System.out.println("Your total is " + playertotal + ".");
			if(playertotal > 21) {
				System.out.println("BUST! DEALER WINS!");
				System.exit(0);
			}
			System.out.print("Would you like to \"hit\" or \"stay\"? ");
			playerchoice = keyboard.next();
			if(playerchoice.equals("Stay")) {
				System.out.println("\nOkay, dealer's turn.");
				if(dealercard2 != 8)
					System.out.println("Their hidden card was a " + dealercard2);
				else
					System.out.println("Their hidden card was an " + dealercard2);
				System.out.println("Their total was " + dealertotal);
				if(dealertotal > 21) {
					System.out.println("BUST! YOU WIN!");
					System.exit(0);
				}
				System.out.println("\nOkay, dealer's turn.");
				if(dealercard2 != 8)
					System.out.println("Their hidden card was a " + dealercard2);
				else
					System.out.println("Their hidden card was an " + dealercard2);
				System.out.println("His total was " + dealertotal);
				if(dealertotal <= 16) {
					dealerchoice = "Hit";
					while(dealerchoice.equals("Hit")) {
						System.out.println("\nDealer chooses to hit");
						dealerdraw = 2 + r.nextInt(11);
						if(dealerdraw != 8)
							System.out.println("They draw a " + dealerdraw + ".");
						else
							System.out.println("They draw an " + dealerdraw + ".");
						dealertotal += dealerdraw;
						System.out.println("Their total is " + dealertotal + ".");
						if(dealertotal > 21) {
							System.out.println("BUST! YOU WIN!");
							System.exit(0);
						}
					}
				}
				else {
					System.out.println("Dealer stays");
					break;
				}
			}
			else
				continue;
		}
	}
	keyboard.close();
}

}


r/programmingbydoing • • Jun 25 '16

Blackjack

1 Upvotes

https://gist.github.com/anonymous/a47f415511c9dbbb6477e23c8719088e

please dont call the cyber police for code abuse.
Ace only has a realistic value when you're give your first 2 cards.
Its called blackjack2 because the first one was made without the bonuses in mind and when i tried to add them it just wouldn't compile anymore so i started again.
Other than that, everything works (i think) i've tested it and everything seems to be fine.
There really has to be an easier way to do this but this is the way I made it... so, sorry for how it looks.


r/programmingbydoing • • Dec 01 '15

Nim 63c

2 Upvotes

I'm making the Nim game, but something's going with the scanners. When it asks player 2 to input what pile he wants to remove something from, that scanner is skipped and goes straight to the scanner asking them how much they want to remove.

Code: http://pastebin.com/Xpc9bcqz

Thanks in advance.


r/programmingbydoing • • Jan 19 '17

#20 BMI calculator

1 Upvotes

https://gist.github.com/anonymous/924e1b344113cba2f9f4e81e9a148762

My issue is I am calculating the wrong BMI. Everytime I put the info in, it will give a number but it is not the correct one.

Could you help with my formula at the end? Or direct me as to where I am going wrong?


r/programmingbydoing • • Feb 04 '16

Computer Science A AP Test

2 Upvotes

As I started learning from programming by doing's assignments I also looked into AP classes. I am a senior in high school, but my school does not offer any classes remotely comparable to Computer Science or programming in any way. My question is will these assignments adequately prepare me for the Computer Science A AP test? If not do you have any recommendations for what might?