Number Guessing Game Extension §
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
System.out.println("Picking a random number between 1 and 30...");
// Generate random number in the range 1-30
int randomNumber = 1 + (int)(Math.random() * (30 - 1));
boolean guessedCorrectly = false;
int counter = 0;
while (!guessedCorrectly) {
System.out.print("Enter your guess: ");
Scanner scanner = new Scanner(System.in);
int userGuess = scanner.nextInt();
counter++;
if (userGuess == randomNumber) {
System.out.println("You guessed right!");
guessedCorrectly = true;
System.out.println("It took you " + counter + " guesses.");
} else if (userGuess < randomNumber) {
System.out.println("Your guess was too low. Try again.");
} else {
// This is the case where (userGuess > randomNumber)
System.out.println("Your guess was too high. Try again.");
}
}
}
}
Fibonacci Sequence §
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// Fibonacci Generator
// caleb b
Scanner scan = new Scanner(System.in);
System.out.println("Enter the amount of numbers you want in the sequence: ");
int n = scan.nextInt();
int[] fib = new int[n];
fib[0] = 0;
fib[1] = 1;
for(int i = 2; i < n; i++) {
fib[i] = fib[i-1] + fib[i-2];
}
for(int i = 0; i < n; i++) {
System.out.print(fib[i] + " ");
}
}
}
View Next Assignment