Fortune Teller with Java Classes

Kelly Lougheed
Jan 9, 2018 · 6 min read
Image for post
Image for post
Photo by Scott Rodgerson on Unsplash

This tutorial will show you how to create a text-based fortune teller with Java. It assumes familiarity with basic programming, Java, classes, and object-oriented programming. If you are unfamiliar with programming, Java, or OOP, check out the tutorials at SoloLearn or Codecademy.

Getting started

class Main {
public static void main(String[] args) {
System.out.println("Hello world!");
}
}

When we run our Java program, it will automatically run the code in the main function. We’ll return to this code later, since we’re going to start out defining a FortuneTeller class in a separate file.

Defining a FortuneTeller class

Image for post
Image for post
Click on the “new file” icon to create your “FortuneTeller.java” file.

First, we want to import Java’s Scanner class in order to read user input. Start your new file with this code:

import java.util.Scanner;

Now, below the import, you can start to define your new class:

class FortuneTeller {
// We'll add code in here!
}

We’ll be adding the rest of our code between the curly brackets { }.

The first thing we will add is a Scanner object for reading user input:

Scanner scanner = new Scanner(System.in);

Now we’re going to add some instance variables. First, I’m going to add an array of fortunes that my fortune teller might generate:

String[] fortunes = {};

I’m going to leave it empty for now and add fortunes later when I’ve finished the rest of the app.

The way I’m going to tell someone’s fortune is to produce three numbers based on user input, so I’ll also need instance variables for those numbers. Add these variables to your class:

int one, two, three;

Now we can start writing the instance methods to produce these three random numbers. I’m going to ask the user their name, favorite color, and favorite food. Then I’ll calculate the number of characters in their answer to produce my “random” number.

To assign int one a value, I will use the getName() method. As discussed above, I’ll calculate the number of characters in the user’s name to produce a seemingly random number. Add the following method to your class:

void getName() {
System.out.println("What's your first name?");
String name = scanner.next();
one = name.length();
}

To assign int two a value, I will use the getColor() method. In this method, the number of characters in the user’s favorite color will serve as the random number. Add this code to your class:

void getColor() {
System.out.println("What's your favorite color?");
String color = scanner.next();
two = color.length();
}

Finally, to assign int three a value, I will use the getFood() method. The number of characters in the user’s favorite food will be our final random number. Add this method to your class:

void getFood() {
System.out.println("What's your favorite food?");
String food = scanner.next();
three = food.length();
}

Now, to continue breaking down our class into small, manageable parts, let’s wrap up all the methods into one askQuestions method to take care of asking all three questions at once. Add this method to your class:

void askQuestions() {
getName();
getColor();
getFood();
}

And now, at last, it’s time to print the user’s fortune based on their input. To accomplish this, we’ll write a tellFortune() method. Add this code to your class:

void tellFortune() {
int res = one + two + three;
res = res % fortunes.length;
System.out.println(fortunes[res]);
}

In this method, we first find the sum of our three “random” numbers. Then we calculate the sum modulo the number of fortunes in our fortunes array to calculate an index between 0 and the index of the last item in the fortunes array. With this value, we can print out a randomly selected fortune from the array.

Once we add as many fortunes as we desire to the array, we will be done defining the class. You can either Google a list of fortunes or make up your own!

I took fortunes from Fortune Cookie Fortunes and populated my array with ten of them:

String[] fortunes = {
"A dubious friend may be an enemy in camouflage.",
"Your success will astonish everyone.",
"You will soon be surrounded by good friends and laughter.",
"Many will travel to hear you speak.",
"Now is a good time to buy stock.",
"Physical activity will dramatically improve your outlook today.",
"Say hello to others. You will have a happier day.",
"You should be able to undertake and complete anything.",
"You will be pleasantly surprised tonight.",
"You will be traveling and coming into a fortune.",
};

Once your array is full of fortunes, we’re ready to start using our FortuneTeller class!

Using FortuneTeller in main

class Main {
public static void main(String[] args) {

}
}

We are going to add some code between the two innermost curly brackets { }.

First, in order to use our FortuneTeller class in main, we need to create a new FortuneTeller object. Inside the innermost curly brackets, create a new FortuneTeller:

FortuneTeller ft = new FortuneTeller();

The code above creates a new FortuneTeller object contained in the variable ft.

Now, thanks to all our hard work writing the FortuneTeller class, all we have to do is call two methods on ft. Looking back at the FortuneTeller class, can you figure out which two methods those are?

(Hint: you need to call the method that asks all the questions and the method that prints your fortune.)

If you guessed the askQuestions() and tellFortune() methods, you are correct! Add this code inside main:

ft.askQuestions();
ft.tellFortune();

Now your “Main.java” file should contain this code:

class Main {
public static void main(String[] args){
FortuneTeller ft = new FortuneTeller();
ft.askQuestions();
ft.tellFortune();
}
}

Run the program to see how it works! You may need to wait a minute for the first prompt.

Image for post
Image for post
Your program should look something like this.

Debugging

Congratulations on writing an object-oriented Java program!

More projects

  • Create a trivia quiz. Keep track of the user’s number of correct answers and give them a grade at the end.
  • Create a personality quiz. Ask the user multiple choice questions where the letters correlate to a numerical score. Then calculate their result based on their numerical score.
  • Create a calculator that performs simple operations (addition, subtraction, multiplication, division). To make it easier, you can have the user input specifically which operation they want as well as the two numbers.
  • Students, create a program that tells you your schedule (where you should be) on any given day at any given time (based on user input of the day/time).
  • What other programs can you create that involve user input?

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch

Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore

Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store