Wednesday, November 2, 2011

Challenge 029

When the specific code is entered into the compiler, your result is as follows:

******
******
******
******
******

The for loop has three stages: initialization (it's executed once, as the loop begins).
termination (expression evaluates to false, the loop then terminates).
increment (what is produced after each cycle through the loop).

There are five lines of *'s because we set k=1 and tell the loop to produce the output of *'s until the statement for (int k = 1; k <= 5; k++) is false. This happens to be 5 times since there are only 5 lines.
As for the number of *'s in a line, the for loop tells i to create the loop. Since we set i=1, the for loop says to print out an * until the statement for (int i = 1; i <=6; i++) is false. This happens when the i value reaches 7. Since on 7 it is false, it terminates and produce 6 *'s.

The way the for loop works is first the compiler will verify that the for loop for k is true for k=1, then it will go down and verify that the for loop for i is true for i=1. Because of the System.out.println() , it skips a line and goes on to the next line. It then goes back up to the for loop for k because of the k++ in the code. This means thats k = k+1. So now it produces the second line of stars because the loop is true. After this, it goes down to the for loop for i++ so it produces 2 stars on the lines. This loop continues until k reaches 6 and i reaches 7

Challenge 028

import java.util.Scanner;

public class GradeOMatic
{
public static void main(String[] args)
{
Scanner scanUserInput = new Scanner(System.in);
System.out.print("Grade Received (%): ");
int n = scanUserInput.nextInt();
if (n >= 70)
if (n >= 80)
if (n >= 90)
System.out.println("Excellent!");
else
System.out.println("Good!");
else
System.out.println("Average.");
else
System.out.println("You Stink!"); //just kidding it's System.out.println("Bad Times!");
}
}
This code displays the appropriate comment when percentage scores are entered.

(With help from the code in Challenge026)

Challenge 027

Location hotSpot = new Location(4 , 7)

Tuesday, November 1, 2011

Challenge 026

The code goes wrong when you type in odd numbers when the program is ran. The compiler tells you that any positive odd number is not positive. Another problem that Karl has encountered is how the compiler wont run the program and provide him with an answer when he enters a negative number.

The problem in the code is in his statement: if (n % 2 == 0)
This is incorrect because this is telling the compiler to only perform the task if the remainder of n/2 is 0. This makes sense because any even number divided by 2 will result in an int. He could fix this solution by eliminating the faulty statement.