X
    Categories: Java

Stanford cs106a Assignment 2, Problem 1 – PythagoreanTheorem

Below is my answer for Problem 1, Assignment 2:

The question asks,
By using the Pythagorean Theorem, calculate the value of c, in relation to input provided by the user for the values of a, and b. Write a ConsoleProgram that accepts values for a and b as doubles (you can
assume that a and b will be positive) and then calculates the solution of c as a
double.

My solution is as follows:

/*
* File: PythagoreanTheorem.java
* Name: Jason Coltrin
* Section Leader: n/a
* -----------------------------
* This file is the starter file for the PythagoreanTheorem problem.
*/

import acm.program.*; //imports classes needed to run ConsoleProgram

public class PythagoreanTheorem extends ConsoleProgram {
public void run() {
println("Enter values to compute the Pythagorean Theorem!");

// sets user input of a: to n1 as double
double n1 = readDouble("Enter value of a: ");

// sets user input of b: to n2 as double
double n2 = readDouble("Enter value of b: ");

// order of calculation calculates in parentheses first, then + second,
// and sets value of sqr root to variable c.
double c = Math.sqrt((n1 * n1) + (n2 * n2));

// Prints the answer after "C ="
println("c = " + c);
}
}

The output looks like below:

coltrinit:
Related Post