Stanford CS106A Assignment 2 Pythagorean Theorem Solution

31 Oct

Woohooo! Finally an easier one 🙂 This one, the professor pretty much went over in Lecture 6. Luckily, I took good notes. Here is the problem:

Here is my solution, also available on github:


Since the other problems here were Graphics programs, I stumbled a bit by creating a “GLabel”. Since this is a Console program, remember to use “println()” to display a message or “readInt()” stored as an integer to ask the user for feedback. If you keep these in mind, this is a pretty simple problem (probably the easiest one in Assignment 2).

<pre>/*
 * File: PythagoreanTheorem.java
 * Name: 
 * Section Leader: 
 * -----------------------------
 * This file is the starter file for the PythagoreanTheorem problem.
 */

import acm.program.*;

public class PythagoreanTheorem extends ConsoleProgram {
	public void run() {
		sayWelcomeMessage();
		askUserInput();
	}
	private void sayWelcomeMessage() {
		println( "Enter values to compute the Pythagorian theorem" );
	}
	private void askUserInput() {
		int a = readInt ("a:"); //asks user to enter an integer for a
		int b = readInt ("b:"); //asks user to enter an integer for b
		double x = (double)a; // converts variable "a" from an integer to a double 
		double c = Math.sqrt((x*x) + (b*b)); //calculates square root
		println("c:"+ c); //displays value as a double
	}
}</pre>
Advertisements

One Response to “Stanford CS106A Assignment 2 Pythagorean Theorem Solution”

Trackbacks/Pingbacks

  1. » CS106a Assignment 2 – Pythagorean Theorem …zero to hero - March 7, 2012

    […] Natasha The Robot solution […]

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s