Category Archives: Resources

CS Tools: Practice-it!

     click here     

Practice-It is a web application to help you practice solving Java programming problems online.

To use Practice-It, first create an account, then choose a problem from our list. Type a solution and submit it to our server. The system will test it and tell you whether your solution is correct.

Marty Stepp, of Stanford University Computer Science, is the primary developer of Practice-It, although Practice-It is an independent tool not directly affiliated with Stanford University nor any other university. Marty runs a similar site, CodeStepByStep.com, that offers a different selection of coding problems for Java, C++ and Python.

Current contributors to Practice-It also include:

  • Melissa Galloway, University of Washington
  • Ryan Rowe, University of Washington
  • Whitaker Brand, University of Washington

Some notable past contributors to the development and administration of Practice-It are:

  • Katlyn Edwards
  • Zack Cava
  • Jessica Miller

Some former students and TAs who have authored or ported a significant number of problems into Practice-It include:

  • Roy McElmurry
  • Robert Baxter
  • Leslie Ferguson

Also thanks to:

  • Zorah Fung for drawing the Practice-It logo image and mascot
  • Glen Herrmannsfeldt from Caltech for contacting us with many bug fixes and suggestions for improvement to the quality of the system
  • Countless other teaching assistants and colleagues who added problems

Practice-It is inspired by similar tools such as CodingBatJavaBall, and CodeWrite.

Our Privacy Policy

Built-in: Quadratic Equation

Write a program, QuadraticEQ_YI.java that takes as input arguments the coefficients of the quadratic equation, a, b, c and finds the solutions of the equation. In other words, if a, b and c are the coefficients of ax^2 + bx + c, then a can be obtained with args[0], b with args[1] and c with args[2]


NOTE: Assume the equation has two solutions.

Below is the syntax highlighted version of Quadratic.java from §1.2 Built-in Types of Data.
/******************************************************************************
 *  Compilation:  javac Quadratic.java
 *  Execution:    java Quadatic b c
 *  
 *  Given b and c, solves for the roots of x*x + b*x + c.
 *  Assumes both roots are real valued.
 *
 *  % java Quadratic -3.0 2.0
 *  2.0
 *  1.0
 *
 *  % java Quadratic -1.0 -1.0
 *  1.618033988749895
 *  -0.6180339887498949
 *
 *  Remark:  1.6180339... is the golden ratio.
 *
 *  % java Quadratic 1.0 1.0
 *  NaN
 *  NaN
 *
 *
 ******************************************************************************/

public class Quadratic { 

    public static void main(String[] args) { 
        double b = Double.parseDouble(args[0]);
        double c = Double.parseDouble(args[1]);

        double discriminant = b*b - 4.0*c;
        double sqroot =  Math.sqrt(discriminant);

        double root1 = (-b + sqroot) / 2.0;
        double root2 = (-b - sqroot) / 2.0;

        System.out.println(root1);
        System.out.println(root2);
    }
}
Copyright © 2000–2017, Robert Sedgewick and Kevin Wayne. Last updated: Fri Oct 20 14:12:12 EDT 2017.

Built In: Using Scanner for input


/**
 *  good resource: http://docs.oracle.com/javase/tutorial/essential/io/scanning.html
 * @author gracielaelia
 * Problem: Both hasNext and next methods may block waiting for further input.
 * hasNext() doesn't return false ever!!!! next() blocks until something is input!
 * As you're reading from stdin, that'll either be when you send an EOF character (usually ^d on Unix), 
 * or at the end of the file if you use < style redirection.
 * You cannot easily send and EOF character using the keyboard"
 * -- usually Ctrl+D on Linux/Unix/Mac 
 * or Ctrl+Z on Windows does it
 */    

import java.util.Scanner;

public class ScannerTest_GE {
    public static void main(String[] args){
        Scanner scan = new Scanner(System.in);
        String name;  // declaration
        double base, exponent;
        System.out.println("Enter the base ");
        base = scan.nextDouble();
        System.out.println("Enter the exponent ");
        exponent = scan.nextDouble();
        System.out.println("Enter your name " );    
        name = scan.next();
        System.out.println(name + " the value is "+ Math.pow(base,exponent));
        System.out.println(name + " the integer value is "+ (int)Math.pow(base,exponent));
    }
}


// Enter the base 
// 2
// Enter the exponent 
// 5
// Enter your name 
// grace
// The value is 32.0
// The integer value is 32

Built-in: Boolean Algebra

 

Some basic concepts from MathHacks:

 

Advanced Topic: Static Methods and the String class

Static Methods:

The Math class:
Math.pow(10, 3)

    In Java, numbers as primitive data types are not objects, so you can never invoke a method on a number.
    Instead, you pass a number as an explicit parameter to a method
    ClassName.methodName(parameters)
  1. What happens to this code fragment when you compile it?

int x = 2;
System.out.println(x.pow(3));

  1. What is the difference between an ADT and a primitive data type? What can you create with an ADT?

The String Class
In Java, strings are objects that belong to the class String.
You do not need to call a constructor to create a string object.

A string is a sequence of characters. Strings are objects of the String class.

The substring method computes substrings of a string.

The call s.substring(start, pastEnd)

returns a string that is made up of the characters in the string s, starting at position start, and containing all characters up to, but not including, the position pastEnd.

Here is an example:
String greeting = “Hello, World!”;
String sub = greeting.substring(0, 5); // sub is “Hello”

H e l l o ,   W o r  l  d  !
0 1 2 3 4 5 6 7 8 9 10 11 12


The position number of the last character (12 for the string “Hello, World!”) is always 1 less than the length of the string.

Let us figure out how to extract the substring “World”.
Count characters starting at 0, not 1. You find that W, the eighth character, has position number 7. The first character that you don’t want, !, is the character at position 12 .

               <-----5---->
H e l l o ,   |W o r  l  d | !
0 1 2 3 4 5 6 |7 8 9 10 11 | 12


String sub2 = greeting.substring(7, 12);

You can easily compute the length of the substring: It is pastEnd – start. For example, the string “World” has length 12 – 7 = 5.

If you omit the second parameter of the substring method, then all characters from the starting position to the end of the string are copied.

For example,
String tail = greeting.substring(7); // tail is “World!”

  1. Why can you have multiple substring methods doing something different?

If you supply an illegal string position (a negative number, or a value that is larger than the length of the string), then your program terminates with an error message.

  1. Will it be an error during compilation or at run time?

Strings and the char Type
Strings are sequences of Unicode characters.
Character literals look like string literals, but we use single quotes: ‘M’ is a character, “M” is a string containing a single character.

Characters have integer values.
Screen Shot 2015-02-11 at 9.53.31 AM

You can use escape sequences inside character literals. For example, ‘\n’ is the newline character, and ‘\u00E9’ is the character é.

“When Java was first designed, each Unicode character was encoded as a two-byte quantity. The char type was intended to hold the code of a Unicode character. However, as of 2003, Unicode had grown so large that some characters needed to be encoded as pairs of char values. Thus, you can no longer think of a char value as a character. Technically speaking, a char value is a code unit in the UTF-16 encoding of Unicode. That encoding represents the most common characters as a single char value, and less common or supplementary characters as a pair of char values.” Clay Horstmann

Screen Shot 2015-02-11 at 12.59.39 PM

The charAt method of the String class returns a code unit from a string. As with the substring method, the positions in the string are counted starting at 0.
For example, the statement

String greeting = “Hello”;
char ch = greeting.charAt(0);

sets ch to the value ‘H’.

  1. How do you find out the number of characters a string has?
  2. How can you create an array of char type containing all the characters of a string?

Visit edmodo.com to answer these questions.

Conditionals: CompoundIntTable_YI.java – Needs fixing

Screen Shot 2014-09-23 at 10.00.31 AM

NO MORE MAGIC NUMBERS

Things to keep in mind when submitting your work:
1. Copy and paste your program in the post.
2. Attach your file(s).
3. Make sure your program has a header and the input/output.
4. If your program doesn’t run, an explanation should be the first line in the post.

Screen Shot 2014-09-28 at 12.38.49 PM

Classwork:
YI_CompoundIntTable.java: Use a while loop to show how the investment increases as the accumulated total becomes at least $1,100 at an interest rate of 1.2% when $1,000 is deposited in a savings bank account.

The table should have the following columns:


year      accum interest/year          total accumulated up to this year  
 1        12.0                         1012.0
 2        24.14                        1024.14
 3        36.43                        1036.43
...

Number of years for the investment of $1000 to reach at least a value of $1,100 with an interest rate of 1.2% is  8

Homework:
CompIntCompareTable_YI.java: Create another table that compares how you use the formula P(1+r)^t, where t is the number of years and how your program calculates the equivalent values.
End up your assignment with a conclusion about the similarities and the differences between the two approaches.

Conditionals: Project Euler

https://projecteuler.net/

About Project Euler

Leonhard Euler (1707-1783)

What is Project Euler?

Project Euler is a series of challenging mathematical/computer programming problems that will require more than just mathematical insights to solve. Although mathematics will help you arrive at elegant and efficient methods, the use of a computer and programming skills will be required to solve most problems.

The motivation for starting Project Euler, and its continuation, is to provide a platform for the inquiring mind to delve into unfamiliar areas and learn new concepts in a fun and recreational context.

 

Who are the problems aimed at?

The intended audience include students for whom the basic curriculum is not feeding their hunger to learn, adults whose background was not primarily mathematics but had an interest in things mathematical, and professionals who want to keep their problem solving and mathematics on the cutting edge.

 

Can anyone solve the problems?

The problems range in difficulty and for many the experience is inductive chain learning. That is, by solving one problem it will expose you to a new concept that allows you to undertake a previously inaccessible problem. So the determined participant will slowly but surely work his/her way through every problem.

 

What next?

In order to track your progress it is necessary to setup an account and have Cookies enabled. If you already have an account then Login, otherwise please Register – it’s completely free!

However, as the problems are challenging then you may wish to view the Problems before registering.

 

“Project Euler exists to encourage, challenge, and develop the skills and enjoyment of anyone with an interest in the fascinating world of mathematics.”

 

Input/Output: Command Line: AddInts


/******************************************************************************
 *  Compilation:  javac AddInts.java
 *  Execution:    java AddInts
 *  Dependencies: StdIn.java StdOut.java
 *  
 *  This program takes a command-line argument n, reads in n integers,
 *  and prints out their sum.
 *
 *  % java AddInts n
 *
 ******************************************************************************/

public class AddInts { 
    public static void main(String[] args) { 
        int n = Integer.parseInt(args[0]);
        int sum = 0;
        for (int i = 0; i < n; i++) {
            int value = StdIn.readInt();
            sum = sum + value;
        }
        StdOut.println("Sum is " + sum);
    }
}