Computer Science 15-100 (Sections T & U), Spring 2008
Homework 2
Due: by email on Fri 25-Jan-2008 at 10:00am (email copy) and at recitation
(physical copy)
(no late submissions accepted).
Sample questions and solutions (study these first!):
// Hw2Sample1.java
// David Kosbie, 15-100, Section T-or-U
import java.util.Scanner;
public class Hw2Sample1 {
public static void main(String[] args) {
// declare local variables
Scanner scanner = new Scanner(System.in);
int x, y, sum;
// get the input (with a suitable prompt)
System.out.print("Enter two integers (separated by a space): ");
x = scanner.nextInt();
y = scanner.nextInt();
// compute result and display it
sum = x + y;
System.out.println(x + " plus " + y + " equals " + sum);
}
}
Solution:
// Hw2Sample2.java // David Kosbie, 15-100, Section T-or-U import java.util.Scanner; import java.io.File; public class Hw2Sample2 { public static void main(String[] args) throws Exception { // declare local variables Scanner scanner = new Scanner(new File("in.txt")); int x, y, product; // get the input (with no prompt -- it's from a file!) x = scanner.nextInt(); y = scanner.nextInt(); // compute result and display it (with no extra UI -- it's from a file!) product = x * y; System.out.println(product); } }
Solution:
// Hw2Sample3.java // David Kosbie, 15-100, Section T-or-U import java.util.Scanner; import java.io.File; import java.io.PrintStream; public class Hw2Sample3 { public static void main(String[] args) throws Exception { // declare local variables Scanner scanner = new Scanner(new File("in.txt")); PrintStream out = new PrintStream(new File("out.text")); int x, y, quotient; // get the input (with no prompt -- it's from a file!) x = scanner.nextInt(); y = scanner.nextInt(); // compute result and display it (with no extra UI -- it's from a file!) quotient = x / y; out.println(quotient); } }
// Hw2Sample4.java
// David Kosbie, 15-100, Section T-or-U
import java.util.Scanner;
public class Hw2Sample4 {
public static void main(String[] args) {
// declare local variables
Scanner scanner = new Scanner("3 7"); // hard-coded input values in a string
int x, y, sum;
// get the input (with a suitable prompt)
System.out.print("Enter two integers (separated by a space): ");
x = scanner.nextInt();
y = scanner.nextInt();
// compute result and display it
sum = x + y;
System.out.println(x + " plus " + y + " equals " + sum);
}
}
Assigned Questions:
Carpe diem!