20111022_1006PM (1435307)/Homework6

advertisement
1. Name the four (eight) primitive types in Java.
byte, short, int, long, double, float, char, Boolean
2. Consider the following program:
class One {
public static void main(String[] args) {
System.out.println(args[0] == args[1]);
}
}
Let's say you compile then run this program with:
java One tomato tomahto
What's the output and why?
Now call it with:
java One tomato tomato
Does the output change? Why or why not?
What is the enduring conclusion of this experiment?
java one tomato tomahto
output
false. We do not compare String using == ,
but use stringName.equals(String other);
java one tomato tomato output: false
3. How many instance variables does CheckerBoard have?
4 instance variables:
board values, i, I, j
4. Same question about instance methods, static variables, static methods.
2 instance methods, 3 static variable, 1 static methods
5. Why does this program not compile?
class One {
public static void main(String[] args) {
int diceOne, diceTwo;
diceOne = Math.floor(Math.random() * 6 + 1);
diceTwo = Math.floor(Math.random() * 6 + 1);
System.out.println( diceOne + " " + diceTwo );
}
}
What can you do to make it run properly, so as to simulate a pair of dice?
Method Math.floor returns a double type. Thus we should cast double to int , then given the
value to diceOne/ diceTwo
class One {
public static void main(String[] args) {
int diceOne, diceTwo;
diceOne = (int)Math.floor(Math.random() * 6 + 1);
diceTwo = (int)Math.floor(Math.random() * 6 + 1);
System.out.println( diceOne + " " + diceTwo );
}
}
6. What's the return type of Math.floor(...)?
double
7. How do you produce random integers in the interval (-50, 50)?
(int) Math.floor(Math.random()*100-50);
8. Write a method sorted that receives an array of integers as argument and returns a boolean.
The method returns true if the array is sorted and false otherwise/
class Two{
public static boolean isSorted(int[] num){
if(num.length < 3) return true; //an array with less than 3 elements, return true
else {
int i =0;
boolean ascending = true; // show the array is sorted by ascending or descending
boolean sorted = true;
while(i<num.length-1){
if(num[i] ==num[i+1]) i++;
else if (num[i] <num[i+1]) break; // if the first two consecutive integers, which are not equal,
//are in an ascending relationship
// we assume that the array is sorted in ascending order
else {
ascending = false; break; // if the first two consecutive integers that are not equal are in
// descending relation, we assume the array is sorted descendingly.
}
}
if(i >= num.length - 2) sorted = true; // if a[0] to a[length-2] are all equal, eg{2, 2, 2,2, 4}, return true
else{
if (ascending == true){ // assume it is ascending
for(int j =i; j<num.length-1; j++){
if (num[j] > num[j+1]) sorted =false;
else sorted =true;
}
}
else {
for(int k = i; k<num.length-1;k++){
if (num[k]<num[k+1]) sorted =false;
else sorted =true;
}
}
}
return sorted;
}
}
public static void main(String[] args){
int[] num = {7,5,2};
System.out.println(Two.isSorted(num));
}
}
}
9. Did you notice the use of BufferedReader and InputStreamReader in the program above?
What class (introduced with Java 1.5) in java.util eliminates the need for such complicated
code?
Describe the most intimidating (and very concrete) side effect of reading as we do in the program
above.
Scanner
10. Consider the following program:
class One {
public static void main(String[] args) {
String months = "JanFebMarAprMayJunJulAugSepOctNovDec";
int index = Integer.parseInt(args[0]);
System.out.println(months.substring((index - 1) * 3, index * 3));
}
}
Here's how one can run it after compiling it:
-bash-3.2$ javac One.java
-bash-3.2$ java One 3
Mar
-bash-3.2$ java One 11
Nov
-bash-3.2$ java One 16
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String
index out of range: 48
at java.lang.String.substring(String.java:1934)
at One.main(One.java:5)
-bash-3.2$ java One
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
at One.main(One.java:4)
-bash-3.2$ java One 2a
Exception in thread "main" java.lang.NumberFormatException: For input string:
"2a"
at
java.lang.NumberFormatException.forInputString(NumberFormatException.java:48)
at java.lang.Integer.parseInt(Integer.java:458)
at java.lang.Integer.parseInt(Integer.java:499)
at One.main(One.java:4)
-bash-3.2$
How does the program react to each of our inputs?
month.substring(int index1, in index2)
Output a string constructed by characters in String month beginning at index1 and ending at
index2-1
11. How can you modify the program to make it issue more informative error messages?
import java.util.*;
class One {
public static void main(String[] args) throws Exception{
String months = "JanFebMarAprMayJunJulAugSepOctNovDec";
System.out.println("Enter an integer from 1 to 12 indicating the number of month in a year:");
Scanner sc = new Scanner(System.in);
int index = Integer.parseInt(sc.nextLine());
System.out.println(months.substring((index - 1) * 3, index * 3));
}
}
12
public class PrimeFactorsTest
public static int readInt(String prompt) throws Exception // read an
input from Scanner. If it is an integer return it, if it is not, catch the
exception and require user to re input.
public static boolean isPrime(int n) // from integer div from 2 to n-1,
test if n%div ==0, retrun false, otherwise return true.
public static void printPrimeFactors(int n, int start) //test n%a , while
a is any integer from start to n-1. if n%a ==0, isPrime(a), if true, print,
else do nth.
13
My method to find prime factors only one pass, every fast.
public static void primeFactors(int number) {
int n = number;
String remember = "";
System.out.println(1);
for (int i = 2; i <= n; i++) {
if (n % i == 0) {
System.out.println(i);
n /= i;}
}
}
import java.io.*;
import java.util.*;
public class PrimeFactorsTest
{
// reads a String from the user and converts it to an int
public static int readInt(String prompt) throws IOException
{
int result = 0; // the value read from the user
// create a new BufferedReader to read from standard input
BufferedReader reader =
new BufferedReader(
new InputStreamReader(System.in));
// print out the user prompt
System.out.print(prompt);
// attempt to read until valid input is entered
while(true)
{
try
{
// parse the input into an integer
result = Integer.parseInt(reader.readLine());
return result;
}
catch(NumberFormatException e)
{
// ask the user to re-enter the data
System.out.print("Bad number format, redo: ");
}
}
} // readInt
public static void primeFactors(int number) {
int n = number;
String remember = "";
System.out.println(1);
for (int i = 2; i <= n; i++) {
if (n % i == 0) {
System.out.println(i);
n /= i;}
}
}
public static void main(String[] args) throws IOException
{
int n;
do
{
n = readInt("Enter a number, or -1 to quit: ");
primeFactors(n);
} while(n > 0);
}
} // PrimeFactorsTest
Download