Please do not comment in this thread. This thread will be used to archive lessons.
If you are looking for the most recent tutorials, please go to this thread.
So you want to be a game developer!
I once was in the same shoes as you -- I wanted to make awesome games! But when I looked through the vast resources of the Internet, scouring for a guide that could help a beginning programmer transform into an Android game developer, I was unable to find a simple, thorough, yet comprehensive tutorial that I needed to succeed.
Hours and hours of reading books and watching videos later, I now think that I can help others overcome this "barrier to entry."
So without further ado, I'd like to jump right into my series.
{
"lightbox_close": "Close",
"lightbox_next": "Next",
"lightbox_previous": "Previous",
"lightbox_error": "The requested content cannot be loaded. Please try again later.",
"lightbox_start_slideshow": "Start slideshow",
"lightbox_stop_slideshow": "Stop slideshow",
"lightbox_full_screen": "Full screen",
"lightbox_thumbnails": "Thumbnails",
"lightbox_download": "Download",
"lightbox_share": "Share",
"lightbox_zoom": "Zoom",
"lightbox_new_window": "New window",
"lightbox_toggle_sidebar": "Toggle sidebar"
}
__________________________________________________
Lesson #1-0: What is Java?
Java -- everyone's heard of it. But what is it really?
I'm not going to delve too deep into Java details, as all of that information IS available online and you are here for one thing: game development.
All you need to know for now is that Java is both a programming language (that lets you communicate with computers) and a platform (that is driven by a virtual machine that interprets all of your code).
Java was designed to be everywhere -- in phones, cars, computers, and any other object that is computerized. The developers promised that you would be able to write one program that will run on any device that runs the Java platform. This promise kind of fell short, as Java did not proliferate the world's electronics devices at the rate and the extent people expected; however, a few years ago, Android came along, and this open source platform began to do what Java could not. Android devices started making their ways into cars, desktops, tablets, phones, refrigerators, and more recently, Nexus Q's. Who knows what else in the future?
Well Java will be the foundational structure of all Android game development that we will cover (at least in the predictable future), so this is why we will start with Java.
As always, if you have any questions, refer to my first post for contact information!
If you already know how to do something that I cover in a lesson, feel free to skip it! I will try to make this guide cumulative, yet easy to incorporate into what you already know.
_______________________________________________
I realize this is the most boring part of game development... bear with me here and don't be discouraged!
*One final note* : The following instructions are for Mac and Windows.
_______________________________________________
Lesson #1-1: Downloading Java and Eclipse.
Before we can do any sort of Java programming, we must first prepare our development machine!
To install Java Development Kit (JDK - it lets you create java programs), follow the following steps:
Note: As of yet, Java 7 is not supported, so you must download Java 6 (JDK6).
1. Here's the link to the download (To people reading this guide in the far future: if the following link no longer functions, search for JDK on Google. If Google no longer exists, I don't know what to tell you).
http://www.oracle.com/technetwork/java/javase/downloads/jdk6-downloads-1637591.html
2. Once you are there, below Java SE Development Kit 6 Update XX, look for YOUR operating system and version to download the corresponding JDK.
3. When the download is completed, follow the instructions to get the JDK installed!
Now we must download Eclipse, the IDE. Feel free to look up more information on Eclipse, but once you begin programming, you will easily understand what its awesome capabilities are.
Eclipse will compile your code, let you export your code, help you correct your code, organize it, etc. It's extremely useful!
1. Follow this link to the Eclipse.org's download page:
http://www.eclipse.org/downloads/
2. Download the corresponding version of Eclipse IDE for Java EE Developers.
3. You will get a .zip file containing the Eclipse folder. No installation is needed. Place it where you want to, and open eclipse.exe.
_______________________________________________
Lesson #1-2: Setting up Eclipse:
1. Upon starting Eclipse, it will ask you where you want to place your "workspace." Your workspace is where all of your resources, code, assets, etc. will be kept.
Choose a location that you will be able to access easily.
2. Once that happens, you will see a welcome screen like so:
I will pick up right here from the welcome screen for the next tutorial tomorrow morning (US Eastern Time)!
Thanks for reading.
_______________________________________________
Day 1: Summarized
Today, we discussed Java and began setting up our developmental computers, installing both the JDK and Eclipse.
Tomorrow, we will write our first Java programs and discuss the meaning of Java jargon.
_______________________________________________
Day 2:
Lesson #1-3: Dissecting Java:
Today, we will dissect a Java class.
But first... let's talk about Eclipse.
Yesterday, we left off at the welcome screen. You won't ever need to see it again. Just exit out of the tab like so:
Now you will be greeted with the screen you will see every time you open Eclipse: the workbench. Don't worry too much about the different panels. You will learn what each of them do eventually. For now, just check the following things.
1. Eclipse has multiple perspectives suited for different tasks. Check to see that the currently selected perspective is Java. If it is not Java, go to Window > Open Perspective > Other and select Java.
2. Look at the bottom panel. If you see a Console tab, move on. If not, go to Window > Show View > Console. This will display the Console tab.
You are now ready to start programming!
Take a look at the Package Explorer - it's on the left side of the screen. This is where Eclipse will organize all of your projects. If you are ready to start coding, read on!
1. Press File > New > Java Project.
2. Enter a project name of your choice.
3. Press Finish. You should now see the project in your package explorer.
4. Double click on it to expand it. You will see the following:
__________________________________________________
src is where all of your Java code will be placed.
JRE System Library (if your version of Java is not JavaSE - 1.7 like my screenshot, don't worry about it. We won't have compatibility issues) contains pre-written Java code that you can import into your own projects. This is there so programmers like me and you do not have to waste time writing code to perform frequented operations; you can just import it.
__________________________________________________
5. RIGHT-CLICK on src, select New, and create a (Java) Class file. Name it HelloWorld.
(By convention, class names start capitalized, and every subsequent word is capitalized!)
6. Hopefully you will see this screen!
Let's talk quickly about Java syntax, or grammar.
1. The purple words "public class" basically are descriptors of the word HelloWorld that follows. They are declaring that HelloWorld is a class that is public (it can be accessed by other classes).
2. The curly braces define where the class begins and ends. The opening { denotes the beginning of the class and the closing } denotes the end of the class. Your entire class is within these two braces.
So what exactly is a class? First, let us talk about objects (as Java docs describe them).
Objects, in the real world, describe things that have both a state and behavior. For example, your phone's state can be: turned on or turned off while its behavior can be: displaying a game or playing music.
Objects, in programming, are similar. They too have a state and behavior, storing state in fields, also called variables, and behaving via use of methods.
A class, then, is the "blueprint from which individual objects are created." Classes are used to create objects, and classes also define these objects' states and behaviors.
The class we have created together, HelloWorld, is not the best example for what a class is, so here's a pseudo-class that better illustrates what a class:
Let's dissect this class. Pay careful attention to the braces, which have been color coded to demonstrate where each brace's counterpart is.
(Note: Think of these braces like parentheses and brackets in math. They sort of determine the "order of operations" in programming. One misplaced brace can make your code behave strangely! For example: [5(2+1)] = 15. But if you change the placement of the parentheses, [(52+1)] = 53, you get a completely different value.)
The red braces contain the class called Phone. In other words, it contains the blueprint that you use to create Phone objects. This class contains one method called togglePower, which as we have mentioned before is used to express or change the behavior of an object.
The yellow braces denote the beginning and end of the method called togglePower. This method checks the value of the boolean variable "turnedOn" and acts accordingly.
The green braces denote the beginning and end of one conditional if statement, and the blue braces do the same for another conditional if statement.
If you have never programmed before, I know some of these things must be strange to you, so let me explain some of these oddities.
1. Whenever a line begins with //, everything that follows is considered a "comment," meaning that the computer will ignore it. You can use comments to leave a note for yourself (for future reference) or for other programmers( to be able to easily discern the purpose of the following lines of code).
2. The three "statements" that follow the first comment:
All three of these are variables. You may have learned in math that variables are letters or symbols that represent another numerical value.
In programming, a variable can be an integer (negative whole numbers, zero, and positive whole numbers), a boolean (true or false), or String (text), among several others.
As before, the purple text modifies the following word. If we refer to the first statement:
int weight = 0;
This statement is creating an integer variable called "weight" and assigning a value of 0 (using the equal sign - this is called initializing a variable, giving it an initial value).
Refering to the second statement:
boolean turnedOn = false;
This statement is creating a boolean variable called "turnedOn" (by convention, Java variables begin lower case and capitalize every subsequent word, like "firstSecondThirdFourth") and assigning a value of "false."
I'm sure you get the idea and can explain the third statement.
You probably have noticed that each of these statements end with a ;
Well, think of the semicolon as the period in Java. It is another punctuation that will prevent your statements from becoming "run-on statements." As a general rule, whenever you are making a declarative statement, you would use a semicolon. More on this later.
Now one last thing:
There is an equal sign = and there is a double equal sign ==.
The first of these, the assignment operator, assigns the Second item as the value of the First item (i.e. "weight = 0" assigns 0 as the value of weight).
The latter of these is comparitive. It compares the first item with the second item (i.e. "turnedOn == true" DOESN'T assign true as the value of "turnedOn" but rather checks if "turnedOn" IS EQUAL to true).
An alternative explanation can be found here: http://www.javacoffeebreak.com/faq/faq0022.html
_________________
Lesson #1-3.5: A Quick Lesson on Naming:
In Java, you can name classes or variables whatever you want as long as it is not one of those purple words that Java has reserved for its own use (public, static, void, int, etc).
Classes are typically named like so:
ExampleClassName.
Methods and variables are named like so:
exampleMethodName()
and
exampleVariableName.
In the Phone class above, togglePower is just a made-up name.
So until you fill that togglePower method with statements (instrutions), togglePower is just a blank method.
_________________
Lesson #1-4: Writing our first program:
You should have a class called HelloWorld now as shown below:
____________________
Code:
[COLOR="blue"]public class HelloWorld {
}[/COLOR]
____________________
We are now going to add a method called the main method to this class. If you do not remember what a method does, scroll up and do a quick review before proceeding.
A main method (the method by the name of main) is the "entry-point" for your program. It will automatically be invoked (or called) when you run the program - in other words, pressing Play will run the main method. Nothing more.
Dissecting the Main Method:
____________________
Code:
[COLOR="green"]public static void main(String[] args) {
}[/COLOR]
____________________
1. public, static, void - are Java modifiers.
We will discuss these in detail later, but know that these three words are what we would call Java vocabulary, meaning that these words are already pre-defined in Java and you cannot use them as variable names or method names. The three words here describe what type of method main is, the answer to which is, public, static, and void.
2. Methods, in Java, are indicated like below:
I. methodOne()
This above method is called "methodOne" and requires no arguments, or parameters, for the method to work.
II. methodTwo(type argument)
This above method is called "methodTwo" and requires an argument of type type (which can be int, boolean, etc).
When dealing with a method that requires an argument, at the moment it is invoked (or called), it will ask for an input. It will take this input and use it in the method. I will show you how this works in the following examples.
3. Applying #2 to the main method:
main(String[] args)
We know that the main method requires an argument of type String called args. The [] indicates that this is an array, which you can think of as a table of corresponding x and y values. For now, just know that this is what goes in as the argument of the main method every time. You do not need to understand why or what it means just yet. Trust me.
Here is the main method with its braces:
____________________
Code:
[COLOR="green"]public static void main(String[] args) {
}[/COLOR]
____________________
Now are you able to tell me where this main method begins and ends?
It begins where the first brace opens { and ends where the second brace closes }.
Let's now insert this method into the HelloWorld class.
__________________
Code:
[COLOR="blue"]public class HelloWorld {[/COLOR][COLOR="green"]
public static void main(String[] args) {
}[/COLOR]
[COLOR="blue"]}[/COLOR]
__________________
If you were to copy this code into eclipse and pressed play, it would compile successfully and run.
The problem is... the main method is empty. It won't do anything yet.
So let's write our first statement:
__________________
Code:
[COLOR="red"]System.out.println("Hello XDA!");[/COLOR]
____________________
Pretty basic right? No? Let's dissect it.
1. System refers to a class in the library that I've mentioned before (from which you can import code), also known as the API (Application Programming Interface).
2. The periods between "System" and "out" & "out" and "println" represent hierarchy.
For example:
HelloWorld.main(args);
would invoke the main method in the class HelloWorld.
3. println requires an argument. Inside it, you can type both literals and variables.
You indicate literals with quotes: " " and variable names can just be written.
I will show you an example on this.
(Note: If you want to know more about the System.out.println and how it works at the lowest level, you can refer to this site: http://luckytoilet.wordpress.com/2010/05/21/how-system-out-println-really-works/
But I recommend not doing so until you have a very thorough understanding of Java. )
I know it's frustrating for some of you to be writing code that you don't yet fully understand, but just bear with me for a while. Everything will become clear.
Now we insert the statement into the Main Method to get the full working code:
________________
Code:
[COLOR="blue"]public class HelloWorld {[/COLOR]
[COLOR="green"]public static void main(String[] args) {[/COLOR]
[COLOR="red"]System.out.println("Hello XDA!");[/COLOR]
[COLOR="green"]}[/COLOR]
[COLOR="blue"]}[/COLOR]
________________
Copy and paste this into eclipse and press play! You should see:
What's going on here? When you press play, the main method is called. The main method has one statement (System.out...)
which displays "Hello XDA!"
NOTE: To make it easier to tell which brace goes corresponds with which, press Ctrl + Shift + F. This auto-formats your code!
Day 3
Lesson #1-5: More on Variables:
Refer to the phone pseudo-class that I created as an example:
The three fields (also called variables) that I've created are: an integer variable called weight, a boolean variable called turnedOn, and a String object called color.
Today, we will discuss these in detail.
There are four kinds of variables (also called fields. < REMEMBER THIS OR YOU WILL BE CONFUSED):
First, recall that Classes are blueprints for creating objects. Every time you create an object with this class, you are instantiating (creating an instance of) this class. In other words, if you were to use the Phone class to create Phone objects, every time you created a new Phone object, you would have a new instance of the Phone class.
With each of these instances, variables that are defined in the class are also created. So each of these Phone instances will now have the weight, turnedOn, and String fields. When you make adjustments to a specific phone by, for example, adding 1 to weight, IT WILL ONLY AFFECT THAT PHONE. The other phone's weights are not affected. This means that each of these Phone objects have their own sets of fields (variables) that are independent from each other.
This is because the variables (fields) are...
1. Instance variables. When a variable is declared without the keyword "static" (i.e. "int weight = 0" rather than "static int weight = 0"), you are creating instance variables, which have unique values for each instance that they belong to.
What if you wanted to be able to change the values of these variables (again, fields) and affect every single Phone object that you created?
Then you create what we call...
2. Class variables. Any time that you declare a variable with the keyword "static" ("static int weight = 0"), you are basically saying that there will only be a single copy of this variable even if there are multiple Phone objects.
Have a look at the following example. It will (hopefully) clear some things up.
Code:
[COLOR="Blue"]
class AndroidPhone{
[/COLOR]
[COLOR="SeaGreen"]
//Declare and Initialize Variables (REMEMBER // IS A COMMENT INDICATOR).
//Note: doubles are used for decimal values (int are used for whole numbers).[/COLOR]
[COLOR="Blue"]
static double versionNumber = 2.2;
boolean turnedOn = false;
final String color = "blue";
public static void main(String[] args) {
...[/COLOR]
Pretend that we live in a world where you can make real life changes happen with Java.
Let's say Samsung has created 10 Android Phones using the AndroidPhone class above.
The next day, 10 users purchase these phones. We will label them phoneOne, phoneTwo, phoneThree, and so on.
When Samsung releases an update, they would want all 10 of these devices to get the update together (I know this isn't a very realistic scenario, just pretend)!
So they would use Eclipse to say:
Code:
[COLOR="SeaGreen"]//This line and the following line are comments (//).
//This is a method that updates phones:[/COLOR]
[COLOR="blue"]
static void updatePhones() {
versionNumber = 2.3;
}[/COLOR]
(Note: If you take the equal sign too mathematically, it will confuse you. So, whenever you give a value to a variable, try and interpret it like this:
"versionNumber is NOW EQUAL TO 2.3." It will make it easier to conceptualize.)
Recall that we created a static double called versionNumber. This means that when you change the value of versionNumber once, it will affect every instance of the AndroidPhone class, meaning that all 10 AndroidPhones will receive the update immediately!
It makes sense to create a static variable for the versionNumber, but it does not make sense to create a static variable for the power! You don't want the user to be able to turn off other people's phones - you want each phone to have its own "turnedOn" boolean (True/False variables).
How, then, do you select which phone will turn on or off?
It's rather simple!
Remember that we labeled each of these phones (phoneOne, phoneTwo, etc).
Code:
[COLOR="SeaGreen"]//If you are confused by the == and =, you should scroll up and review!
//Ctrl + F and search for "double equal sign"
//ALWAYS Pay attention to which brace corresponds with which![/COLOR]
[COLOR="Blue"]static void pressPowerButton{[/COLOR]
[COLOR="Red"]if (phoneOne.turnedOn == false){
phoneOne.turnedOn = true;
}[/COLOR]
[COLOR="Orange"]if (phoneOne.turnedOn == true){
phoneOne.turnedOn = false;
}[/COLOR]
[COLOR="seaGreen"]//Remember with equal signs:
//Think: "NOW EQUALS"[/COLOR]
[COLOR="blue"]}[/COLOR]
...
Now the final variable, "final String color = "blue";"
String means text, and we are creating a color variable with the value of "blue" (quotes indicate literals. no quotes would give color the value of a variable called blue).
The color of these 10 AndroidPhones will never change (ignore spraypaint and cases). So, we just indicate that they are "final."
In case you forgot (or skipped) how we got into the discussion of static, non-static, and final variables, we were talking about the four types of variables in Java.
Moving on to the third variable!
We've been creating variables that belonged to the class as a whole. Now we will talk about...
3. Local Variables. If you create a variable within a method, it will only belong to that method. If you try to invoke that variable by name in other methods, Eclipse will happily and truthfully inform you that the variable doesn't exist!
Example:
Code:
[COLOR="Blue"]public class localVariables {[/COLOR]
[COLOR="seaGreen"]//This is a Class-wide variable:
//You can use it in any method.[/COLOR]
static double pi = 3.14;
[COLOR="Red"] public static void main(String[] args) {[/COLOR]
[COLOR="seaGreen"] //This is a local variable
//called hello.[/COLOR]
double hello = 2.0;
[COLOR="seaGreen"] //This means hello
//is NOW EQUAL TO
//pi + hello;[/COLOR]
hello = pi + hello;
[COLOR="Red"]}[/COLOR]
[COLOR="DarkOrange"] static void secondaryMethod(){[/COLOR]
double hello = 4.0;
hello = pi + hello;
[COLOR="DarkOrange"]}[/COLOR]
[COLOR="blue"]}
[/COLOR]
There are three variables (NOT TWO) in this class.
1. The class variable called pi.
2. The local variable called hello in the main method.
3. The local variable called hello in the secondaryMethod.
REMEMBER:
When you declare and initialize a variable in a method, that variable will only belong to that method!
Let us finish with the discussion of the final type of variable:
4. Parameters. It is possible to use a local variable in multiple methods. This is how:
Code:
[COLOR="Blue"]public class localVariables {[/COLOR]
//This is a Class-wide variable:
//You can use it in any method.
static double pi = 3.14;
[COLOR="Red"] public static void main(String[] args) {[/COLOR]
[COLOR="seaGreen"] //This is a local variable
//called hello.[/COLOR]
double hello = 2.0;
[COLOR="seaGreen"] //This means hello
//is NOW EQUAL TO
//pi + hello;[/COLOR]
hello = pi + hello;
//invoke secondaryMethod()
secondaryMethod(hello);
[COLOR="Red"]}[/COLOR]
[COLOR="DarkOrange"] static void secondaryMethod(double hello){[/COLOR]
hello = hello + 5;
[COLOR="DarkOrange"]}[/COLOR]
Whenever you invoke a method, you use the "methodName();" statement.
If this method requires a parameter, the code will not successfully run (it will give you errors for that method).
The secondaryMethod requires a "double (decimal number)" to proceed. So you must pass in a double when you invoke the method...
Code:
[COLOR="DarkOrange"]secondaryMethod(hello);[/COLOR]
What this does (when you invoke secondaryMethod from the main method):
It takes the hello double from the main method and "sends it over" to the secondaryMethod, which labels it as a LOCAL VARIABLE called hello. So there are TWO hello variables involved, just like before. NOT ONE.
What does this mean?
Main method's hello will have a value of 5.14.
Secondary method's hello will have a value of 10.14.
Confused? PM me.
__________________
Just to clear things up regarding methods and invocation.
In Java, the code will typically be read from top to bottom.
As the programmer, you are basically doing one of two things:
1. Setting up things to be invoked.
2. Invoking (calling) things.
When you create a new method, let's say it's named methodName, it will be ignored until you explicitly call it into action by writing:
methodName();
You can see an example of this if you compare the examples for Local Variables and Parameters. In the Local Variables example, I setup the secondaryMethod() but I never call it to happen. So nothing inside it actually gets
reached when you press Play. However in the Parameters example, I state: secondaryMethod(hello);. This calls the secondaryMethod that I have setup, so everything inside will be reached and ran.
The only exception is the main method, because it is IMPLICITLY called when you press Play in Eclipse.
You can create as many methods as you want. They are there for your benefit: to group and organize your statements, and to make these statements easily accessible without re-writing each line of code.
Lesson #1-6: Fun(?) with Math
Math is pretty straightforward. Let's begin with a few arithmetic operators.
Code:
+ : addition
- : subtraction
/ : division
* : multiplication
% : returns the value of the remainder.
Examples:
Code:
class MathLearning {
[COLOR="SeaGreen"] // These are class-wide variables:
[/COLOR] static int a = 10;
static int b = 15;
static int c = 22;
[COLOR="Blue"] public static void main(String[] args) {
[/COLOR]
[COLOR="SeaGreen"]// The following are local variables
// They belong to the main method only.[/COLOR]
int result;
int resultTwo;
int resultThree;
int resultFour;
int resultFive;
[COLOR="SeaGreen"] // These assign values to the five "result variables".
// (You could've assigned when you declared them above)[/COLOR]
result = a + b;
resultTwo = a - b;
resultThree = a * c;
resultFour = c / b;
resultFive = c % b;
[COLOR="Green"] //The following statements
//invoke the blahBlahBlah method
//by "inputting" the required
//integer parameter.
[/COLOR]
blahBlahBlah(result);
blahBlahBlah(resultTwo);
blahBlahBlah(resultThree);
blahBlahBlah(resultFour);
blahBlahBlah(resultFive);
[COLOR="blue"] }
[/COLOR]
[COLOR="DeepSkyBlue"] public static void blahBlahBlah(int output) {
[/COLOR]
[COLOR="SeaGreen"] //This method takes the parameter
//and creates a variable called output.
//This variable is then displayed
//in the below statement.
[/COLOR]
System.out.println(output);
[COLOR="DeepSkyBlue"]}[/COLOR]
}
Before you copy and paste the code to Eclipse, let's see if you know what the code will do.
Try and follow the code to see if you can write down the five outputs.
If you get stuck, check below:
1. We first declare a new class called MathLearning.
2. Next we declare 3 class-wide variable integers: a, b, and c.
3. We move on to create the main method with its typical parameter (String[] args).
4. Then we create 5 integers. Unlike before, we don't initialize (meaning we don't give them a starting value).
5. We assign values to the 5 integers that we created in step 4.
6. The statements that begin with blahBlahBlah... are invoking the blahBlahBlah method with a required integer parameter.
7. We setup the blahBlahBlah(int output) method.
Important notes:
The location of the blahBlahBlah(int output) method does not matter. We can put it above the main method or below the main method.
The main method, if you recall, will ALWAYS run first.
When the statements from step 6 above are "reached" (again, think Top to Bottom in the main method), Java will look for the method by the name of blahBlahBlah and follow
the instructions contained therein.
The resulting output is...
Code:
25
-5
220
1
7
Wait a second. Everything makes sense, but resultFour is completely off!
22/15 is not 1... or is it?
Remember that the variables c and b (22 and 15) are both integers.
resultFour, which is calculated using c / b is also an integer. This means that when the calculation happens, the computer will
round down to the nearest whole number to keep the value of resultFour as an integer, as in the remainder is just thrown away.
This is why you do not see a decimal result, but a lower value of 1.
The solution? Let's change all the int declarations to double declarations.
There's another problem. We get five lines of numbers, but they aren't labeled.
If we want each of the lines to display:
Result 1 is 25.
Result 2 is -5.
Result 3 is 220.
...
...
What could we do?
There's only one line that outputs text (System.out.println...) within the blahBlahBlah class, and it treats all the inputs the same way.
It has no idea of telling whether a given input is result or resultFive.
This is when we use a counter.
To do so, we will learn... two more operators today:
Code:
++ : adds one to the variable.
-- : subracts 1 from the variable.
There are differences between:
Code:
//This is the pre-increment operator
++variable;
and
Code:
/This is the post-increment operator
variable++;
But the latter is much more commonly used and you can (for the most part) accomplish the exact same things without the former,
so we won't waste time discussing it at the moment.
Example of a counter follows:
Code:
class Counter {
[COLOR="SeaGreen"] //Create a class-wide integer called counter.
[/COLOR] static int counter = 0;
[COLOR="Blue"]public static void main(String[] args) {[/COLOR]
[COLOR="SeaGreen"]//This is a loop. It will keep
//repeating everything contained
//inside the loop while the
//conditions are met![/COLOR]
[COLOR="Orange"]while (counter < 10){[/COLOR]
[COLOR="SeaGreen"]//This post-increment operator adds 1.[/COLOR]
counter++;
[COLOR="SeaGreen"] //Display the new counter value.[/COLOR]
System.out.println(counter);
[COLOR="ORange"]}[/COLOR]
[COLOR="Blue"]}[/COLOR]
}
Let's dissect this class.
1. We declare a Counter class.
2. We create an integer called counter with initial value of zero.
3. We create a main method.
4. Inside the main method, we create a "while loop" (we will learn this soon!)
5. The while loop, as long as counter is below 10, will add one, and display that number.
int counter starts at zero. As soon as Java reaches the while loop, it will add one, and print the new value of counter: 1.
int counter is now 1. The loop will add 1 again and print the new value of counter: 2.
int counter is now 2. The loop will add 1 again and print the new value of counter: 3.
...
int counter is now 10. The while (counter < 10) condition is no longer met, so the loop ends.
________________
Now let's apply this to the first MathLearning class example:
Code:
class MathLearning {
[COLOR="SeaGreen"]// These are class-wide variables:[/COLOR]
static double a = 10;
static double b = 15;
static double c = 22;
[COLOR="SeaGreen"] //Setup a counter.
[/COLOR] static int counter = 0;
[COLOR="Blue"] public static void main(String[] args) {
[/COLOR]
[COLOR="SeaGreen"]// The following are local variable
// They belong to the main method only.[/COLOR]
double result;
double resultTwo;
double resultThree;
double resultFour;
double resultFive;
[COLOR="SeaGreen"]// These assign values to the five "result variables".[/COLOR]
result = a + b;
resultTwo = a - b;
resultThree = a * c;
resultFour = c / b;
resultFive = c % b;
[COLOR="SeaGreen"]//The following statements
//invoke the blahBlahBlah method
//by "inputting" the required
//integer parameter.[/COLOR]
blahBlahBlah(result);
blahBlahBlah(resultTwo);
blahBlahBlah(resultThree);
blahBlahBlah(resultFour);
blahBlahBlah(resultFive);
[COLOR="Blue"]
}[/COLOR]
[COLOR="RoyalBlue"]public static void blahBlahBlah(double output) {[/COLOR]
[COLOR="SeaGreen"]//Add one to counter.[/COLOR]
counter++;
[COLOR="SeaGreen"]//This method takes the parameter
//and creates a variable called output.
//This variable is then displayed
//in the below statement.[/COLOR]
System.out.println("Result " + counter + " is " + output);
[COLOR="RoyalBlue"]}[/COLOR]
}
Compare this to today's first example.
1. I changed all the int declarations to double declarations to show decimal values.
2. I created a static int called counter (if this is not static, each time that the method is invoked,
the value of counter will be 1, as each instance of this method will get its own counter integer), and used it to label each line of output.
The console will display:
Code:
Result 1 is 25.0
Result 2 is -5.0
Result 3 is 220.0
Result 4 is 1.466...
Result 5 is 7.0
3. Let's talk about this:
Code:
System.out.println("Result " + counter + " is " + output);
You are familiar with System.out.println();
But what are the pluses used for?
In this case, these pluses are not additions. They just let you combine different variables and literals into one String piece that can be displayed
using System.out.println();
So what ("Result " + counter + " is " + output) is really showing is:
"Result counter is output"
And we will conclude Day 4 here.
Thanks for reading!
Confused? PM me. I will reply ASAP!
Lesson #1-7: More Fun with Math
A quick review:
In Java, you will frequently see statements written like so:
Given that number is an integer...
Code:
number = number + 5;
This tends to confuse many beginning programmers, because they are missing the fundamental purpose of the equal sign.
Like I've said before, the equal sign does not just state equality; instead, it is used to ASSIGN a value.
In other words, it doesn't just state that the operand on the left and the value on the right are equal. Instead, it says that the operand is now equal to the value.
Interpreting the example above, you should think to yourself, 'number is now equal to number + 5.' This will save you a lot of headache.
If you understand this, here is a list of equivalent expressions that will save you some time in programming:
Code:
number = number + 5;
//can be written as:
number += 5;
number = number - 5;
//can be written as:
number -= 5;
number = number * 5;
//can be written as:
number *= 5;
number = number / 5;
//can be written as:
number /= 5;
Lesson #1-8: Randomization
Predictability makes for boring games. If you want games to challenge players, you will want to use randomization.
Let's use TUMBL as an example. For those of you who are not familiar with the game, click here.
Each row is generated randomly, meaning that the player will not be able to figure out a pattern that lets them stay alive longer.
Stars are generated randomly on the left or right side of the screen.
Power-ups appear randomly.
And so on.
So how do you integrate randomization to a game?
It's quite simple. Take a look at this example class:
Code:
[COLOR="SeaGreen"]//In this class, we will create a Random object called rand.
[/COLOR]
[COLOR="Blue"]class Randomization {
[/COLOR]
[COLOR="RoyalBlue"] public static void main(String[] args) {[/COLOR]
Random rand = new Random();
[COLOR="RoyalBlue"]}[/COLOR]
[COLOR="Blue"]}[/COLOR]
In this class named Randomization, we create a Random object called rand.
Let's break up this statement:
Code:
Random rand
think of this just like:
Code:
int number
You are creating a new object called rand using the type Random.
The second part of the statement:
Code:
= new Random()
assigns a new Random object with a default seed (I will explain seed in a second) as the value of the newly-created rand.
In other words...
you are basically telling the computer:
"I want to create a Random object called rand. Use the Random class to create this new object."
If you are confused, that's okay. We will go into object creation and constructors in a lot more detail in the coming lessons.
Just know that:
Code:
Random rand = new Random();
creates a new Random object called rand (you can change this name).
Mini Lesson : Imports
When you copy and paste the following class into Eclipse:
Code:
//In this class, we will create a Random object called rand.
[COLOR="Blue"]class Randomization {
[/COLOR]
[COLOR="RoyalBlue"]public static void main(String[] args) {[/COLOR]
Random rand = new Random();
[COLOR="RoyalBlue"]}[/COLOR]
[COLOR="blue"]
}
[/COLOR]
You will see red squiggly lines below the word Random, indicating the presence of an error:
This error occurs because the "Random class" is not recognized by your current class, Randomization.
Earlier, I mentioned that the src folder contains all your Java code and that the JRE System Library contains importable code
that you can incorporate into your own projects.
Think of this Library as one containing "books" (Java classes). When you write an essay and you reference a book, you cite it.
Same with Java. When you use a "book" (Java classes) from the Library, you must state that you are using this "book."
This is accomplished by importing.
How do we import? It's pretty simple.
1. The easiest way is to press:
Code:
Ctrl + Shift + O
This will automatically import the class that the compiler thinks you are most likely to use.
2. Another way is to put your mouse over the words that show an error (in this case Random) and click on the quick fix that suggests importing
the Random class from Java.util.
Either way, when you successfully import, the error will disappear, and you will see the following above your class name:
Code:
import java.util.Random;
- indicating that your class makes use of this Random class.
The full class, after importing, will look like this.
Code:
[COLOR="SeaGreen"]//Here we import the java.util.Random class.[/COLOR]
[COLOR="Red"]import java.util.Random;
[/COLOR]
[COLOR="SeaGreen"]//In this class, we will create a Random object called rand.[/COLOR]
[COLOR="Blue"]class Randomization {[/COLOR]
[COLOR="RoyalBlue"]public static void main(String[] args) {[/COLOR]
[COLOR="SeaGreen"] //This creates a new Random object.[/COLOR]
Random rand = new Random();
[COLOR="RoyalBlue"]}[/COLOR]
[COLOR="Blue"]}[/COLOR]
Well, now that we have a random object called rand, we can use it to randomize things.
The easiest method we will learn is:
Code:
.nextInt(int maxPlusOne)
What does this method do?
When you call this from a random object such as rand like so:
Code:
rand.nextInt(11);
It will generate an integer between 0 and 10.
Using this, you can simulate chance and probability.
How? We will go over probability and if statements tomorrow!
If you have any questions, contact me!
If you are learning from and enjoying the tutorials, please support Kilobolt Studios!
And Like us on Facebook to receive updates when a new lesson is posted!
Lesson #1-9: If and else statements
In Java, we can control the "flow" of the program by using conditional statements.
Let's take a look at this simple example.
Code:
[COLOR="Blue"]class DrinkingAgeTest {
[/COLOR]
[COLOR="SeaGreen"]//Class-wide integer age.
[/COLOR]static int age = 18;
[COLOR="RoyalBlue"] public static void main(String[] args) {
[/COLOR]
[COLOR="Red"]if (age >= 21){
System.out.println("You may drink.");
}[/COLOR]
[COLOR="DarkOrange"]else{
System.out.println("You are too young to drink.");
System.out.println("Come back in " + (21 - age) + " years.");
}[/COLOR]
[COLOR="RoyalBlue"]}[/COLOR]
[COLOR="Blue"]}[/COLOR]
This is a pretty simple class. Let me explain some of the things we have here.
1. class DrinkingAgeTest creates a class called DrinkingAgeTest.
2. We then create a static integer age (this does not have to be static if it is placed inside the main method).
3. Of course we create a main method, as all Java programs will look for this as a starting point.
4. Now the interesting parts:
Code:
[COLOR="Red"]if (age >= 21){
System.out.println("You may drink.");
}[/COLOR]
[COLOR="DarkOrange"]else{
System.out.println("You are too young to drink.");
System.out.println("Come back in " + (21 - age) + " years.");
}[/COLOR]
Meet the if statement. It is written like so:
Code:
if (conditionOne){
}
//You can have as many if statements as you want.
if (conditionTwo){
}
//If none of the previous conditions are met, it carry out instructions in "else"
else{
}
When Java encounters the if statement, it checks each condition to see if it is satisfied (true).
If so, it carries out everything inside the braces for that if statement. If not, the statement is completely skipped.
Applying this to the example class, the compiler checks if age, which is 18, is greater than or equal to 21.
It is not, so it skips the line:
Code:
System.out.println("You may drink.");
Since none of the previous conditions are met, it automatically goes into the else statement, which outputs:
Code:
You are too young to drink.
Come back in 3 years.
Note: If you have multiple "if" statements, each of them is checked to see if true. If only one of the conditions can be true (i.e. the conditions you are testing for are mutually exclusive), it is therefore more efficient to use the "else if" statement like so:
Code:
if (conditionOne){
doThis();
}
else if(conditionTwo){
doThat();
}
else{
doOther();
}
Now we are going to apply this to simulate probability.
Lesson #1-10: Simulating Probability: Relational Operators
In the lesson #1-8, we created a random object called rand and invoked the method "nextInt."
Code:
rand.nextInt(11);
Recall that the above generates a number between 0 and 10 (11 numbers starting with zero).
Now let's simulate probability, starting with a simple example.
Code:
import java.util.Random;
[COLOR="SeaGreen"]//Let's simulate a coin toss![/COLOR]
[COLOR="Blue"]class Simulation {
[/COLOR]
[COLOR="RoyalBlue"] public static void main(String[] args) {[/COLOR]
[COLOR="SeaGreen"]//Create a Random object called rand.
[/COLOR]
Random rand = new Random();
[COLOR="Red"] if (rand.nextInt(2) == 1){
System.out.println("heads");
}[/COLOR]
[COLOR="DarkOrange"]
else if (rand.nextInt(2) == 0){
System.out.println("tails");
}[/COLOR]
[COLOR="Orange"] else if (rand.nextInt(2) == 2){
System.out.println("side. Fix your random number generator!");
}[/COLOR]
[COLOR="RoyalBlue"] }
[/COLOR]
[COLOR="Blue"]}[/COLOR]
This is also a pretty straightforward class. We use the random number generator to create an number between 0 and 1 (inclusive) and set it equal to a newly created integer: coinInt.
We arbitrarily decide that the value of 1 is equal to heads and the value of 0 is equal to tails. Now we test the value of coinInt using else if statements (mutually exclusive events) and display the appropriate string (text).
Since the value of coinInt should never (theoretically) be 2, I created a third statement that is only read if coinInt does somehow become 2 (it should be as common as landing a coin on its side).
In these two lessons, we used two operators: == and >=.
Here are all six relational operators:
Code:
== equal to
!= not equal to
> greater than
>= greater than or equal to
< less than
<= less than or equal to
Lesson #1-11: Conditional Operators and Our First Game
In this lesson, we are going to create a simple game. Oh, don't get too excited. By simple, I mean simple.
Before we do that, here's a quick lesson on conditional operators:
Code:
|| means or.
&& means and.
When you have an if statement like below:
Code:
if (conditionOne == true || conditionTwo == true){
doThis();
}
Then if either conditionOne or conditionTwo is true, it will invoke the "doThis()" method;
When you have a statement like this:
Code:
if (conditionOne && conditionTwo){
doThat();
}
Then both conditionOne and conditionTwo must be satisfied before "doThat" method is called.
NOTE: When you just write a boolean (variables with value of either true or false, such as conditionOne) without stating: == true or == false, it is assumed that you actually wrote boolean = true.
In other words:
Code:
if (condition == true){
doThis();
}
and
Code:
if (condition){
doThis();
}
Are equivalent.
Now back to our game!
Here is how the game works. You roll a 6-sided die. If you land a 1 or 2 you lose. If you get a 3, 4, or 5, you roll again. If you get a 6, you win.
To write good programs, you have to plan beforehand. You should think the following:
1. I need a random number generator.
2. I should test if:
I. a number is less than or equal to 2.
II. if not, I should test whether if that number is between 3 and 5 (inclusive)
III. if not, I should test whether if that number is 6.
3. I should carry out an appropriate response.
Simple. Now let's create this class.
Code:
[COLOR="DarkOrchid"]import java.util.Random;[/COLOR]
[COLOR="SeaGreen"]//The greatest game ever made follows.
[/COLOR]
[COLOR="Blue"]class BySimpleIMeanSimple {
[/COLOR]
static int dieValue;
[COLOR="RoyalBlue"] public static void main(String[] args) {
[/COLOR]
rollDie();
[COLOR="RoyalBlue"] }
[/COLOR]
[COLOR="DeepSkyBlue"] static void rollDie(){
[/COLOR]
Random rand = new Random();
[COLOR="SeaGreen"] //Assign a random number between 1 and 6 as dieValue
[/COLOR] dieValue = rand.nextInt(6) + 1;
System.out.println("You rolled a " + dieValue);
[COLOR="SeaGreen"] //Why add 1? Think about it.
[/COLOR]
testDieValue(dieValue);
[COLOR="DeepSkyBlue"] }
[/COLOR]
[COLOR="MediumTurquoise"] static void testDieValue(int dieValue){
[/COLOR] [COLOR="Red"] if (dieValue <= 2){[/COLOR]
System.out.println("You Lose.");
[COLOR="Red"]}[/COLOR]
[COLOR="Orange"]else if (dieValue == 3 || dieValue == 4 || dieValue == 5){[/COLOR]
System.out.println();
System.out.println("Rerolling.");
System.out.println();
rollDie();
[COLOR="Orange"]}[/COLOR]
[COLOR="SandyBrown"]else if (dieValue == 6){[/COLOR]
System.out.println("You win! Congratulations!");
[COLOR="SandyBrown"]}[/COLOR]
[COLOR="MediumTurquoise"] }
[/COLOR]
}
I want you to spend time with this class. Copy and paste it into eclipse and play around with it.
We will discuss this class in detail in tomorrow's lesson!
You might be surprised what you have already learned!
A tip: if you don't know what the purpose of a certain line of code is, it is a good idea to remove it temporarily (comment it out and run it). You can compare results with and without the statement =)
If you have any questions:
Pm me or email me!
Lesson #1-12: Analysis of the BySimpleIMeanSimple class
Looking at yesterday's "game" in-depth.
Yesterday, we created our very first game. Now we will dissect the class behind it.
Here's the code:
Code:
[COLOR="DarkOrchid"]import java.util.Random;[/COLOR]
[COLOR="SeaGreen"]//The greatest game ever made follows.
[/COLOR]
[COLOR="Blue"]class BySimpleIMeanSimple {
[/COLOR]
static int dieValue;
[COLOR="RoyalBlue"] public static void main(String[] args) {
[/COLOR]
rollDie();
[COLOR="RoyalBlue"] }
[/COLOR]
[COLOR="DeepSkyBlue"] static void rollDie(){
[/COLOR]
Random rand = new Random();
[COLOR="SeaGreen"] //Assign a random number between 1 and 6 as dieValue
[/COLOR] dieValue = rand.nextInt(6) + 1;
System.out.println("You rolled a " + dieValue);
[COLOR="SeaGreen"] //Why add 1? Think about it.
[/COLOR]
testDieValue(dieValue);
[COLOR="DeepSkyBlue"] }
[/COLOR]
[COLOR="MediumTurquoise"] static void testDieValue(int dieValue){
[/COLOR] [COLOR="Red"] if (dieValue <= 2){[/COLOR]
System.out.println("You Lose.");
[COLOR="Red"]}[/COLOR]
[COLOR="Orange"]else if (dieValue == 3 || dieValue == 4 || dieValue == 5){[/COLOR]
System.out.println();
System.out.println("Rerolling.");
System.out.println();
rollDie();
[COLOR="Orange"]}[/COLOR]
[COLOR="SandyBrown"]else if (dieValue == 6){[/COLOR]
System.out.println("You win! Congratulations!");
[COLOR="SandyBrown"]}[/COLOR]
[COLOR="MediumTurquoise"] }
[/COLOR]
}
1. The first line is simple: import the Random class.
2. We then declare the name of the class: BySimpleIMeanSimple
3. Then a static integer called dieValue, which will hold the value of the rolled die is created
4. Next, we create the main method, which just invokes a method called rollDie();
5. The rollDie() method is then created. It has the following parts.
I. Creation of the Random object called rand.
II. Assignment of a random number between 0 and 5 (+1 since numbers range from 1 to 6 on a die) to the dieValue integer we created earlier.
III. It uses System.out.println to display the value of the integer dieValue.
IV. It invokes the method testDieValue(), which is defined below the rollDie() method. This testDieValue() method requires an integer parameter, so we input the new dieValue, which contains the random number between 1 and 6.
6. Next we declare the testDieValue() method. This is where the Control Flow statements happen (we control the way that the program proceeds based on conditional statements).
It takes the value of integer dieValue and then carries out the appropriate if statement.
I. If the value is less than or equal to 2, the player loses, so it displays, "You lose."
II. If the value is exactly 6 (==), it displays "You Win! Congratulations!"
III. If the value is 3 or 4 or 5 (This could've been written in many ways, such as: if (dieValue >= 3 && dieValue <= 5)...), it rerolls, invoking again the rollDie() method, which creates a random number and assigns it as the value of dieValue and then uses this value to invoke the testDieValue();
Someone asked earlier, what is the purpose of the: System.out.println();
Well, it is there to create an empty line in the console (where the output is displayed). It helps organize the way the program "speaks" to you.
NOTE: Make sure you are keeping up with the braces. When you do actually programming, braces won't be color coded to show you where the boundaries of each class or method are!
Lesson #1-13: Switches in Java
Java, much like railroad tracks, incorporates switches to direct the path of execution.
We will look at switches using an example that we have used before: a coin toss.
NOTE: Make sure that the class name in the Package Explorer to the left side of the screen on Eclipse matches that of the one stated in the code. Otherwise, you will get an error. The reason for this is that when you press Play, Eclipse looks for the class that with the name of the file that you are executing, and it will not be able to locate it.
(i.e. You should create a class named CoinTossSwitch.java and copy this code):
Code:
[COLOR="Purple"]import java.util.Random;[/COLOR]
[COLOR="Blue"]class CoinTossSwitch {
[/COLOR]
[COLOR="RoyalBlue"]public static void main(String[] args) {[/COLOR]
Random rand = new Random();
int randomInt = rand.nextInt(2);
System.out.println(randomInt);
[COLOR="Green"] switch (randomInt){[/COLOR]
case 1: System.out.println("Heads!");
break;
case 0: System.out.println("Tails!");
break;
[COLOR="Green"] }[/COLOR]
[COLOR="RoyalBlue"] }[/COLOR]
[COLOR="Blue"]}[/COLOR]
Let's examine the switch in detail:
Code:
[COLOR="Green"] switch (randomInt){[/COLOR]
case 1: System.out.println("Heads!");
break;
case 0: System.out.println("Tails!");
break;
[COLOR="Green"] }[/COLOR]
__________
As you can tell, the format of a switch is as follows:
switch (variable){
case 1: doThis();
break;
case 2: doThat();
break;
case 3: doOther();
break;
}
Inside the parentheses (), you write the variable name that you are testing.
If this variable is an integer, you write:
case 1, case 2, and so on.
If it is is a boolean, you would write:
case true, case false.
If it is a String, you would write whichever values that the String variable can take.
For example, if your String can contain any color value, you would use:
case "red", case "blue", and so on.
The purpose of the "break;" is to separate the cases. If you forget to put the break, the code will not stop executing after a case is satisfied. It will keep going.
__________
Applying this to the example code above,
1. We are testing an integer called randomInt.
2. If randomInt is 0, the computer will output: "Heads!" and break the case.
3. If randomInt is 1, the computer will output: "Tails!" and break the case.
What would be a practical application of this code? Let's say that we have a game in which the player can select one of three characters.
Let's name them Mario, Luigi, and Yoshi.
We would then create a String variable that holds the value of the name, and then use a switch to carry out the appropriate response.
Note: The following will only work in Java 1.7. If you have 1.6 or below, just look through it to see what it is doing!
Code:
[COLOR="Green"]//Sample Character Selection Screen
[/COLOR]
[COLOR="Blue"]class CharacterSelect {
[/COLOR]
[COLOR="RoyalBlue"] public static void main(String[] args) {
[/COLOR]
String currentCharacter = "Mario";
int maxLife;
int maxJump;
int maxSpeed;
[COLOR="Red"] switch (currentCharacter){
[/COLOR]
[COLOR="DarkOrange"]case "Mario":[/COLOR]
System.out.println("You have selected Mario!");
maxLife = 70;
maxJump = 50;
maxSpeed = 25;
[COLOR="DarkOrange"]break;[/COLOR]
[COLOR="Olive"] case "Luigi": [/COLOR]
System.out.println("You have selected Luigi!");
maxLife = 40;
maxJump = 70;
maxSpeed = 30;
[COLOR="Olive"]break;[/COLOR]
[COLOR="Lime"]case "Yoshi": [/COLOR]
System.out.println("You have selected Yoshi!");
maxLife = 50;
maxJump = 30;
maxSpeed = 40;
[COLOR="Lime"]break; [/COLOR]
[COLOR="Red"]}[/COLOR]
[COLOR="RoyalBlue"]}[/COLOR]
[COLOR="Blue"]}[/COLOR]
We store the current character's value in the String variable currentCharacter and use a switch to change the character's attributes.
Tomorrow we will discuss looping. We are getting closer to developing a game, so hang tight and stay tuned!
If you want to thank me for the guide, you can press Thanks or donate here or download TUMBL +!
Thank you guys for reading and I'm here if you have any questions!
PM me or email me!
Lesson #1-14: Introduction to Loops
In the previous lessons, we discussed conditional statements (such as the if statement) that carry out an appropriate response depending on the condition satisfied.
We will now begin covering loops, which are also often conditionally executed.
First, what is a loop? Well, as the name suggests, loops refer to code that is executed multiple times.
When is a loop useful? A very simple scenario: if you wanted to output a specific line of text a hundred times.
One solution to this would be to copy and paste the System.out.println(...) statement 100 times.
This is not very efficient for both the programmer and the computer.
Instead, the proper solution would be to utilize a loop and a counter to execute one line of System.out.println(...) 100 times.
A more practical (and relevant) example is the game loop. We will have a hefty discussion about this crucial loop later, but here's a little preview of what is coming.
Games, despite popular belief, are very mechanical in nature. Behind the fancy graphics and beautiful sounds, there is a "heart" that causes the game to "update" its contents (move all in-game objects to the new location based on their velocity) and to render the graphics(re-draw the objects in the newly defined location). The game loop is the closest thing to this heart.
Like I said before, loops tend to be conditional. The game loop is too.
Here's an example of a fake game loop.
Code:
[COLOR="DarkRed"]while (playerAlive == true){[/COLOR]
updateGame(deltaTime);
renderGame(deltaTime);
[COLOR="DarkRed"]}[/COLOR]
In this example of the while loop, if the condition playerAlive == true is satisfied, the updateGame() method and the renderGame() method will be executed.
The updateGame() method will handle things like collision or physics, while renderGame() method will display the characters and environment in the current location.
I added a deltaTime parameter to the methods, which is typically the number of nanoseconds that have passed since the previous execution of the loop. I'll explain why, although this might not have any meaning to you until you actually start game programming.
Processors, especially those found on modern mobile devices, are erratic; the speed at which the loop is executed varies.
Why is this a problem? Let's say that updateGame() method moves a character right by 5 pixels. Now consider what would happen if updateGame() was not run at equal intervals. If the game slowed down and the loop took double the amount of time to execute again, the character would move at half speed. This would be disastrous for even a simple game like Temple Run.
So what a lot of game developers do is this. Instead of moving 5 pixels, the character would move 5 pixels MULTIPLED BY the amount of time that elapsed since the last execution of the loop (which we can define as deltaTime). This means that no matter how much the processor slows down, the character will always travel at the same speed.
Enough with the introductions. Let's meet the first loop!
Lesson #1-15: The While Loop
We saw a quick example of a while loop above. Let's discuss it in a little more depth.
The while loop will continue to execute as long as the condition is satisfied.
Take a look at this example:
Code:
[COLOR="DarkRed"]while (earthIsSpinning){[/COLOR]
//Remember that when you have a boolean without '== true' or '== false', the former is understood.
//The compiler will read this as:
//earthIsSpinning == true
System.out.println("The earth is still spinning.")
[COLOR="DarkRed"]}[/COLOR]
If this was an actual program, it would just flood your console as fast as the computer is capable of with the sentence "The earth is still spinning." At least for the predictable future.
We rarely want programs that run forever. So how do you end a while loop?
Simple. When the loop is executed to your satisfaction, you change the variable earthIsSpinning to false so that the condition is no longer satisfied. Then the loop will terminate.
A full class example follows:
Code:
[COLOR="Blue"]public class Looping {
[/COLOR] [COLOR="RoyalBlue"]public static void main(String[] args) {[/COLOR]
boolean earthIsSpinning = true;
int counter = 0;
[COLOR="MediumTurquoise"]while (earthIsSpinning){[/COLOR]
System.out.println("The earth is still spinning.");
System.out.println(counter);
counter++;
[COLOR="Teal"]if (counter >= 10){[/COLOR]
earthIsSpinning = false;
[COLOR="Teal"]}[/COLOR]
[COLOR="MediumTurquoise"]}[/COLOR]
[COLOR="RoyalBlue"]}[/COLOR]
[COLOR="Blue"]}[/COLOR]
And this is the output:
Code:
The earth is still spinning.
0
The earth is still spinning.
1
The earth is still spinning.
2
The earth is still spinning.
3
The earth is still spinning.
4
The earth is still spinning.
5
The earth is still spinning.
6
The earth is still spinning.
7
The earth is still spinning.
8
The earth is still spinning.
9
Most of this code is self explanatory, because it incorporates elements that we have seen before.
Let's talk about some of the things that you may have forgotten or have unanswered questions about.
Within the main class:
1. We create a boolean earthIsSpinning, and initialize the value to be true.
2. We also create a counter and set the value as 0;
A while loop that has the condition (earthIsSpinning == true) is created.
Inside it,
1. We display "The earth is still spinning."
2. We display the value of the integer counter.
3. We add 1 to counter's value.
An if statement is contained inside the while loop.
If counter is less than 10, this if statement is ignored!
With each iteration, or execution, of the while loop, the value of the counter integer, which begins at 0, increases by 1.
This means that after the 10th display, earthIsSpinning would be set equal to false, and the condition of the while loop will no longer be satisfied, meaning that it will terminate.
Why does this if statement have to be inside the while loop? Because if we put the if statement outside the while loop, it will only run once right after the first execution of the while loop, when counter is equal to 1. The if condition will not be satisfied and the statement will never be called again.
_____________________
Do you ever find it difficult to count? Me neither, but let's create a counting program for the heck of it.
This program will use two values: an initial value and a final value. It will then sequentially count the integers between the two values.
_____________________
Code:
[COLOR="Blue"]public class Looping {
[/COLOR] [COLOR="RoyalBlue"]public static void main(String[] args){[/COLOR]
int initialValue = 0;
int finalValue = 10;
int counter = 0;
[COLOR="DarkRed"] if (initialValue < finalValue) {[/COLOR]
System.out.println("Input accepted!");
System.out.println("Initial Value: " + initialValue);
System.out.println("Final Value: " + finalValue);
System.out.println();
System.out.println("Initiating count.");
System.out.println();
System.out.println(initialValue);
counter++;
[COLOR="DarkOrange"]while (initialValue < finalValue) {[/COLOR]
initialValue++;
System.out.println(initialValue);
counter++;
[COLOR="DarkOrange"]}[/COLOR]
[COLOR="Olive"]if (initialValue == finalValue){[/COLOR]
System.out.println();
System.out.println("Counting complete.");
System.out.println("There are " + counter + " numbers (inclusive) between " + (initialValue - counter + 1) + " and " + finalValue + ".");
[COLOR="Olive"] }[/COLOR]
[COLOR="DarkRed"] } else {[/COLOR]
[COLOR="SeaGreen"] //Executed if: if (initialValue < finalValue) above is not true.[/COLOR]
System.out.println("Final value is less than initial value!");
System.out.println("Please choose new values.");
[COLOR="Red"]}
[/COLOR]
[COLOR="RoyalBlue"]}[/COLOR]
[COLOR="Blue"]}
[/COLOR]
The Output:
Code:
Input accepted!
Initial Value: 0
Final Value: 10
Initiating count.
0
1
2
3
4
5
6
7
8
9
10
Counting complete.
There are 11 numbers (inclusive) between 0 and 10.
Try to study this code and see if you can figure out what it is doing.
It looks complex, but it is very straightforward!
We will analyze this in detail tomorrow!
_____________________
If you want to thank me for the guide, you can press Thanks or donate here or download TUMBL +!
Thank you guys for reading and I'm here if you have any questions!
PM me or email me!
Sorry about the long wait! My computer broke down, and I just managed to get the power supply replaced.
But on a more positive note:
I think after 3 more days, we can begin actual game development.
Of course there's a lot more to learn, but I think it would be more fun and more efficient to learn some of the tougher concepts by application.
Without further ado, let's jump into our next lesson!
Lesson #1-16: Analyzing the Looping Class
In the last lesson, I created a class called Looping as follows:
Code:
[COLOR="Blue"]public class Looping {
[/COLOR] [COLOR="RoyalBlue"]public static void main(String[] args){[/COLOR]
int initialValue = 0;
int finalValue = 10;
int counter = 0;
[COLOR="DarkRed"] if (initialValue < finalValue) {[/COLOR]
System.out.println("Input accepted!");
System.out.println("Initial Value: " + initialValue);
System.out.println("Final Value: " + finalValue);
System.out.println();
System.out.println("Initiating count.");
System.out.println();
System.out.println(initialValue);
counter++;
[COLOR="DarkOrange"]while (initialValue < finalValue) {[/COLOR]
initialValue++;
System.out.println(initialValue);
counter++;
[COLOR="DarkOrange"]}[/COLOR]
[COLOR="Olive"]if (initialValue == finalValue){[/COLOR]
System.out.println();
System.out.println("Counting complete.");
System.out.println("There are " + counter + " numbers (inclusive) between " + (initialValue - counter + 1) + " and " + finalValue + ".");
[COLOR="Olive"] }[/COLOR]
[COLOR="DarkRed"] } else {[/COLOR]
[COLOR="SeaGreen"] //Executed if: if (initialValue < finalValue) above is not true.[/COLOR]
System.out.println("Final value is less than initial value!");
System.out.println("Please choose new values.");
[COLOR="Red"]}
[/COLOR]
[COLOR="RoyalBlue"]}[/COLOR]
[COLOR="Blue"]}
[/COLOR]
The Output:
Code:
Input accepted!
Initial Value: 0
Final Value: 10
Initiating count.
0
1
2
3
4
5
6
7
8
9
10
Counting complete.
There are 11 numbers (inclusive) between 0 and 10.
It might have been a while since we discussed some of these concepts, so please refer to previous lessons if you are confused!
And of course, you can pm me or email me questions as always.
Now to analyze:
1. The blue text begins the Looping class. (I hope you know this by now ).
2. The light blue text then begins the main method (you should know what the main method is also).
3. The next three statements beginning "int..." initialize three integers: initialValue, finalValue, and counter.
4. The point of this program is to count from a lower number to a higher number, so the first condition it tests for, using an if statement is whether initialValue < finalValue.
5. If this condition is satisfied, we see a bunch of System.out.println("...")
6. The counter variable is increased by 1.
7. The while loop then initiates, and this increases initialValue by 1, and displays the new initialValue.
8. Counter variable is again increased by 1.
9. With each iteration (repetition) of the while loop, we check if the initialValue (which increases by 1 with each iteration) is equal to finalValue, because that is when we can stop counting.
10. When this if condition (colored gold) is satisfied, we stop counting, and display the counter variable, which has been increasing by 1 with each increase in value of the initialValue variable.
Make sure you run this code a few times with your own numbers to understand what exactly is happening at each step.
If you want to make your own programs, you should be able to analyze and at least have a general sense of what other programmers are trying to accomplish with their code.
Lesson #1-17: The For Loop
The while loop utilized a counter that we coded ourselves. Now we will implement the for loop which comes with a built-in counter, so to speak.
The form of a for loop is as follows (as stated in Java docs):
Code:
for (initialization; termination;
increment) {
statement(s)
}
"When using this version of the for statement, keep in mind that:
1. The initialization expression initializes the loop; it's executed once, as the loop begins.
2. When the termination expression evaluates to false, the loop terminates.
3. The increment expression is invoked after each iteration through the loop; it is perfectly acceptable for this expression to increment or decrement a value."
Confused?
Let's look at an example:
Code:
[COLOR="Blue"]class ForLoop {
[/COLOR] [COLOR="RoyalBlue"]public static void main(String[] args){[/COLOR]
[COLOR="Red"]for(int variable = 1; variable <11; variable++){[/COLOR]
System.out.println("Count is: "
+ variable;
[COLOR="Red"]}[/COLOR]
[COLOR="RoyalBlue"]}[/COLOR]
[COLOR="Blue"]}[/COLOR]
The output would be:
Code:
Count is: 1
Count is: 2
Count is: 3
Count is: 4
Count is: 5
Count is: 6
Count is: 7
Count is: 8
Count is: 9
Count is: 10
The for loop is quite simple:
The first part of the for (...) is the initialization of a variable.
We initiate an integer called variable, with the value of 1.
The second part "variable <11" is the condition. Think of this as: while (variable < 11)...
Everything inside the for loop will run as long as this second part is satisfied.
The third part "variable++" is what happens to the initialized variable after each iteration. We increase it by one.
Lesson #1-18: Applying the For Loop
In this lesson, we will recreate the Looping program using not the while loop, but the for loop!
Have a look at the while loop example again:
Code:
[COLOR="Blue"]public class Looping {
[/COLOR] [COLOR="RoyalBlue"]public static void main(String[] args){[/COLOR]
int initialValue = 0;
int finalValue = 10;
int counter = 0;
[COLOR="DarkRed"] if (initialValue < finalValue) {[/COLOR]
System.out.println("Input accepted!");
System.out.println("Initial Value: " + initialValue);
System.out.println("Final Value: " + finalValue);
System.out.println();
System.out.println("Initiating count.");
System.out.println();
System.out.println(initialValue);
counter++;
[COLOR="DarkOrange"]while (initialValue < finalValue) {[/COLOR]
initialValue++;
System.out.println(initialValue);
counter++;
[COLOR="DarkOrange"]}[/COLOR]
[COLOR="Olive"]if (initialValue == finalValue){[/COLOR]
System.out.println();
System.out.println("Counting complete.");
System.out.println("There are " + counter + " numbers (inclusive) between " + (initialValue - counter + 1) + " and " + finalValue + ".");
[COLOR="Olive"] }[/COLOR]
[COLOR="DarkRed"] } else {[/COLOR]
[COLOR="SeaGreen"] //Executed if: if (initialValue < finalValue) above is not true.[/COLOR]
System.out.println("Final value is less than initial value!");
System.out.println("Please choose new values.");
[COLOR="Red"]}
[/COLOR]
[COLOR="RoyalBlue"]}[/COLOR]
[COLOR="Blue"]}
[/COLOR]
We can safely remove all the counter variable related statements, as the for loop will handle that for us.
The only other segment of code we need to modify is the while loop section.
We will replace this with the for loop :
Code:
[COLOR="Blue"]public class ForLooping {
[/COLOR] [COLOR="RoyalBlue"]public static void main(String[] args) {[/COLOR]
int initialValue = 0;
int finalValue = 10;
[COLOR="DarkRed"]if (initialValue < finalValue) {[/COLOR]
System.out.println("Input accepted!");
System.out.println("Initial Value: " + initialValue);
System.out.println("Final Value: " + finalValue);
System.out.println();
System.out.println("Initiating count.");
System.out.println();
System.out.println(initialValue);
[COLOR="Green"] for (initialValue = initialValue + 1; initialValue <= finalValue; initialValue++){
[/COLOR] System.out.println(initialValue);
[COLOR="Green"]}[/COLOR]
[COLOR="DarkRed"]} [/COLOR][COLOR="Red"]else {[/COLOR]
System.out.println("Final value is less than initial value!");
System.out.println("Please choose new values.");
[COLOR="Red"]}[/COLOR]
[COLOR="RoyalBlue"]}[/COLOR]
[COLOR="Blue"]}[/COLOR]
Remember to change the name of the class (Select it on the left side of the screen in the Package Explorer, use F2) before running the code!
The output:
Code:
Input accepted!
Initial Value: 0
Final Value: 10
Initiating count.
0
1
2
3
4
5
6
7
8
9
10
Using the for loop significantly reduced the size of the code, and it is much more efficient!
=) I don't know what we will be learning tomorrow, but I'll try to make the most of the 2 more days!
[Day 10] Final Touches Part I
[Day 11] Final Touches Part II
[Day 12] Beginning Java Game Development
Related
I posted my problem at stackoverflow, please help me if you can.
my problem is very.. different. I got a code similar to:
Code:
public class PlayerCharacter
{
public void move(int direction)
{
if(direction != 0) //Skips this
{
...
}
else //Enter here
{
destinationMap = GamePlayScreen.canTransferMap(direction);
...
}
...
}
}
public Class GamePlayScreen
{
private PlayerCharacter p;
private static GamePlayScreen instance;
...
public void codeStartsHere()
{
//heppens in motionEvent only
p.move(0);
}
public static Map canTransferMap(int direction)
{
return instance.canTransferToMap(direction); //returns here the currect value
}
private Map canTransferToMap(int direction)
{
...
return getMap(nextMapName); //returns here the currect value
}
public Map getMap(String mapName)
{
for(Map t : maps)
{
if(t.getMapName().equals(mapName) == true)
{
return t; //returns here the currect value
}
}
return null; //never gets here
}
}
Everything works fine until "GamePlayScreen.canTransferMap(direction)" ends. Though it gets the correct value from "instance.canTransferToMap(direction)", when I watch PlayerCharacter->move->destinationMap I see that it returns a null!
I went step by step and watched the return values in every "return", before & after it: it returns null instead of the value! What is even stranger, it ALWAYS works at the first time and fails at the 2nd.
I updated the android SDK but didn't help, and so reinstalling the application & doing "project->clean".
Notes:
1. I'm using Galaxy S I9000, eclipse and it is a canvas drawn application.
2. I wrote as close a copy as I could (please note that this is my REAL code).
Thanks in advance
It's hard to tell for sure, but I think you've got a scope problem. You're assigning a value to destinationMap by calling a static function of the class GamePlayScreen, but the static function is calling non-static functions within the same class so unless maps is declared static, your for loop: for (Map t: maps) , is probably returning a local variable Map that is going out of scope as soon as your call return t.
It isn't a local array, it's "private ArrayList<Map> maps;" that is defined along side "private PlayerCharacter p;" and "private static GamePlayScreen instance;" in GamePlayScreen's instance;
I tired to replace the "for-each" loop with a regular "for" but it doesn't change anything.
Though a return of a non-existing object address may sound logical, it is not possible in Java because all of the objects are allocated in the heap and not in stack. (Though I had such problems in C++)
Well, I'd have to see all the code involved I guess. I know that all objects in Java are heap based, but that also means that they must be new'd somewhere too and I saw no new for the Map object, but I suppose you did that when you placed them in the ArrayList. The static qualifier on canTransferMap() throws me off though. Why is it there if you're returning a properly new'd object?
In my code I wish to access GamePlayScreen's data from within PlayerCharacter, even though I do not have the needed reference.
My solution for that is to have a static reference to GamePlayScreen in GamePlayScreen and thus it is available from everywhere. (And I know I will not have more then one GamePlayScreen at once in my game)
About the "new" keyword, as for now I have zero "new"-s while playing the game.
I pre-allocate ALL of my data and release the temporary in a loading screen, right before the actual game starts.
Hello, i'm making an app, and i need for the app to populate a list view, i've got this to work, the listview is populated by arrays in the values resources folder. the name for this array is defined by the selected items of two spinners combined with a "_" in the middle. How do i set this custom array ID?
here is my current main activity code: (i've used a existing array id to test that it works "tener_future")
Code:
package org.townsend.spanish.donate;
import android.app.Activity;
import android.content.res.Resources;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Spinner;
public class Main extends Activity implements OnClickListener {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
View conjugateButton = findViewById(R.id.conjugate_button);
conjugateButton.setOnClickListener(this);
}
@SuppressWarnings({ "unchecked", "rawtypes" })
private void verbAndTense() {
Resources res = getResources();
String[] listItems = res.getStringArray(R.array.tener_conditional);
Spinner verbs = (Spinner) findViewById(R.id.verbs);
Spinner verb_tenses = (Spinner) findViewById(R.id.verb_tenses);
ListView conjugated = (ListView) findViewById(R.id.ListView01);
conjugated.setAdapter(new ArrayAdapter(this,
android.R.layout.simple_list_item_1, listItems));;
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.conjugate_button:
verbAndTense();
break;
}
}
}
If I understand your question correctly, you are trying to get a reference to an Id stored in the R class, but which reference you need changes at runtime?
If that is the case, I think you may want to program a custom utility/method that can return the correct R reference for you. R is just a static generated class of ints, so it cannot evaluate something like R.id.dynamicterm1_dynamicterm2 where dynamicterm1 and dynamicterm2 change at runtime.
One way to do this might be a static util class like this:
Code:
package org.townsend.spanish.donate.util;
import org.townsend.spanish.donate.R;
public class ReferenceFinder
{
public static int find(String prefixName, String suffixName)
{
int returnValue = -1; // -1 indicates an error
if ( prefixName.equals("verb") && suffixName.equals("tense") )
{
returnValue = R.id.verb_tense;
}
else if( prefixName.equals("adj") && suffixName.equals("tense") )
{
returnValue = R.id.adjective_tense;
}
return returnValue;
}
Then you would call it like so:
Code:
Resources res = getResources();
int resourceID = ReferenceFinder.find("verb", "tense") ;
String[] listItems = res.getStringArray( resourceID );
I'm sure there are other ways to do this, but this is the first that came to mind. Hope that helps
would that mean that in the resource finder class that i'd have to define every possible outcome? because i'll have hundreds of outcomes once i have loaded the full list's and their outcome array's
and i think you have understood me correctly, basically it's and app (for spanish) where in one spinner you input a verb, in another you input a tense, and when you press a button it fills a list view with the 6 conjugations.
also it seems like in the second snippet of code i would have to actually set the "verb" and "tense" or could i put something dynamic like
Code:
verbs.getSelectedItem() + "_" + verb_tenses.getSelectedItem
Thanks for the help
hmm.... you might be able to do it via reflection actually, so that you wouldnt have to define each one.
I'm not 100% sure what the code would be but it would probably looks something like this:
Code:
String className= "com.example.myapp.R.id";
Class cl = Class.forName( className );
String fieldName = verbs.getSelectedItem() + "_" + tenses.getSelectedItem();
Field f = cl.getDeclaredField ( fieldName );
//since field is static, the "object" is ignored
int resourceID = f.getInt ( new Object() );
ok thanks i'm trying to get it to fit in, and i believe i have:
Code:
@SuppressWarnings({ "unchecked", "rawtypes" })
private void verbAndTense() {
Spinner verbs = (Spinner) findViewById(R.id.verbs);
Spinner verb_tenses = (Spinner) findViewById(R.id.verb_tenses);
verb_tenses.getSelectedItem();
String className= "org.townsend.spanish.donate.R.array";
Class cl = Class.forName( className );
String fieldName = verbs.getSelectedItem() + "_" + verb_tenses.getSelectedItem();
Field f = cl.getDeclaredField ( fieldName );
//since field is static, the "object" is ignored
int resourceID = f.getInt ( new Object() );
String[] listItems = f.getStringArray( resourceID );
ListView conjugated = (ListView) findViewById(R.id.ListView01);
conjugated.setAdapter(new ArrayAdapter(this,
android.R.layout.simple_list_item_1, listItems));
}
where it says :
Code:
String[] listItems = f.getStringArray( resourceID );
is it correct to put the "f" in there? and second is asks to define "Field" what should i import it as? or do i need to declare it in another format?
should be something like
String[] listItems = getResources.getStringArray( resourceID );
resourceID is an int just like R.id.something_something
i changed getResources to res, since it was defined as:
Code:
Resources res = getResources();
however my problem with "Field" in the line:
Code:
Field f = cl.getDeclaredField ( fieldName );
still exists, it says "Field cannot be resolved to a type" and gives me a load of options including imports, making a new class, interface, enum or adding a parameter. what should i do? I've tried several of the imports but then other segments suchs as:
Code:
cl.getDeclaredField ( fieldName );
become errored.
Thank you for all your guys' help so far
If you're using the Field class and don't IMPORT it, well, that's a problem
You're best friend --> http://developer.android.com/reference/java/lang/reflect/Field.html
thank you yes my porblem was i was unsure which to import it as, although i was more confident about it being that one (i had about 8 options from eclipse)
previous code however has now given me errors, :
Code:
Class cl = [U]Class.forName( className )[/U];
this section saying : "Unhandled exception type ClassNotFoundException"
Code:
Field f = [U]cl.getDeclaredField ( fieldName )[/U];
this with: "Unhandled exception type NoSuchFieldException"
and
Code:
int resourceID = [U]f.getInt ( new Object() )[/U];
with: "Unhandled exception type IllegalAccessException"
I looked through the field resource page and the last one where it says this error occurs when the field is not accesible....:/
I then checked the Class resources page and the first one said that type ClassNotFoundException is thrown when requested class cannot be found, and i thought i had declarred it in the previous
Code:
String className= "org.townsend.spanish.donate.R.array";
I know that in the example you provided me you put R.id, howeve this is a value array so it should be array right?
and the second says its thrown when the field cannot be found.
Im guessing that means that the first one is affecting the rest? how could i correct this,
if you wish to see the entire void it is here
Code:
@SuppressWarnings({ "rawtypes", "unchecked" })
private void verbAndTense() {
Spinner verbs = (Spinner) findViewById(R.id.verbs);
Spinner verb_tenses = (Spinner) findViewById(R.id.verb_tenses);
verb_tenses.getSelectedItem();
String className= "org.townsend.spanish.donate.R.array";
Class cl = Class.forName( className );
String fieldName = verbs.getSelectedItem() + "_" + verb_tenses.getSelectedItem();
Field f = cl.getDeclaredField ( fieldName );
//since field is static, the "object" is ignored
Resources res = getResources();
int resourceID = f.getInt ( new Object() );
String[] listItems = res.getStringArray( resourceID );
ListView conjugated = (ListView) findViewById(R.id.ListView01);
conjugated.setAdapter(new ArrayAdapter(this,
android.R.layout.simple_list_item_1, listItems));
}
Thank you
Yes, sorry it should be R.array or whatever
As for the "unhandled exceptions", if you use eclipse, just do the "recommended fix" and it will add a try/catch for you.
You may have to define some fields outside the try catch block and move some stuff around a bit after eclipse adds the try/catch.
Also, just as an aside, you may want to read a tutorial or two on reflection in Java so what I am saying doesnt sound as new/strange. Not required but it always helps to know a bit of reflection I think
Hello i am working this code on Programmr.com and i have tried everything to figure this simple code out and any help would be great-full this is from java program from the site. FYI i am a rookie this may be a simple code but i am trying to think different but no luck.
Here is the problem : >
Problem:
You and the Martian start becoming good friends. There is so much in common between the two of you - an interest in camping on volcanic peaks to hunting for quarters in the swimming pool. One summer afternoon, you and your Martian friend decide to play a game of Echo. The purpose of the game is to echo what the other person is saying. If the Martian says "zboggattyu", you have to reply back with "zboggattyu".
The exercise below, asks you to enter some text on the system console. This text will be stored in the variable 'someText'. This is then copied into another variable called '-echo', which is printed back to the system console. However, we are unable to get the code to compile. You have to get the code to compile, so you can play echo with your Martian friend.
What we expect:
Primarily, we expect you to get the code to compile. Once the code is compiled and run, it will ask you to enter a String on the system console. We expect the same String is echoed (printed) back on the system console.
Hint:
There are some rules governing valid variable names
Learning Outcomes:
After completing this exercise, you should have learned what constitutes a valid variable name.
Here is the code
import java.util.Scanner;
public class Echo {
public static void main(String args[]) {
Scanner scanner = new Scanner(System.in);
System.out.println("Please enter something: ");
String someText = scanner.next();
String echo = "";
///{
//start your coding here
// ?
///}
System.out.println(echo);
}
}
That excersie compiled fine for me even without making any modifications to it... However, the solution they're probably looking for is:
Code:
import java.util.Scanner;
public class Echo {
public static void main(String args[]) {
Scanner scanner = new Scanner(System.in);
System.out.println("Please enter something: ");
String someText = scanner.next();
String echo = "";
echo = someText;
System.out.println(echo);
}
}
Which seems to work fine for me, though to be honest that is a bad way of doing it as you don't actually need the echo variable so you're wasting resources by defining a new variable... a more efficient way of doing it is:
Code:
import java.util.Scanner;
public class Echo {
public static void main(String args[]) {
Scanner scanner = new Scanner(System.in);
System.out.println("Please enter something: ");
String someText = scanner.next();
System.out.println(someText);
}
}
Or you could even go one step further and ignore the someText variable altogether like below:
Code:
import java.util.Scanner;
public class Echo {
public static void main(String args[]) {
Scanner scanner = new Scanner(System.in);
System.out.println("Please enter something: ");
System.out.println(scanner.next());
}
}
Edit: After looking at this some more and seeing that the lesson is about variable names I believe that they actually meant to give you the below code to solve:
Code:
import java.util.Scanner;
public class Echo {
public static void main(String args[]) {
Scanner scanner = new Scanner(System.in);
System.out.println("Please enter something: ");
String someText = scanner.next();
String -echo = "";
System.out.println(-echo);
}
}
Where the line of String -echo =""; would be causing the code not to compile because of the rules governing the naming of variables so the solution would have been to change '-echo' to 'echo' - unfortunately it would seem that they messed they're own exercise up there :laugh:
Thank you for the help developers.
Sent from my SGH-M819N using XDA Free mobile app
I am requesting for a code that generates a random number from 0-100. for example it generates 55. then 55 won't be generated anymore unless the application exits or restarts.
mitsumei said:
I am requesting for a code that generates a random number from 0-100. for example it generates 55. then 55 won't be generated anymore unless the application exits or restarts.
Click to expand...
Click to collapse
Then just save all the generated numbers in a Set (or a boolean array or even in an ArrayList if you want to do more complex stuff with those numbers). Normally you don't have te right to request for code, but I'm in a good mood right now :
Java:
private HashSet savedNumbers = new HashSet();
private int generateNewRandomNumber() {
int number;
do {
number=(int) 101*Math.random();
} while(savedNumbers.contains(number));
savedNumbers.add(number);
return number;
}
SimplicityApks said:
Then just save all the generated numbers in a Set (or a boolean array or even in an ArrayList<Integer> if you want to do more complex stuff with those numbers). Normally you don't have te right to request for code, but I'm in a good mood right now :
Java:
private HashSet<Integer> savedNumbers = new HashSet<Integer>();
private int generateNewRandomNumber() {
int number;
do {
number=(int) 101*Math.random();
} while(savedNumbers.contains(number));
return number;
}
Click to expand...
Click to collapse
thank you so much for the code but the generated numbers keeps on repeating.
i will generate random number from 0-4. but it keeps on repeating when i used your code
mitsumei said:
thank you so much for the code but the generated numbers keeps on repeating.
i will generate random number from 0-4. but it keeps on repeating when i used your code
Click to expand...
Click to collapse
Sorry forgot the statement: savedNumbers.add(number);
If you only generate from 0 of 4 it will crash on the sixth number in an endless loop
I am describing two possible approaches: an online and an offline approach.
The online approach is pretty much the approach suggested above, and creates a new number whenever a new number is requested
Code:
import java.util.HashSet;
public class RandSequence {
private final int maxNum;
private HashSet<Integer> alreadyUsed;
/**
* Creates a RandSequence object.
* @param maxNum integers lower than maxNum will be created. maxNum must be greater than zero.
*/
public RandSequence(int maxNum) {
this.maxNum = maxNum;
this.alreadyUsed = new HashSet<Integer>();
}
/**
* Creates a random number, which has not been returned
* since the last reset, in the range [0,maxNum-1].
* @return a random number in the range of [0,maxNum-1]
* @throws Exception This Exception is thrown if maxNum numbers were returned.
*/
public int random() throws Exception {
if(alreadyUsed.size() >= maxNum) {
throw new Exception("Error: all integers in the range [0,maxNum-1] have already been returned");
}
int randNum = 0;
do {
randNum = (int)Math.floor(((double)maxNum) * Math.random());
} while(alreadyUsed.contains(randNum));
alreadyUsed.add(randNum);
return randNum;
}
/**
* Call this method, if all random numbers have been used.
*/
public void reset() {
alreadyUsed = new HashSet<Integer>();
}
}
The very obvious downside: like for a coupon collector, it becomes harder and harder to find new items, when most items are used. The running time of the rand() method increases, and if maxNum calls are processed, a running time of at least c*maxNum^2 (c ... a certain constant amount of computation) is expected for the code above in all.
Here the following offline approach comes in: If a large fraction of the possible random numbers is expected to be created, it's much cheaper to create maxNum numbers, and permute them randomly, since maxNum commutations are necessary to create any permutation of maxNum items. Therefore creating all maxNum randnumbers at once like below is a lot cheaper if many random numbers are required:
Code:
/**
* Creates a non-repeating random sequence of maxNum integers in the range of [0,maxNum-1]
* @param maxNum length of the random sequence
* @return an array holding the permutations of the numbers
* @throws Exception An Exception is thrown if maxNum is nonpositive
*/
public static int[] permutations(int maxNum) throws Exception {
if(maxNum < 1) {
throw new Exception("Error: the number of random numbers must be positive");
}
int perm[] = new int[maxNum];
for(int i=0 ; i<maxNum ; i++) {
perm[i] = i;
}
//each permutation of n objects can be
//achieved by executing n pairwise commutations
for(int i=0 ; i<maxNum ; i++) {
//pick randomly two elements of perm
int i_1 = (int)Math.floor(((double)maxNum)*Math.random());
int i_2 = (int)Math.floor(((double)maxNum)*Math.random());
//then permute both elements of perm
int first = perm[i_1];
int second = perm[i_2];
perm[i_1] = second;
perm[i_2] = first;
}
return perm;
}
The generated random numbers can now be consumed by iteratively walking through the returned array whenever random numbers are needed, until they are all used.
Suppose 1000 numbers of integers in [0,999] are created, this approach takes only 1000*c (c ... a certain constant amount of computation) computations, and in contrast the online approach may consume 500000*c computations. If we executed the for-loop for maxNum*2 times to really mix the numbers up well, using the offline approach would be still an advantage. But if only two or three of those random numbers are actually used, significantly more computations are required for the offline approach than for the online approach, and the memory requirements might also be a lot lower ... depending on the implementation of class HashSet (I haven't had a close look on the specs/source code of HashSet, but I suppose that the memory used for HashSet is expanded exponentially requiring a logarithmic number of reallocations with the number of items added to it).
Summary: use the first approach, if only few random numbers are used, use the second approach, if almost maxNum random numbers are required.
Hello,
I create that thread to present you a tutorial learning you to save data with SQLite on Android. This tutorial is also available in video on Youtube :
Learn to save data with SQLite on Android
On Android, there are several solutions to persist data between users’ sessions. One solution is to use a relational database to persist data and then to be able to query easily these data. In standard, Android SDK comes with a SQLite implementation. Biggest advantage of SQLite integration to Android OS is the fact that there is no need to to setup the database. So, no administration of this database. SQLite is embedded in standard and each application can have its SQLite database.
The only job that developers must make is to define SQL tables and statements for creating and updating data. Access to an SQLite database involves accessing the file system. So, it can be a slow operation. To avoid ANR (Application Not Responding) errors, it’s recommended to perform database operations asynchronously.
When an application creates and uses a SQLite database, it will be saved by default in the directory : DATA/data/APP_PACKAGE/databases/FILENAME .
1. Architecture
All classes needed to manage databases in Android SDK are contained in the package android.database . The package android.database.sqlite contains the SQLite specific classes.
SQLite API is centered around 2 main classes :
SQLiteOpenHelper that is an helper class to extend to manage database operations.
SQLiteDatabase that is the base class for working with a SQLite database in Android.
2. SQLiteOpenHelper
When you want to work with a SQLite database in Android, you must extend SQLiteOpenHelper class. In the constructor of your subclass you call the super() method of SQLiteOpenHelper, specifying the database name and the current database version.
You need also to override the following methods :
onCreate() that is called when database is accessed but not yet created.
onUpgrade() called when you choose to increment the version number of the database. In this method you can manage the migration process between two databases versions.
Both methods get and SQLiteDatabase instance in parameter which is the way to communicate with the database.
Furthermore, SQLiteOpenHelper provides 2 methods to get access to an SQLiteDatabase instance object respectively in read and in write modes :
getReadableDatabase() for read mode.
getWriteableDatabase() for write mode.
3. SQLiteDatabase
SQLiteDatabase is the class used to communicate with a SQLite database. It exposes several methods to interact with database like insert(), update() or delete().
In addition, it lets you to make queries via rawQuery() to queries made directly in SQL or via query() method. This last method provides a structured interface for specifying a SQL query.
4. Practice
Now, you know theory about SQLite in Android context. We can put in practice all the concepts. To achieve that, we’re going to make a database with a players table letting us to store NBA players.
To start, we create a simple Player Java POJO :
Code:
public class Player {
private int id;
private String name;
private String position;
private int height;
public Player() {
}
public Player(int id, String name, String position, int height) {
this.id = id;
this.name = name;
this.position = position;
this.height = height;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPosition() {
return position;
}
public void setPosition(String position) {
this.position = position;
}
public int getHeight() {
return height;
}
public void setHeight(int height) {
this.height = height;
}
@Override
public String toString() {
return name + " - " + position + " - " + height + " cm";
}
}
Then, we must create the SQLiteOpenHelper extended class to manage our application database. Code is here :
Code:
package com.ssaurel.samples.sqlite;
import java.util.LinkedList;
import java.util.List;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class SQLiteDatabaseHandler extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "PlayersDB";
private static final String TABLE_NAME = "Players";
private static final String KEY_ID = "id";
private static final String KEY_NAME = "name";
private static final String KEY_POSITION = "position";
private static final String KEY_HEIGHT = "height";
private static final String[] COLUMNS = { KEY_ID, KEY_NAME, KEY_POSITION,
KEY_HEIGHT };
public SQLiteDatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
String CREATION_TABLE = "CREATE TABLE Players ( "
+ "id INTEGER PRIMARY KEY AUTOINCREMENT, " + "name TEXT, "
+ "position TEXT, " + "height INTEGER )";
db.execSQL(CREATION_TABLE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// you can implement here migration process
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
this.onCreate(db);
}
public void deleteOne(Player player) {
// Get reference to writable DB
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_NAME, "id = ?", new String[] { String.valueOf(player.getId()) });
db.close();
}
public Player getPlayer(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_NAME, // a. table
COLUMNS, // b. column names
" id = ?", // c. selections
new String[] { String.valueOf(id) }, // d. selections args
null, // e. group by
null, // f. having
null, // g. order by
null); // h. limit
if (cursor != null)
cursor.moveToFirst();
Player player = new Player();
player.setId(Integer.parseInt(cursor.getString(0)));
player.setName(cursor.getString(1));
player.setPosition(cursor.getString(2));
player.setHeight(Integer.parseInt(cursor.getString(3)));
return player;
}
public List<Player> allPlayers() {
List<Player> players = new LinkedList<Player>();
String query = "SELECT * FROM " + TABLE_NAME;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(query, null);
Player player = null;
if (cursor.moveToFirst()) {
do {
player = new Player();
player.setId(Integer.parseInt(cursor.getString(0)));
player.setName(cursor.getString(1));
player.setPosition(cursor.getString(2));
player.setHeight(Integer.parseInt(cursor.getString(3)));
players.add(player);
} while (cursor.moveToNext());
}
return players;
}
public void addPlayer(Player player) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, player.getName());
values.put(KEY_POSITION, player.getPosition());
values.put(KEY_HEIGHT, player.getHeight());
// insert
db.insert(TABLE_NAME,null, values);
db.close();
}
public int updatePlayer(Player player) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, player.getName());
values.put(KEY_POSITION, player.getPosition());
values.put(KEY_HEIGHT, player.getHeight());
int i = db.update(TABLE_NAME, // table
values, // column/value
"id = ?", // selections
new String[] { String.valueOf(player.getId()) });
db.close();
return i;
}
}
Database is created in the constructor of the extended class. Players table is created in the onCreate() method thanks to a SQL statement.
In our class, we add methods to add a new player, to delete an existing one, to update and then a method to get all the players in the table. In this last method, we use a Cursor object to iterate on rows and then build equivalent Player instances.
To use our class to create some players then display on a simple ListView, we can use the following code :
Code:
public class MainActivity extends Activity {
private SQLiteDatabaseHandler db;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// create our sqlite helper class
db = new SQLiteDatabaseHandler(this);
// create some players
Player player1 = new Player(1, "Lebron James", "F", 203);
Player player2 = new Player(2, "Kevin Durant", "F", 208);
Player player3 = new Player(3, "Rudy Gobert", "C", 214);
// add them
db.addPlayer(player1);
db.addPlayer(player2);
db.addPlayer(player3);
// list all players
List<Player> players = db.allPlayers();
if (players != null) {
String[] itemsNames = new String[players.size()];
for (int i = 0; i < players.size(); i++) {
itemsNames[i] = players.get(i).toString();
}
// display like string instances
ListView list = (ListView) findViewById(R.id.list);
list.setAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, android.R.id.text1, itemsNames));
}
}
}
Execution result can be seen here :
{
"lightbox_close": "Close",
"lightbox_next": "Next",
"lightbox_previous": "Previous",
"lightbox_error": "The requested content cannot be loaded. Please try again later.",
"lightbox_start_slideshow": "Start slideshow",
"lightbox_stop_slideshow": "Stop slideshow",
"lightbox_full_screen": "Full screen",
"lightbox_thumbnails": "Thumbnails",
"lightbox_download": "Download",
"lightbox_share": "Share",
"lightbox_zoom": "Zoom",
"lightbox_new_window": "New window",
"lightbox_toggle_sidebar": "Toggle sidebar"
}
SQLite implementation in Android is simple and really powerful. You can now use it in your Android application to persist data.
Don't hesitate to give it a try and give me your feedbacks about this tutorial.
Thanks.
Sylvain
Hey, I have made a preview for SQLite database earlier this month for my friend.
If anyone's interested then it's there at https://www.GitHub.com/Fifa2151/SQLiteTest
Thanks,
Raj.
Sent from my Pixel using Tapatalk
sylsau said:
Hello,
I create that thread to present you a tutorial learning you to save data with SQLite on Android. This tutorial is also available in video on Youtube :
Learn to save data with SQLite on Android
On Android, there are several solutions to persist data between users’ sessions. One solution is to use a relational database to persist data and then to be able to query easily these data. In standard, Android SDK comes with a SQLite implementation. Biggest advantage of SQLite integration to Android OS is the fact that there is no need to to setup the database. So, no administration of this database. SQLite is embedded in standard and each application can have its SQLite database.
The only job that developers must make is to define SQL tables and statements for creating and updating data. Access to an SQLite database involves accessing the file system. So, it can be a slow operation. To avoid ANR (Application Not Responding) errors, it’s recommended to perform database operations asynchronously.
When an application creates and uses a SQLite database, it will be saved by default in the directory : DATA/data/APP_PACKAGE/databases/FILENAME .
1. Architecture
All classes needed to manage databases in Android SDK are contained in the package android.database . The package android.database.sqlite contains the SQLite specific classes.
SQLite API is centered around 2 main classes :
SQLiteOpenHelper that is an helper class to extend to manage database operations.
SQLiteDatabase that is the base class for working with a SQLite database in Android.
2. SQLiteOpenHelper
When you want to work with a SQLite database in Android, you must extend SQLiteOpenHelper class. In the constructor of your subclass you call the super() method of SQLiteOpenHelper, specifying the database name and the current database version.
You need also to override the following methods :
onCreate() that is called when database is accessed but not yet created.
onUpgrade() called when you choose to increment the version number of the database. In this method you can manage the migration process between two databases versions.
Both methods get and SQLiteDatabase instance in parameter which is the way to communicate with the database.
Furthermore, SQLiteOpenHelper provides 2 methods to get access to an SQLiteDatabase instance object respectively in read and in write modes :
getReadableDatabase() for read mode.
getWriteableDatabase() for write mode.
3. SQLiteDatabase
SQLiteDatabase is the class used to communicate with a SQLite database. It exposes several methods to interact with database like insert(), update() or delete().
In addition, it lets you to make queries via rawQuery() to queries made directly in SQL or via query() method. This last method provides a structured interface for specifying a SQL query.
4. Practice
Now, you know theory about SQLite in Android context. We can put in practice all the concepts. To achieve that, we’re going to make a database with a players table letting us to store NBA players.
To start, we create a simple Player Java POJO :
Code:
public class Player {
private int id;
private String name;
private String position;
private int height;
public Player() {
}
public Player(int id, String name, String position, int height) {
this.id = id;
this.name = name;
this.position = position;
this.height = height;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPosition() {
return position;
}
public void setPosition(String position) {
this.position = position;
}
public int getHeight() {
return height;
}
public void setHeight(int height) {
this.height = height;
}
@Override
public String toString() {
return name + " - " + position + " - " + height + " cm";
}
}
Then, we must create the SQLiteOpenHelper extended class to manage our application database. Code is here :
Code:
package com.ssaurel.samples.sqlite;
import java.util.LinkedList;
import java.util.List;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class SQLiteDatabaseHandler extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "PlayersDB";
private static final String TABLE_NAME = "Players";
private static final String KEY_ID = "id";
private static final String KEY_NAME = "name";
private static final String KEY_POSITION = "position";
private static final String KEY_HEIGHT = "height";
private static final String[] COLUMNS = { KEY_ID, KEY_NAME, KEY_POSITION,
KEY_HEIGHT };
public SQLiteDatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
String CREATION_TABLE = "CREATE TABLE Players ( "
+ "id INTEGER PRIMARY KEY AUTOINCREMENT, " + "name TEXT, "
+ "position TEXT, " + "height INTEGER )";
db.execSQL(CREATION_TABLE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// you can implement here migration process
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
this.onCreate(db);
}
public void deleteOne(Player player) {
// Get reference to writable DB
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_NAME, "id = ?", new String[] { String.valueOf(player.getId()) });
db.close();
}
public Player getPlayer(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_NAME, // a. table
COLUMNS, // b. column names
" id = ?", // c. selections
new String[] { String.valueOf(id) }, // d. selections args
null, // e. group by
null, // f. having
null, // g. order by
null); // h. limit
if (cursor != null)
cursor.moveToFirst();
Player player = new Player();
player.setId(Integer.parseInt(cursor.getString(0)));
player.setName(cursor.getString(1));
player.setPosition(cursor.getString(2));
player.setHeight(Integer.parseInt(cursor.getString(3)));
return player;
}
public List<Player> allPlayers() {
List<Player> players = new LinkedList<Player>();
String query = "SELECT * FROM " + TABLE_NAME;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(query, null);
Player player = null;
if (cursor.moveToFirst()) {
do {
player = new Player();
player.setId(Integer.parseInt(cursor.getString(0)));
player.setName(cursor.getString(1));
player.setPosition(cursor.getString(2));
player.setHeight(Integer.parseInt(cursor.getString(3)));
players.add(player);
} while (cursor.moveToNext());
}
return players;
}
public void addPlayer(Player player) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, player.getName());
values.put(KEY_POSITION, player.getPosition());
values.put(KEY_HEIGHT, player.getHeight());
// insert
db.insert(TABLE_NAME,null, values);
db.close();
}
public int updatePlayer(Player player) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, player.getName());
values.put(KEY_POSITION, player.getPosition());
values.put(KEY_HEIGHT, player.getHeight());
int i = db.update(TABLE_NAME, // table
values, // column/value
"id = ?", // selections
new String[] { String.valueOf(player.getId()) });
db.close();
return i;
}
}
Database is created in the constructor of the extended class. Players table is created in the onCreate() method thanks to a SQL statement.
In our class, we add methods to add a new player, to delete an existing one, to update and then a method to get all the players in the table. In this last method, we use a Cursor object to iterate on rows and then build equivalent Player instances.
To use our class to create some players then display on a simple ListView, we can use the following code :
Code:
public class MainActivity extends Activity {
private SQLiteDatabaseHandler db;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// create our sqlite helper class
db = new SQLiteDatabaseHandler(this);
// create some players
Player player1 = new Player(1, "Lebron James", "F", 203);
Player player2 = new Player(2, "Kevin Durant", "F", 208);
Player player3 = new Player(3, "Rudy Gobert", "C", 214);
// add them
db.addPlayer(player1);
db.addPlayer(player2);
db.addPlayer(player3);
// list all players
List<Player> players = db.allPlayers();
if (players != null) {
String[] itemsNames = new String[players.size()];
for (int i = 0; i < players.size(); i++) {
itemsNames[i] = players.get(i).toString();
}
// display like string instances
ListView list = (ListView) findViewById(R.id.list);
list.setAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, android.R.id.text1, itemsNames));
}
}
}
Execution result can be seen here :
SQLite implementation in Android is simple and really powerful. You can now use it in your Android application to persist data.
Don't hesitate to give it a try and give me your feedbacks about this tutorial.
Thanks.
Sylvain
Click to expand...
Click to collapse
Awesome guide @sylsau...
Also, do you know how to make a flashify type app but only for a specific zip?
When you want to work with a SQLite database in Android, you must extend SQLiteOpenHelper class. In the constructor of your subclass you call the super() method of SQLiteOpenHelper, specifying the database name and the current database version.
Click to expand...
Click to collapse
You don't actually need to use a subclass of SQLiteOpenHelper you can use the SQliteDatabase's open????? methods.
Furthermore, SQLiteOpenHelper provides 2 methods to get access to an SQLiteDatabase instance object respectively in read and in write modes :
Click to expand...
Click to collapse
Actually, in either case, except if the database cannot be opened, for write, both getReadableDatabase and getWritableDatabase will open a database that can be written to. As per :-
Create and/or open a database. This will be the same object returned by getWritableDatabase() unless some problem, such as a full disk, requires the database to be opened read-only. In that case, a read-only database object will be returned. If the problem is fixed, a future call to getWritableDatabase() may succeed, in which case the read-only database object will be closed and the read/write object will be returned in the future.
Click to expand...
Click to collapse
as per developer.android.com/reference/android/database/sqlite/SQLiteOpenHelper#getReadableDatabase()
On occasions people new to SQLite sometimes wonder why no database exists after they have instantiated the subclass of SQLiteOpenHelper (aka the DatabaseHelper). This is because the database is only created when either getWritableDatabase or getReadableDatabase is called. With a single line added to the constructor, the constructor will create the database (and thus invoke the onCreate method) e.g.
Code:
public SQLiteDatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
this.getWritableDatabse();
}
AUTOINCREMENT is perhaps the most commonly misused keyword (perhaps wrongly named). It does not make the column automatically generate a unique ID. It is INTEGER PRIMARY KEY that does this, as it make the column an alias of the **rowid**.
Rather AUTOINCREMENT compliments INTEGER PRIMARY KEY adding a constraint that the generated ID must be larger that any ID that exists or have existed. However, this is a moot point as it's only when the largest possible ID has been assigned (9223372036854775807) that it comes into play (other than without AUTOINCREMENT a deleted highest ID will be resused). At this point a table with AUTOINCREMENT will then fail with an SQLITE_FULL exception (without AUTOINCREMENT will attempt to assign a free lower ID rather than fail). However, AUTOINCREMENT has overheads (using a limited test I came up with an 8-12% degradation in performance when inserting). This is due to a changed algorithm being used that utilises another table sqlite_sequence that stores the highest allocated ID.
The SQLite documentation states :-
The AUTOINCREMENT keyword imposes extra CPU, memory, disk space, and disk I/O overhead and should be avoided if not strictly needed. It is usually not needed.
Click to expand...
Click to collapse
sqlite.org/autoinc.html
There are a few issues with the code, such as :-
You should always close Cursors when finished with them (not doing so may result in too many databases /database objects open exception ).
Checking a Cursor for null after a Cursor is returned from a call to an SQLiteDatabase method that returns a Cursor serves no purpose. A valid Cursor will always be returned. If there is no data then using a Cursor moveTo????? method will return false is the move cannot be made, alternately the getCount() method will return the number of rows in the Cursor.
If there were now rows in the Players table, the the code would fail with an error when an attempt is made to retrieve data at
Code:
player.setId(Integer.parseInt(cursor.getString(0)));
Issues regarding mis-calculated column offsets can be reduced by taking advantage of the Cursor's **getColumnIndex** method.
As such, as an example, the getPlayer method would be improved if changed to :-
Code:
public Player getPlayer(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_NAME, // a. table
COLUMNS, // b. column names
" id = ?", // c. selections
new String[] { String.valueOf(id) }, // d. selections args
null, // e. group by
null, // f. having
null, // g. order by
null); // h. limit
Player player = new Player(); //<<<<<<<<<< Always have a Player to return (should check for default player to indicated )
if (cursor.moveToFirst()) {
player.setId(Integer.parseInt(cursor.getString(cursor.getColumnIndex(KEY_ID))));
player.setName(cursor.getString(cursor.getColumnIndex(KEY_NAME)));
player.setPosition(cursor.getString(cursor.getColumnIndex(KEY_POSITION)));
player.setHeight(Integer.parseInt(cursor.getString(cursor.getColumnIndex(KEY_HEIGHT))));
}
cursor.close(); //<<<<<<<<<< Important to close a Cursor
return player;
}