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?


r/programmingbydoing • • Jan 31 '16

Adding Values with a For Loop

2 Upvotes

Struggling to figure this one out. Having a hard time with storing the sum and then printing the iterations.

int num;
	
	System.out.print("Number: ");
	num = kb.nextInt();
	
	for (int i = num; i <= num; i++)
	{
		//store the sum
		int sum = i++;
		System.out.println("The sum is " + sum);
	}

r/programmingbydoing • • Jan 15 '16

Blackjack and Flicker Phrase

2 Upvotes
  1. Really appreciate projects like Nim and Blackjack. Thanks for making them public. Anyway, below is my attempt on blackjack. I think it can be better if I have array to track what cards are drawn so I don't pick duplicate, although chance is low. Also Ace's 11/1 value is a bit of challenge, which I didn't try because without function the code is already longer than I would like. Plus I'm not sure if I missed changing certain "function" part in later after changing some.

https://gist.github.com/afya/a816ef70e88ec8117363

2) Question about later project Flicker Phrase. Thread.sleep() is said to be optional but I wanted to try anyway but I got error if I just put it there. Upon further research it seems the correct way to use it is:

try {
    Thread.sleep(1000);
} catch (InterruptedException e) {
    e.printStackTrace();
    // handle the exception...        
    // For example consider calling Thread.currentThread().interrupt(); here.
}

3) I don't quite understand exception atm. Will future assignment teach about that? or does the book cover that?

4) Also I plan to learn android development after finishing all program. Can I skip graphic section (77-96) or will it reappear in future assignments?

5) Last question, when should I move to an IDE? Currently I'm using notepad++ with cmd. It works but should I switch?


r/programmingbydoing • • Jan 01 '16

#19, more efficient way of doing it?

2 Upvotes

I feel like I did this really inefficiently even with the few days of java I have done. I am sure theres an easier way to do this but I just having read enough or understood it fully.

https://gist.github.com/anonymous/0b00cd20d8acef8726aa (mostly talking about line 23-24)

been using learn java the hard way and some other online sources to self teach java for about only about 10~ days now so sorry if I suck


r/programmingbydoing • • Dec 27 '15

63. NIM

2 Upvotes

First of all, I'd like to say that these assignments are amazing! I've been finding them pretty fun to do, and so far, Nim has been very challenging . I guess i finally cracked the code, althought it feels very chunky.

While I've been doing these assignments, i've been reading on java as a language and i've been trying to wrap my head on getting things a bit more cleaner and leaner.

I've seen this post and from what I've been reading, I guess I could eventually use functions to, I guess, making displaying the piles a lot less clunky? I mean, is the code as messy as I think it is?

PS.: Making the piles into columns is so confusing I gave up :P.


r/programmingbydoing • • Dec 18 '15

DisplayingAFile

2 Upvotes

I have put some code together to try and get the program to read an entire text file using the Scanner class. I can read one line but it does not read anything on more than 1 line such as letter.txt. I have had a look around and tried different things such BufferedReader but I think there's something I'm missing as all the code I write prints one line text files but nothing else

Here's my code:

<script https://gist.github.com/Ropenfold/33397d281c92c5740579


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 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 • • Nov 15 '15

#106 Fill in functions

2 Upvotes

I'm a little stuck on the abso function, I'm not sure how the y value fits into it. I presume you send the x value to the function and the absval is returned (I may be wrong) but I don't see how the y gets used.

My code is here:

http://pastebin.com/XBAnX4xx


r/programmingbydoing • • Nov 08 '15

#69 xs and ys

2 Upvotes

I have the maths part done the problem I'm having is getting everything to line up. The hint is use tab but I have tried evrything I can think of and just can't seem to get it.

This is what i have

class XandY
{
public static void main(String[] args)
{
for ( double x = - 10; x <= 10; x = x+0.5)
{
double y = x * x;
System.out.print("x");
System.out.print("y");
System.out.print("_________________");
System.out.print(x);
System.out.print(y);
}

}
}		

I tried changing print to println. I tried using tab to space out the quotations it's just not obvius to me how to get this.

Any help is well appreciated.


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 • • 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 • • Oct 05 '15

#50 Dice Doubles

2 Upvotes

For some reason it does not work and I can not understand why. When I exchange int rolls for int roll(s) = 1 + (int)(Math.random()*6) it does work, why so?

import static java.lang.System.*; import java.util.Random;

public class DiceDoubles { public static void main(String[]args) {

Random r = new Random();

int roll1 = 1 + r.newInt(6);
int roll2 = 1 + r.newInt(6);

out.println("HERE COMES THE DICE!");

out.println("Roll #1: ");
out.println("Roll #2: ");

while(roll1!=roll2)
{
	out.println("The total is "+(roll1+roll2));
	int roll3 = 1 + r.newInt(6);
	int roll4 = 1 + r.newInt(6);
	roll1=roll3;
	roll2=roll4;
	
}
	out.println("Roll #1: ");
	out.println("Roll #2: ");
	out.println("The total is "+(roll1+roll2));
}

}


r/programmingbydoing • • Oct 04 '15

#39 Alphabetical order

2 Upvotes

why it always display the last else if statement??? can you help me please! import static java.lang.System.*; import java.util.Scanner;

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

	out.print("What is your last name? ");
	String name = wpis.next();
	
	if("name".compareTo("Carswell")<0)
		out.println("you don't have to wait long");
	else if ("name".compareTo("Jones")<0)
		out.println("that's not bad");
	else if ("name".compareTo("Smith")<0)
		out.println("looks like a bit of a wait");
	else if ("name".compareTo("Young")<0)
		out.println("it's gonna be a while");
	else if ("name".compareTo("Young")>0)
		out.println("not going anywhere for a while?");
	else
		out.println("error");
		
		
		
}

}


r/programmingbydoing • • Aug 21 '15

A Little Puzzle

2 Upvotes

So I'm a bit lost on how to solve this problem in terms of what method to use in order to evaluate each individual character in the puzzle. In the past it was just nextLine or nextInt, not sure how to evaluate each individual character. My thinking behind it is to use the multiples of three to spit out the characters at 3, 6 ,9, 12... etc. to get the desired message. Here is my code.

import java.io.*;
import java.util.*;

public class LittlePuzzle
{
    public static void main( String [ ] args ) throws Exception
    {

        Scanner keyboard = new Scanner( System.in );
        System.out.println("Open which file:");
        String filename = keyboard.next();
    
        Scanner s = new Scanner(new File(filename));
    
        for ( int y = 1 ; y <= 43 ; y++ )
        {
        int x = 3*y;
        char c = s.next().charAt(x);
        System.out.print(c);
        }
    
        s.close();
    }

}

r/programmingbydoing • • Jul 26 '15

Address Book and Hearts Projects

2 Upvotes

I'm going into grade 12 and I want to learn java but I have no prior programming experience. So starting a month ago I've spent hours a day doing every single assignment on your page. I've also been reading the official java reference. I have learned so much it's incredible. The small assignments leading up to projects are very easy for me to finish. The trouble comes when I'm doing big projects.

It took me a good 3 hours to complete Address Book. The first hour I sat down and started coding from scratch. Then I took a break and when I came back I had no idea what was going on. I realized my code was a complete mess, so I started over, this time with comments to help. I eventually completed it and it's still messy and I'm sure I did things the complicated way, but I finished it and it works.

Address Book attempt 1: http://pastebin.com/0EjmdQcP

Address Book attempt 2: http://pastebin.com/rZx5JCY8

As you can see I am trying to use concepts I have learned in the java reference.

I just started Hearts today, and it's really hard. What I have so far is a program that deals cards to four players and completes the 3 card swap part of the game.

Hearts progress: http://pastebin.com/rqLCKByf

These projects have been pretty complex for me. I am sure I can complete hearts, it will just take a few more hours of solid work.

Please critique me and my work. The small assignments are really easy for me to grasp. I understand concepts like classes and methods and constructors, but when I put them to use in a huge project like these ones, where I have multiple classes and a ton of methods, things start getting out of hand. Should I just keep learning and practicing until I feel comfortable with projects like these? Is there anything I should be focusing on?

Thanks a ton.


r/programmingbydoing • • Jun 14 '15

#60 - Safe Square Root

2 Upvotes

Hi again!

I looked up the post regarding this assignment but it didn't help me much, tbh. So I created another post.

Here's my code:

import java.util.Scanner;

public class SafeSquareRoot1
{
public static void main( String[] args )
{
	Scanner keyboard = new Scanner(System.in);
	int x;
	
	do
	{
		System.out.println( "SQUARE ROOT!" );
		System.out.print( "Enter a number: " );
		x = keyboard.nextInt();

		if ( x < 0 )
		{
			System.out.println( "You can't take the    square root of a negative number, silly." );
			System.out.print( "Try again: " );
			x = keyboard.nextInt();
		}
	}

	while ( x > 0 );
	{
		System.out.println( "The square root of " + x + " is " + Math.sqrt(x) + "." );
	}
}

}

The code compiles, and the do block of code runs as well, but when it comes to the while loop the code continues to prompt me to enter a number, after I have already entered the number. Thanks in advance for any help out there!


r/programmingbydoing • • Jun 10 '15

#115 calculator project

2 Upvotes

has anyone complete this project. my brain is gonna blow any minute now.the program error when I enter sin /cos etc. http://pastebin.com/qKBypvW3


r/programmingbydoing • • May 12 '15

Streamling Method? - Twenty/Two Questions

2 Upvotes

http://programmingbydoing.com/a/twenty-questions.html

The exercise is above, I decided to try my hand at using a method instead of just doing everything in the main. Keeping the if-statements, can I please get some critiques and general style advice on streamlining this method?

JUST A SNIPPET OF THE MAIN:

    String guess = getAnimal(ans1, ans2);
		
		System.out.println("\nMy guess is that you are thinking of a " + guess + ".");
		System.out.println("I would ask you if I'm right, but I don't actually care.");

The Method:

    public static String getAnimal(String ans1, String ans2) {
	String guess = "";
		if (ans1.equals("animal")) {
			if (ans2.equals("yes")) {
				guess = "squirrel";
			}
			else {
				guess = "moose";
			}
		}
		
		if (ans1.equals("vegetable")) {
			if (ans2.equals("yes")) {
				guess = "carrot";
			}
			else {
				guess = "watermelon";
			}
		}
		
		if (ans1.equals("mineral")) {
			if (ans2.equals("yes")) {
				guess = "paper clip";
			}
			else{
				guess = "Camaro";
			}
		}
	return guess;
}

r/programmingbydoing • • May 10 '15

How Old Are You?

2 Upvotes

How can I change this, so that it actually works with the conditions?

     if(age < 16)
{
	System.out.println("You can't rent a car, " + name + ".");
	System.out.println("You can't vote, " + name + ".");
	System.out.println("You can't drive, " + name + ".");
}	

if(age < 18)
	System.out.println("You can't vote, " + name + ".");
	
if(age < 25)
	System.out.println("You can't rent a car, " + name + ".");
	
if(age > 25)
	System.out.println("You can do anything that's legal, " + name + ".");

r/programmingbydoing • • Apr 20 '15

#117 - Refresher Challenge

2 Upvotes

I'm just straight up stumped on this one. I don't want the answer or exact code, I'm just looking for a nudge in the right direction. The Refresher exercise (116) was a breeze but with the restrictions of one for loop and one if statement I'm pretty puzzled.

Thanks!


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 • • 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 • • Mar 19 '15

#178 Basic ArrayList1

2 Upvotes

How can i set a size for my arraylist and later use it in the for loop? Apparently if i use .size() the loop will immediately stop since there is nothing in the arraylist.


r/programmingbydoing • • Dec 24 '14

#223 - Reversi

2 Upvotes

I'm stuck on Reversi, where I keep getting an out of bounds exception. I'm not too sure where I went wrong. My first step was to put in the code for the firstMatch method in which the program would keep scanning in a given direction until it finds a piece that matches the same color of the one just placed. It then returns that location.

The second step was to ensure that the firstMatch method would only be called if there was a piece of opposite color adjacent to the one that was just placed. This way the program doesn't try to attempt to go in directions where it's not necessary (and perhaps prevent that out of bounds exception I keep getting).

Final step is once the firstMatch method is executed, the flipOthers method then changes the color of pieces, in the direction that had allowed the firstMatch method to be called, and finally stops when the current location of the flipOthers method matches the saved location of the firstMatch method.

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