Fortune Teller with Java Classes
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
For your Java development environment, create a new repl with Java (listed under “Popular” languages). You will see this default code:
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
Following standard best practices in Java, we will create a new file to contain our FortuneTeller
class. Press the new file icon above the line numbers to create a new file named “FortuneTeller.java.”
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
Navigate back to your “Main.java” file, which contains the default code that comes with your Java project. Find the line that starts with “System” and delete it. You should be left with this skeleton:
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.
Debugging
If you run into any errors, you can try your hand at debugging them based on the error message. Otherwise, you can look at the solution code and see how it compares to yours.
Congratulations on writing an object-oriented Java program!
More projects
Using similar input/output-oriented code, you can try your hand at any of the these beginning Java project ideas. You can use OOP or not!
- 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?