Skip to content

Instantly share code, notes, and snippets.

@NatKarmios
Created August 27, 2016 20:39
Show Gist options
  • Save NatKarmios/7fe0c9a1d7f99dbc1fc8a5e57aa44937 to your computer and use it in GitHub Desktop.
Save NatKarmios/7fe0c9a1d7f99dbc1fc8a5e57aa44937 to your computer and use it in GitHub Desktop.
Year 12 Induction Tasks for Computer Science at Twyford. [By Nat Karmios]
package com.karmios.nat.ComputingWork.InductionTasks.Section2.Task1;
import java.util.Scanner;
public class Code {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
// Prompt the user to enter their weight in pounds
System.out.print("Enter your weight in pounds: ");
double weight = input.nextDouble();
//Prompt the user to enter their height in inches
System.out.print("Enter your height in inches: ");
double height = input.nextDouble();
final double KG_PER_POUNDS = 0.45359237;// Constant
final double M_PER_INCH = 0.0254;// Constant
// Compute BMI
double weightInKg = weight * KG_PER_POUNDS;
double heightInMetres = height * M_PER_INCH;
double bmi = weightInKg / (heightInMetres * heightInMetres);
// Display result
System.out.println("Your BMI is: " + bmi);
if (bmi < 18.5) System.out.println("Underweight");
else if (bmi < 25) System.out.println("Normal");
else if (bmi < 30) System.out.println("Overweight");
else System.out.println("Obese");
}
}

Data Input

The program first creates a Scanner object and assigns it to input (note that the Scanner class had to be imported from java.util):

8   scanner input = new Scanner(System.in);

The program then prompts the user to enter their weight in pounds, calling System.out.println() to print a message to the console, then calling input.nextDouble() to wait for the user to enter a value - the result being assigned to the weight variable. This is repeated for height, which is taken in inches.

Then, two constants are defined: KG_PER_POUNDS and M_PER_INCH, which are decimal numbers used to convert between kilograms and pounds and between meters and inches respectively. The final keyword is used here, as these variables will never be reassigned.

BMI Calculation

The program converts the height and weight to kg and m respectively. It does this by multiplying the appropriate value with its aforementioned conversion constant. The results are assigned to weightInKg and heightInMeters.

Finally, the BMI is calculated: weightInKg is divided by heightInMeters squared, the result being assigned to bmi.

Displaying the Result

Firstly, the BMI is printed by calling System.out.println() and passing in a string including the value of bmi.

Then, the program states whether the user is underweight, normal, overweight or obese by checking whether bmi is below three different values in an if/else if/else if/else statement.

package com.karmios.nat.ComputingWork.InductionTasks.Section2.Task2;
import java.util.Random;
import java.util.stream.IntStream;
public class Code {
public static void main(String[] args){
Random rng = new Random();
int[] pickedNumbers = new int[7];
for(int i=0; i<7; i++) {
int picked;
do {
picked = rng.nextInt(49) + 1;
} while (IntStream.of(pickedNumbers).anyMatch(new Integer(picked)::equals));
pickedNumbers[i] = picked;
}
System.out.println("Lottery numbers:");
for(int i=0; i<6;
System.out.println(pickedNumbers[i++]));
System.out.println("Bonus ball: " + pickedNumbers[6]);
}
}

Initial Declarations

Firstly, a random number generator is created by assigning a new instance of Random (imported from java.util) to the rng variable. An integer array of length seven is created, to store all six lottery numbers as well as the bonus ball, and is assigned to pickedNumbers.

Generating Numbers

To generate the lottery numbers, the program enter a for loop, incrementing the variable i from 0 to 7, for each value in pickedNumbers. In each iteration, a local variable - picked - is created, and the program enters a do/while loop, in which picked is set to rng.nextInt(49) + 1, which will generate a random number between 1 and 49 inclusive.

The do/while loop's boolean condition creates an integer stream of pickedNumbers, and calls anyMatch(new Integer(picked)::equals) on it. This boxes picked into an Integer object, and then iterates over the aforementioned integer stream, calling equals() on said object to check if any of the integers are the same as picked. If any integer in pickedNumbers equal to picked, then anyMatch() returns new, and a new number is generated for that index in pickedNumbers.

Displaying Numbers

After printing "Lottery numbers:", the program iterates over each int in pickedNumbers and prints them on new lines. Finally, "Bonus ball: " is printed along with the last value in pickedNumbers.

package com.karmios.nat.ComputingWork.InductionTasks.Section3.Task1;
import java.util.Random;
import java.util.Scanner;
public class Code {
private static String[][] WORD_LISTS = {
{"hot", "summer", "hard", "dry", "heavy", "light", "weak", "male", "sad", "win",
"small", "ignore", "buy", "succeed", "reject", "prevent", "exclude"},
{"cold", "winter", "soft", "wet", "light", "darkness", "strong", "female", "happy", "lose",
"big", "pay attention", "sell", "fail", "accept", "allow", "include"}
};
public static void main(String[] args) {
Random rng = new Random();
Scanner sc = new Scanner(System.in);
int score = 0;
System.out.print("Enter your name: ");
String name = sc.next();
for (int i = 0; i < 10; i++) {
int pick1 = rng.nextInt(17);
int pick2;
while ((pick2 = rng.nextInt(17)) == pick1) ;
print_question(pick1, pick2);
if (sc.next().equals(WORD_LISTS[1][pick2])) {
System.out.println("Correct!");
score++;
}
else System.out.println("Wrong!");
}
System.out.printf("%s, you scored %s out of 10.%n", name, score);
}
private static void print_question(int num1, int num2) {
System.out.printf("%s is to %s as %s is to... ",
WORD_LISTS[0][num1], WORD_LISTS[1][num1], WORD_LISTS[0][num2]);
}
}
score  0
word_list1  [hot, summer, hard, dry, heavy, light, weak, male, sad, win, small, ignore, buy,
succeed, reject, prevent, exclude]
word_list2  [cold, winter, soft, wet, light, darkness, strong, female, happy, lose, big, pay attention, sell,
fail, accept, allow, include]
PROCEDURE make_question(number1, number2)
OUTPUT word_list1[number1], “is to”, word_list2[number1], “as”,
word_list1[number2] , “is to __________________ ?”
END PROCEDURE
INPUT name
FOR index FROM 1 TO 10
pick1  random(0, LEN(word_list1) – 1) #LEN returns the length of the list
pick2  random(0, LEN(word_list2) – 1) #LEN returns the length of the list
{random(a,b) generates a random number between a and b inclusive}
WHILE pick2 = pick1
pick2  random(0, LEN(word_list2) – 1)
END WHILE
{Now make a question}
make_question(pick1, pick2)
correct_answer  word_list2[pick2]
INPUT user_answer
IF user_answer = correct_answer THEN
score  score + 1
OUTPUT “Correct answer”
ELSE
OUTPUT “Wrong answer”
END IF
NEXT index
END FOR
OUTPUT name, “you got”, score, “out of 10”
package com.karmios.nat.ComputingWork.InductionTasks.Section3.Task2;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.Arrays;
import java.util.Random;
import java.util.Scanner;
import java.util.stream.IntStream;
import com.karmios.nat.ComputingWork.Utils;
public class Code {
private static final String FILE_NAME = "Output.txt";
private static final String[][] WORD_LISTS = {
{"hot", "summer", "hard", "dry", "heavy", "light", "weak", "male", "sad", "win", "left", "front",
"up", "small", "ignore", "buy", "succeed", "reject", "prevent", "exclude"},
{"cold", "winter", "soft", "wet", "light", "darkness", "strong", "female", "happy", "lose", "right", "back",
"down", "big", "pay attention", "sell", "fail", "accept", "allow", "include"}
};
private static int[] picked = new int[20];
static { Arrays.fill(picked, -1); }
public static void main(String[] args) {
Random rng = new Random();
Scanner sc = new Scanner(System.in);
int score = 0;
System.out.print("Enter your name: ");
String name = sc.nextLine();
for (int i = 0; i < 10; i++) {
int pick1, pick2;
while (pickedContains(pick1 = rng.nextInt(20)));
picked[i] = pick1;
while (pickedContains(pick2 = rng.nextInt(20)));
picked[i+10] = pick2;
print_question(pick1, pick2);
if (sc.nextLine().equals(WORD_LISTS[1][pick2])) {
System.out.println("Correct!");
score++;
}
else System.out.println("Wrong!");
}
System.out.printf("%s, you scored %s out of 10.%n", name, score);
writeResult(name, score);
}
private static void print_question(int num1, int num2) {
System.out.printf("%s is to %s as %s is to... ",
WORD_LISTS[0][num1], WORD_LISTS[1][num1], WORD_LISTS[0][num2]);
}
private static boolean pickedContains(int num) {
return IntStream.of(picked).anyMatch(new Integer(num)::equals);
}
private static void writeResult (String name, int score) {
String fileName = Utils.getDir(Code.class) + FILE_NAME;
try {
Files.write(
Paths.get(fileName), String.format("%s, %s%n", name, score).getBytes(), StandardOpenOption.APPEND);
} catch (IOException e) {
System.out.println("Failed to write results to file.");
}
}
}
score  0
word_list1  [hot, summer, hard, dry, heavy, light, weak, male, sad, win, small, ignore, buy,
succeed, reject, prevent, exclude]
word_list2  [cold, winter, soft, wet, light, darkness, strong, female, happy, lose, big, pay attention, sell,
fail, accept, allow, include]
PROCEDURE make_question(number1, number2)
OUTPUT word_list1[number1], “is to”, word_list2[number1], “as”,
word_list1[number2] , “is to __________________ ?”
END PROCEDURE
INPUT name
picked  INT[20]
FOR each question in test LOOP
REPEAT
pick1  random question number
picked[index]  pick1
UNTIL picked does not contain pick1
REPEAT
pick2  random question number
picked[index+10]  pick2
UNTIL picked does not contain pick2
make_question(pick1, pick2)
correct_answer  word_list2[pick2]
INPUT user_answer
IF user_answer = correct_answer THEN
INCREMENT score
OUTPUT “Correct answer”
ELSE
OUTPUT “Wrong answer”
ENDIF
ENDFOR
OUTPUT name, “you got”, score, “out of 10.”
write name + ", " + score + "\n" to "output.txt"

Comments on the Question

The question given was somewhat flawed - it claims that no pair of opposites can be shown twice in the test. Because each question uses up 2 pairs, and 10 questions are required, the 17 pairs provided by the question are not sufficient for the test; I had to add 3 pairs of my own to the list for the code to work.

Functionality

My code completes the criteria exactly, save for the above error. It follows the same function is Task 1, with some added checking to prevent duplicate questions.

It also outputs the test taker's name score to output.txt.

Code Appearence

I believe my code is relatively clean and readable.

A change I could have made was substituting the variables pick1 and pick2 for a single int array of length 2 - this would save me repeating the code for selecting a question from the list. However, this may clutter my code with too many index references, making it a bit less understandable.

I also chose to move sections of code to helper functions, such as pickedContains() - although this could have been achieved in one or two lines in the code, I would have to inflate both while loops and give them a code body to handle this logic, bloating my code a little.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment