Bay 12 Games Forum

Please login or register.

Login with username, password and session length
Advanced search  
Pages: 1 ... 10 11 [12] 13 14 ... 795

Author Topic: if self.isCoder(): post() #Programming Thread  (Read 815782 times)

Stargrasper

  • Bay Watcher
    • View Profile
Re: if self.isCoder(): post() #Programming Thread
« Reply #165 on: January 08, 2012, 02:35:18 pm »

I have actually been prohibited to use recursion in my programming lessons. :V

By whom and why?  It's an incredibly useful technique that will crash the computer if you aren't careful with it.

That really describes any programming.

The first part of my C++ tutorial will follow this post.

Recursion in particular is commonly screwed up.

Let me know if you want me to or not to cover anything.  I can relate our tutorials if you want.  I can also help with C++, as well.  Like I said, I can write for almost anything.

Working on the next tutorials...here's my rough roadmap for the next three...
    1. Strings and Conditionals
    2. Arrays and Loops
    3. Proving You've Been Paying Attention -- Quiz with Solutions/Examples

Any input is good.  I can also write tutorials for other languages if we want.
Logged

Mego

  • Bay Watcher
  • [PREFSTRING:MADNESS]
    • View Profile
Re: if self.isCoder(): post() #Programming Thread
« Reply #166 on: January 08, 2012, 02:47:51 pm »

Write whatever you think is important. Like I said, I'll mostly be referring back to your tutorials for simple things.

Virex

  • Bay Watcher
  • Subjects interest attracted. Annalyses pending...
    • View Profile
Re: if self.isCoder(): post() #Programming Thread
« Reply #167 on: January 08, 2012, 02:54:28 pm »

Maybe something on parralel processing? And since we're doing Java, OOP and interfaces are mandatory. I don't know if closures are commonly used, or even possible in Java, but they'd be a usefull topic to have a tutorial on too.


Edit: First I'd tackle recursion though, that's pretty fundamental. Maybe complexity analysis too.
« Last Edit: January 08, 2012, 02:59:17 pm by Virex »
Logged

Stargrasper

  • Bay Watcher
    • View Profile
Re: if self.isCoder(): post() #Programming Thread
« Reply #168 on: January 08, 2012, 03:00:34 pm »

Maybe something on parralel processing? And since we're doing Java, OOP and interfaces are mandatory. I don't know if closures are commonly used, or even possible in Java, but they'd be a usefull topic to have a tutorial on too.

Yeah, I'll definitely cover all of that eventually.  Parallel is awesome and I'm really looking forward to that one, but it's a little ways off if I keep my current progression.  Objects and interfaces are coming.  With how I'm doing this right now, it doesn't make sense to cover that material until I cover a lot of other things first.  Namely, methods and classes.  I can accelerate that and write a couple advanced tutorials early if you want?  Otherwise, I'm on the basics and working my way up slowly.
Logged

armeggedonCounselor

  • Bay Watcher
    • View Profile
Re: if self.isCoder(): post() #Programming Thread
« Reply #169 on: January 08, 2012, 03:38:00 pm »


It's an incredibly useful technique that will crash the computer if you aren't careful with it.

That really describes any programming.

Sig'd. Also posting to follow. I am semi-literate in C++, and program off and on. I'm currently in an off phase. Mostly because school hasn't started up again for me yet.
Logged
Quote from: Stargrasper
It's an incredibly useful technique that will crash the computer if you aren't careful with it.
That really describes any programming.

Aqizzar

  • Bay Watcher
  • There is no 'U'.
    • View Profile
Re: if self.isCoder(): post() #Programming Thread
« Reply #170 on: January 08, 2012, 03:41:57 pm »

The problem was I was so sick of looking at ifs and for-loops, I made the drawing function compatible for the quarter-array and said, "I'll make it work for everything else later", and then spent like an hour troubleshooting the boolean-check function (still not working).  I'm honestly impressed it drew the larger arrays at all without actually crashing.

Glad you found the problem.  Ifs shouldn't be bad to look at, but if your loops are bothering you, you should consider whether whatever you're doing would be easier with recursion.  Anything and everything you can do with a loop, you can do with recursion.  Anything and everything you can do with recursion, you can do with a loop.  Typically, one is noticeably cleaner than the other.  Of course, in order to understand recursion, you must first understand recursion.

What is your boolean-check function doing versus what you want it doing?  Booleans usually aren't that bad to work with...

I can post the whole code if you like, but since it's working I'm not sure how helpful that would be.  I'll pseudocode it though, to give you an idea.  The whole design is to turn an even-number-length array of booleans into a two-level map of blocks.  The overall for-loop iterates through the array, checking each space for (true).  If it is true, it then checks each of the blocks "around" it to see if they are false, and then randomly decides if it should draw a room that extends into that block's space.  If not, then it just draws a block in the space it's been working from.  ((Since I haven't actually written the "extended" block part yet, it'll just draw a normal sized one anyway - that's my next priority, which will probably help me fix this If-ladder since I won't be relying on an extra dummy-return to see if the statements are firing off.))

It simulates a 2D array with a 1D-array by operating against the (provided) length of the array.  One If-ladder starts by check if the for-loop's iteration is less than length-halved, to write the top row, then it does the bottom row.  This sounds overly complicated and I might be able to simplify it - I originally went this way because I wanted to use a 2D-array for the booleans but I couldn't figure out a function to get the array's overall length, but then I decided to just hard-code the length into the statement anyway, so it doesn't really matter.

And with that in mind, it would probably make more sense to just rewrite all this, but I'm genuinely curious why it isn't working.  I've been going down the If-ladders commenting parts in and out to see what's not working, and it's not pretty.  As far as I can tell, both the MakeDefaultUndergroundSquares function and the actual map-drawer work perfectly fine, it's just going schizo on where and when it's deciding to draw squares - with only the "top row" portion working, it's drawing everything to the bottom half of the map.  At any rate, the most likely problem is that my math is wrong somewhere, but I can't see where - when everything but the else-default "draw a normal square here" contingencies are commented out, it works fine, and all of the drawing-calls I have turn on have the right math for where to draw stuff.

Code: (That's a lot of brackets.) [Select]
public byte[,] MakeDefaultUnderground(bool[] input, int length)
{
output = new byte[xStandard,yStandard];

for(int x = 0; x < xStandard; x++)
{
for(int y = 0; y < yStandard; y++)
{
output[x,y] = (byte)000;
}
}

for(int x = 0; x < length; x++)
{
if ((input[x] == true) && (x < (length/2)))//top row
{
if (x == 0)//is top-left check
{
if (input[(length / 2) + x] == false)//search section to below
{
if (3 > random.Next(10))
{
MakeDefaultUndergroundSquares(x, 0, (length / 2));
//generate tall room from top-left section
input[(length / 2) + x] = true;
}
}
else if (input[x + 1] == false)//search section to right
{
if (3 > random.Next(10))
{
MakeDefaultUndergroundSquares(x, 0, (length / 2));
//generate long room from top-left section
input[x + 1] = true;
}
}
}
else if (x == (length / 2))//is top-right check
{
if (input[(length / 2) + x] == false)//search section to below
{
if (3 > random.Next(10))
{
MakeDefaultUndergroundSquares(x, 0, (length / 2));
//generate tall room from top-right section
input[(length / 2) + x] = true;
}
}
else if (input[x - 1] == false)//search section to left
{
if (3 > random.Next(10))
{
MakeDefaultUndergroundSquares(x, 0, (length / 2));
//generate long room from top-right-minus1 section
input[x - 1] = true;
}
}
}
else
{
if (input[(length / 2) + x] == false)//search section to below
{
if (9 > random.Next(10))
{
MakeDefaultUndergroundSquares(x, 0, (length / 2));
//generate tall room from non-corner section
input[(length / 2) + x] = true;
}
}
else if (input[x - 1] == false)//search section to left
{
//if (3 > random.Next(10))
{
MakeDefaultUndergroundSquares(x, 0, (length / 2));
//generate long room from this non-corner section-minus1
input[x - 1] = true;
}
}
else if (input[x + 1] == false)//search section to right
{
//if (9 > random.Next(10))
{
MakeDefaultUndergroundSquares(x, 0, (length / 2));
//generate long room from this non-corner section
input[x + 1] = true;
}
}
else
{
MakeDefaultUndergroundSquares(x, 0, (length / 2));
//generate standard square room in this section
}
}
}
else if (input[x] == true)//bottom row
{
if (x == ((length / 2) + 1))//is bottom-left check
{
if (input[x - (length / 2)] == false)//search section to above
{
if (3 > random.Next(10))
{
MakeDefaultUndergroundSquares((x - (length / 2)), 1, (length / 2));
//generate tall room from the top-left section
input[x - (length / 2)] = true;
}
}
else if (input[x + 1] == false)//search section to right
{
if (3 > random.Next(10))
{
MakeDefaultUndergroundSquares((x - (length / 2)), 1, (length / 2));
//generate long room from the bottom-left section
input[x + 1] = true;
}
}
}
else if (x == (length - 1))//is bottom-right check
{
if (input[x - (length / 2)] == false)//search section to below
{
if (3 > random.Next(10))
{
MakeDefaultUndergroundSquares((x - (length / 2)), 1, (length / 2));
//generate tall room from the top-right section
input[x - (length / 2)] = true;
}
}
else if (input[x - 1] == false)//search section to left
{
if (3 > random.Next(10))
{
MakeDefaultUndergroundSquares((x - (length / 2)), 1, (length / 2));
//generate long room from the bottom-right-minus1 section
input[x - 1] = true;
}
}
}
else
{
if (input[x - (length / 2)] == false)//search section to above
{
if (3 > random.Next(10))
{
MakeDefaultUndergroundSquares((x - (length / 2)), 1, (length / 2));
//generate tall room in the above non-corner section
input[x - (length / 2)] = true;
}
}
else if (input[x - 1] == false)//search section to left
{
if (3 > random.Next(10))
{
MakeDefaultUndergroundSquares((x - (length / 2)), 1, (length / 2));
//generate long room from this non-corner section-minus1
input[x - 1] = true;
}
}
else if (input[x + 1] == false)//search section to right
{
if (3 > random.Next(10))
{
MakeDefaultUndergroundSquares((x - (length / 2)), 1, (length / 2));
//generate long room from this non-corner section
input[x + 1] = true;
}
}
else
{
MakeDefaultUndergroundSquares((x - (length / 2)), 1, (length / 2));
//generate standard square room in this section
}
}
}
}

return output;
}

Don't worry if you don't think you can help me, I'm sure this code to totally opaque to anyone but me.

EDIT: And I once again realized an incredibly moronic error elsewhere in the code.  Damn, okay, nobody even look at this post, I'm back on the case.
« Last Edit: January 08, 2012, 03:56:06 pm by Aqizzar »
Logged
And here is where my beef pops up like a looming awkward boner.
Please amplify your relaxed states.
Quote from: PTTG??
The ancients built these quote pyramids to forever store vast quantities of rage.

Mego

  • Bay Watcher
  • [PREFSTRING:MADNESS]
    • View Profile
Re: if self.isCoder(): post() #Programming Thread
« Reply #171 on: January 08, 2012, 03:43:29 pm »

Mego's C++ Tutorial

Setting Up

In order to program in C++, all you need is a text editor. However, if you want to run your code, you'll need a C++ compiler, which will turn the code into an executable. The simplest way to get both tools is to install an IDE that supports C++. There are several to choose from, such as Eclipse, Code::Blocks, Geany, and QT Creator. I personally use Code::Blocks mainly, but which IDE you choose won't matter much for these tutorials. Read the documentation for your IDE to see how to create, compile, and execute code, and then continue to the lesson.

Lesson 1: Hello, World!

Foreword: I will be simplifying a lot of language stuff during early tutorials so that they don't get bogged down by details. In the later tutorials where those features are discussed, I'll make a note to go back and explain the things I just gloss over.

For the record, I am a believer in the philosophy of learning by doing. So, rather than introducing a topic, explaining it, and then giving code that shows how it is used, I will post some example code, and then explain what is going on in it.

With that said, let's look at your typical Hello World program in C++.

Code: (hello.cpp) [Select]
#include <iostream>

using namespace std;

int main() {
    cout << "Hello, world!" << endl;
    return 0;
}

Alright, even in a simple program like this, there's a lot of stuff going on. Let's break it up, line by line.

Code: [Select]
#include <iostream>
This is called a preprocessor directive. It tells the preprocessor (the thing that gets your code ready for compilation) that you need access to stuff in the iostream header (a type of code file that contains code to be used in other files), so it should include the code in there in this file. The preprocessor then replaces the line with the entire body of the iostream header.

Code: [Select]
using namespace std;
This line is one of two ways to use the code in the C++ Standard Library. The second way will be explained in detail when we discuss namespaces. You'll need this if you want to access anything in the iostream header or any other header in the Standard Library.

Code: [Select]
int main() {
Now we get to the meat of the code. This is a function (or method, if you prefer that naming convention) definition. All the code inside the main function gets executed when the program runs. The main function must always be declared as an int (short for integer, more on variables and types later), and must be in all lowercase, because C++ source code is case-sensitive. The opening brace signifies the start of the code that the function will execute.

Code: [Select]
cout << "Hello, world!" << endl;
This is a relatively complex statement compared to the rest of the code. To print things to standard output (typically a console/terminal window), you must use cout. cout is a special kind of object called an output stream. You put things into the stream with <<. Here, we are putting two things into the stream. First, we put the string "Hello, world!" into the stream. This will make the output display "Hello, world!", without the quotes. Next, we put endl in. endl is another special object that is declared in the iostream header. It represents a newline, customized to your system (\r\n in Windows, \n in pretty much every other OS). It does some other stuff, too, but that's not important right now.

Code: [Select]
return 0;
All functions in C++ must return a value, with one exception, which we will examine in a later tutorial. The main function is declared an int-returning function, so it must have a return statement with an int. A return statement is the exit point of a function. Try moving this line above the previous line and look at the difference. Even though there is code after the return, it is not executed. A return statement ends the function, no matter where in the function it is. For the main function, to represent successful execution, 0 is returned.

The next line is a closing brace, which matches to the opening brace on the first line of the function. That tells the compiler that any further code is not a part of the main function.

End of Lesson

If there's anything that you think needs explaining better, let me know, and I'll fix it.

Stargrasper

  • Bay Watcher
    • View Profile
Re: if self.isCoder(): post() #Programming Thread
« Reply #172 on: January 08, 2012, 06:19:33 pm »

Stargrasper's Java Basics Tutorial Series

Suppose I should accomplish something...like wave my hands and say it's all magic.

Lesson 0.4: Strings and Conditionals

Strings are groupings of text characters.  Internally, they are implmented as character arrays.  Arrays are magic.  Don't worry about what it is.  The String class is an object.  More on classes and objects later.  The important thing is that Java generally pretends Strings are primitives.  For now, virtually everything about Strings is magic.

When defining a String, you enclose the contents in double quotes.
Code: [Select]
String myString = "This is a String";

The word String is capitalized because it is an object.  myString is, again, the name of the variable.  Stylistically, I prefer and suggest naming variables with more than one word by capitalizing the first letter of every word but the first.  Variables should always start with a lower case letter unless they are constants.  More on constants later.  A single = in Java signifies an assignment.  Anything in double quotes is what you're placing in the string.

It's also worth noting that because String isn't a primitive and Java is pretending it is, Java is doing a lot of stuff for you to make sure you can pretend String is a primitive.  We'll discuss what it's doing later.  For now, it's magic.

Strings contain text.  This includes escape characters.  Here's a couple quick examples:
Code: [Select]
String newLine = "\n";
String tab = "\t";
String quote = "\"";

There are a lot of escape characters.  Those are just a few I use a lot.

Now, conditionals.  This is kind of a big section.  I'll include code excerpts describing functionality and then the whole of the example code at the end.

This is your standard if .. then .. else block of code, but a bit condenced.  For instance, you don't write the word then.
Code: [Select]
if ( condition ) {
// execute if condition is true
} else {
// execute if condition is false
}

The condition above is always a boolean value.  Nothing else is allowed in it...with a catch.  Here's a quick example:

But first note that there's a little setup...
Code: [Select]
// Lets just declare and define a couple booleans
boolean condition = false;
boolean condition2 = true;
Code: [Select]
// Just to make things more clear in the console
String firstExample = "First Example";
// Output to console
System.out.println(firstExample);

// Check whether our boolean condition is true
if ( condition == true ) {
// If it is, execute this code.

// Note that I defined an anonymous String
// and immediately sent it to println
System.out.println("\tCondition Passes");
} else {
// If condition is false, execute this code

// As above, I defined an anonymous String
// and sent it directly to println
System.out.println("\tCondition Fails");
}
/*
 * Note that a conditional will only ever execute either
 * the true code or the false code.  It will skip
 * whichever block of code is not needed for the
 * conditional
 */

You can do the opposite, too.  That is, check if the condition is false.
Code: [Select]
System.out.println("\nSecond Example");
/*
 * Now this gets a bit more confusing.
 * The conditional passes as true if
 * the condition being checked is true.
 *
 * If condition is false, the whole
 * expression passes as true.
 */
if ( condition == false ) {
System.out.println("\tCondition Passes");
} else {
System.out.println("\tCondition Fails");
}

Just because a conditional is checking if a condition is true, that doesn't mean that the specific thing you're checking is true.  As above, my if statement can pass as true if I'm checking condition == false and condition is false.  Don't forget you can do this.  It's bad style to always check if something is true and then not have any code to execute when it is.
Code: [Select]
System.out.println("\nThird Example");
/*
 * People get confused and think that they should
 * always be checking if something is true
 * even if they only want to execute code
 * when a condition is false.  The above
 * code demonstrates that this isn't necessary.
 *
 * In fact, stylistically, you should never have
 * an if block be empty like this.
 */
if ( condition == true ) {
// noop
} else {
System.out.println("\tCondition Fails");
}

Slight note, noop is an Assembly command meaning "no operation".  Because comments are ignored, Java thinks there is nothing at all written there.  It's a placehold to keep us from getting too confused as looks like this to Java:
Code: [Select]
System.out.println("\nThird Example");
if ( condition == true )
else
System.out.println("\tCondition Fails");

It's bad style to do that.  Instead, you should reverse the logic that the conditional is checking and just leave off the else clause entirely.
Code: [Select]
System.out.println("\nFourth Example");
/*
 * It is entirely legal and encouraged to
 * leave off the else statement if you
 * don't want to execute code there
 */
if ( condition == false ) {
System.out.println("\tCondition Passes");
}

Okay, great.  There are a lot of situtations where I want to check a sequence of things.  Is it a bird?  No?  Fine, is a plane?  No?  Fine, is it Superman?  Yeah!  You'll do this by hooking conditionals together.  I call this "cascading ifs".
Code: [Select]
System.out.println("\nFifth Example");
/*
 * Further more, you can cascade if statements
 * together to form chains that I will henceforth
 * be referring to as cascading ifs
 */
if ( condition == true ) {
System.out.println("\tCondition Passes #1");
} else if ( condition2 == true ) {
System.out.println("\tCondition Passes #2");
} else {
System.out.println("\tCondition Fails Entire Cascade");
}

Cascading ifs are a nice alternative to things like switch, which is more magic I'll get to later.  Basically, the code tries to execute the next block of code after the else.  That happens to be another if statement.  Again, it is skipped entirely if the first conditional passes.

Programmers are lazy bums.  We don't want to type anything more than we really have to.  "If I can understand what it's supposed to do, why can't the computer".  Hence, we created a method of not having to explicitly ask whether a boolean is true or false.  If you input the boolean name on it's own, Java is assuming you want to know if it is true.
Code: [Select]
System.out.println("\nSixth Example");
/*
 * You don't have to ask it whether the boolean
 * is true explicitly.  Java will implicitly
 * ask that if all you do is enter the boolean
 */
if ( condition ) {
System.out.println("\tCondition Passes");
} else {
System.out.println("\tCondition Fails");
}

But I'm a lazy bum who doesn't want to type more than I have to!  What if I want to check if that boolean is false?  Well, use the NOT operator.
Code: [Select]
System.out.println("\nSeventh Example");
/*
 * You can use the same notation to check
 * if a boolean is false.
 *
 * In Java, ! is the NOT operator
 *
 * The following code reads as
 * "if not condition"
 * or
 * "if condition is false"
 */
if ( !condition ) {
System.out.println("\tCondition Passes");
} else {
System.out.println("\tCondition Fails");
}

The NOT operator reverses whatever logic it is attached to, so...
Code: [Select]
!true == false;
!false == true;

if ( a != b ) {
// They don't match
}

Up to this point, I've lied to you.  I told you that conditional statements only take boolean values.  Here's the catch I mentioned earlier...you can put logical expressions into them.  As long as it resolves to a boolean, it doesn't matter what it is.  In fact, checking if ( condition == true ) isn't a boolean at all!  It's an expression that resolves to a boolean.  Same with if ( condition == false ), it's an expression that evaluates condition.  The only time we actually entered a straight boolean value into our conditional was when we used condition without asking what it was.  That is, if ( condition ) is actually checking a boolean.  if ( !condition ) is checking a boolean.  if ( true ) and if (false) are checking booleans.  Virtually everything else is evaluating an expression.
Code: [Select]
System.out.println("\nEighth Example");
/*
 * You don't actually have to enter a boolean into
 * the conditonal.  You can enter an expression that
 * resolves to a boolean.  We did this earlier when
 * asking for 'condition == false'.  It is an
 * expression that resolves to true if it passes.
 *
 * No real reason we need to limit ourselves to
 * booleans, though.  The expression can be
 * anything that resolves to a boolean.
 */
byte a = 2;
byte b = 3;
byte c = 5;

// if a + b is c
if ( a + b == c ) {
System.out.println("\t" + a + " + " + b + " = " + c);
} else {
System.out.println("\t" + a + " + " + b + " =/= " + c);
}
/*
 * You'll note that I can link different things together
 * in a string by using the + operator.  It's shorthand
 * for String.append(string).  In other words, magic.
 */

We should take a short time to talk about brackets and scoping.  Brackets signify a block of code.  Between a matching set of brackets is its own little universe.  At the end, anything created inside that block ceases to exist.  This is called scoping.  Code within a block is said to exist in that scope.  For example...
Code: [Select]
/*
 * Stargrasper
 * Updated 1/8/2012
 */

package com.bay12forums.stargrasper.javatutorial.lesson3;

public class Scoping {

public static void main(String[] args) {
System.out.println("Start");
// Initialize something
String everywhere = "This can be seen from anywhere in the main()";

/*
* I can open a code block pretty much
* anywhere I want.
*/
{
System.out.println("\tFirst Block");
/*
* From here to the closing bracket is a semi-isolated
* universe.  We can see anything in the outer brackets,
* so we can see the String everywhere.
*
* Now we declare and define num.
*/
int num = 5;

System.out.println("\t\tnum = " + num);
}

/*
* See that closing brace right above this comment?
* At that point, num stopped existing.
*/
System.out.println("\n\tBetween Blocks\n");

{
System.out.println("\tSecond Block");
/*
* Normally, we can't have two variable of
* the same name.  But I can name another
* variable num because we are outside
* the scope of the first block and thus
* the num from that block no longer
* exists.
*/
int num = 10;

System.out.println("\t\tnum = " + num);
}
}

}

Okay, how often are you really going to create independant blocks of code like in that example?  I've legitimately done it exactly twice.  More reasonably, you'll do this...
Code: [Select]
if ( condition ) {
int num = 5;
}

// Some time later...

if ( condition2 ) {
int num = 3;
}

This works because num stopped existing after the first if block ended.

When Java executes a condition, it runs the next "line" of code.  If you use brackets, Java pretends the block is a "line" for purposes of what to run with respect to the conditional.
Code: [Select]
System.out.println("\nNinth Example");
/*
 * When you execute an if-else, Java executes the next
 * "line" of code.  Brackets make Java think the enclosed
 * block is a line.  That means that so long as you
 * only need to execute one block of code, this
 * is perfectly legal syntax.
 *
 * Stylistically, please don't do this.  It's great
 * until you modify the code wanting to add to
 * that if statement, forget to add the brackets,
 * and then spend a week trying to figure out
 * why it isn't working.
 */
if ( condition )
System.out.println("\tConditon Passes");
else
System.out.println("\tCondition Fails");

While this does work, I stylistically say you shouldn't ever do it.  The reason is maintanance.  If you change that code, you might break the conditional and get caught trying to figure out why it won't work because you forgot to add brackets so you could run more than one line.  It's a style thing.  I think the brackets make it easier to read, anyway.

There are times when I want to check more than one condition.  I can use cascading ifs if I want to check them each for failure in order, but if I just want to check several things as once, it'd be nice to do it with one conditional.  Here's how we do it.
Code: [Select]
System.out.println("\nTenth Example");
/*
 * You can check multiple conditions in a
 * a couple of different ways.
 */
if ( condition ) {
if ( condition2 ) {
System.out.println("\tConditions Both Pass");
} else {
System.out.println("\tCondition1 Passes and Condition2 Fails");
}
} else {
System.out.println("\tCondition1 Fails or Both Conditions Fail");
}

/*
 * This is messy.  Why should I use two if statements
 * when I can use one and just check them both?
 *
 * To check two statements, use the AND operator.
 * Java used && as its AND operator
 */
if ( condition && condition2 ) {
System.out.println("\tConditions Both Pass");
} else {
System.out.println("\tConditions Fail; one, the other or both");
}

/*
 * Alternatively, I might want to check if either
 * one of the is true.  For that we use the
 * OR operator.
 *
 * The OR operator is ||
 */
if ( condition || condition2 ) {
System.out.println("\tConditions Pass, one, the other, or both");
} else {
System.out.println("\tConditions Fail, both of them");
}
/*
 * I can use any boolean operator here.
 */

Here are the boolean operators
   1. | = bitwise OR - TRUE iff either or both of two booleans are TRUE.
   2. & = bitwise AND - TRUE iff both of two booleans are TRUE.
   3. ^ = XOR - TRUE iff both of two booleans are different, ie, either is true and the other false, FALSE if both are TRUE or both are FALSE.  Ludicrously useful.
   4. ! = NOT - TRUE iff given boolean is FALSE, ususually used to reverse logic of a boolean.
   5. || = OR - TRUE iff either or both of two conditions are TRUE.
   6. && = AND - TRUE iff both of two conditions are TRUE.
   7. == = EQUALS - TRUE iff both of two values are the same.
   8. != = NOT EQUALS - TRUE iff both of two values are not the same.
   9. ?: = IF-THEN-ELSE - If IF is true, replaces statement with THEN, otherwise replaces statement with ELSE.
   * iff - Mathematical shorthand for "If And Only If"

That last boolean operator?  It's actually shorthand for the conditional statement.  Here's the syntax:
Code: [Select]
condition ? outputIfTrue : outputIfFalse

That whole block doesn't quite work like a normal conditional.  In a normal conditional, Java executes code based on whether the condition is true or false.  In this, Java replaces that whole statement with either the code for outputIfTrue or outputIfFalse based on whether the condition is true, using the first for true and the second for false.  Here's a quick example:
Code: [Select]
System.out.println("\nEleventh Example");
/*
 * There is an entirely different, shorthand
 * way to handle conditionals.  It is
 * traditionally know as ?: notation.
 *
 * This is an inline notation that I can plug
 * directly into println.
 */
System.out.println(condition ? "\tPass" : "\tFail");

Because I promised, here's the code for the conditionals I've been excerpting from.
Spoiler (click to show/hide)

Post Epilogue

There's a huge amount of information here and I'm sure I missed some things.  If it's anything important, I'll come back to it.  Promise.  Conditionals are one of those very, very big topics.  Kind of like the next topic (arrays, loops, math stuff I forgot) probably will be as well.  As always, please ask questions and please give comments.

I wanted to do some more creative things, but this lesson got really long, really fast.  I'll show cool tricks later, I guess.  Particularly, I really wanted to talk more about XOR.  You can basically use it to replace conditionals if you know what you're doing.  I'm also holding off on switch statements for now, but that should come fairly quickly as well.  This took far too long to write and got really long, so I'm breaking my habit of having two chapterlets per update.
Logged

Max White

  • Bay Watcher
  • Still not hollowed!
    • View Profile
Re: if self.isCoder(): post() #Programming Thread
« Reply #173 on: January 08, 2012, 06:33:30 pm »

If you are going to put Strings and conditions into the same lesson, you should explain why
Code: [Select]
String name = System.in.readln()
if (name == "Max")
{
System.out.println("Welcome!")
}
else
{
System.out.println("GTFO")
}

will not work as intended, instead requiring a function.

Although c# uses don't worry about that so much, it totally works as you would expect in c#.

MagmaMcFry

  • Bay Watcher
  • [EXISTS]
    • View Profile
Re: if self.isCoder(): post() #Programming Thread
« Reply #174 on: January 08, 2012, 06:57:09 pm »

Programmers are lazy bums.  We don't want to type anything more than we really have to.  "If I can understand what it's supposed to do, why can't the computer".  Hence, we created a method of not having to explicitly ask whether a boolean is true or false.  If you input the boolean name on it's own, Java is assuming you want to know if it is true.
Code: [Select]
System.out.println("\nSixth Example");
/*
 * You don't have to ask it whether the boolean
 * is true explicitly.  Java will implicitly
 * ask that if all you do is enter the boolean
 */
if ( condition ) {
System.out.println("\tCondition Passes");
} else {
System.out.println("\tCondition Fails");
}


Actually, this is not even special or lazy behaviour.
The if only needs a boolean value (not an equation) to decide which block will be run, and for this purpose, condition evaluates to a boolean (because it it one) and is therefore just as valid as condition == true. In this case, the two statements are completely exchangeable and will probably get optimized to the same bytecode anyway.

I know you know that, Stargrasper, but it's probably better to keep stuff consistent so people won't try to memorize special syntax that isn't even special, it'll just confuse them. In this case, people could think that all if statements require a comparison operator. This isn't bad per se, but people could go on to think that comparison operators only belong in if statements. I had this exact same misinterpretation for a while when I was 11 and just learning Perl.
Logged

Max White

  • Bay Watcher
  • Still not hollowed!
    • View Profile
Re: if self.isCoder(): post() #Programming Thread
« Reply #175 on: January 08, 2012, 06:59:58 pm »

thus
Code: [Select]
boolean condition = (1 == 2);is totally legal, on the basis that the == operator returns a boolean.

Programming is cool.  :P

Stargrasper

  • Bay Watcher
    • View Profile
Re: if self.isCoder(): post() #Programming Thread
« Reply #176 on: January 08, 2012, 07:05:19 pm »

If you are going to put Strings and conditions into the same lesson, you should explain why
Code: [Select]
String name = System.in.readln()
if (name == "Max")
{
System.out.println("Welcome!")
}
else
{
System.out.println("GTFO")
}

will not work as intended, instead requiring a function.

Although c# uses don't worry about that so much, it totally works as you would expect in c#.

Short answer: it doesn't work because System.in.readln() does not exist.

Longer answer: You mean let someone enter a string into the console a la C++ cin, right?  I was going to say I've never used System.in.readln(), but it appears there's no such thing in Java...  So are you asking something else or are you using the wrong command?  I'll look into entering and reading from the console, but I've honestly never done it before in Java.  I was originally taught that if I want user input I should either pass it as a command line argument, read it from a file, or read it from a JOptionPane or other GUI element.

Beyond that, I'm not up to methods.  The only methods I'm using so far are main() and System.out.println(), both of which count as magic until I get around to the methods lesson.

Programmers are lazy bums.  We don't want to type anything more than we really have to.  "If I can understand what it's supposed to do, why can't the computer".  Hence, we created a method of not having to explicitly ask whether a boolean is true or false.  If you input the boolean name on it's own, Java is assuming you want to know if it is true.
Code: [Select]
System.out.println("\nSixth Example");
/*
 * You don't have to ask it whether the boolean
 * is true explicitly.  Java will implicitly
 * ask that if all you do is enter the boolean
 */
if ( condition ) {
System.out.println("\tCondition Passes");
} else {
System.out.println("\tCondition Fails");
}


Actually, this is not even special or lazy behaviour.
The if only needs a boolean value (not an equation) to decide which block will be run, and for this purpose, condition evaluates to a boolean (because it it one) and is therefore just as valid as condition == true. In this case, the two statements are completely exchangeable and will probably get optimized to the same bytecode anyway.

I know you know that, Stargrasper, but it's probably better to keep stuff consistent so people won't try to memorize special syntax that isn't even special, it'll just confuse them. In this case, people could think that all if statements require a comparison operator. This isn't bad per se, but people could go on to think that comparison operators only belong in if statements. I had this exact same misinterpretation for a while when I was 11 and just learning Perl.

You know, there's a paragraph in the lesson somewhere that explains this.  It starts with the phrase "I lied to you".

My experience is that it's best to teach new programmers to evaluate the expressions for the value they want rather than directly plug in the boolean.  It makes more sense to them because it's explicit and self-documenting.  I'll look at that section of the text and consider re-writing it.

thus
Code: [Select]
boolean condition = (1 == 2);is totally legal, on the basis that the == operator returns a boolean.

Programming is cool.  :P

Yep.  Neat, huh?  For the curious, that resolves to condition = false because 1 does not equal 2.
Logged

MagmaMcFry

  • Bay Watcher
  • [EXISTS]
    • View Profile
Re: if self.isCoder(): post() #Programming Thread
« Reply #177 on: January 08, 2012, 07:08:24 pm »

thus
Code: [Select]
boolean condition = (1 == 2);is totally legal, on the basis that the == operator returns a boolean.
Or this:
Code: [Select]
boolean condition = (true == false) == (false == false);

You know, there's a paragraph in the lesson somewhere that explains this.  It starts with the phrase "I lied to you".
Oops. Must have skipped that paragraph.
Logged

Max White

  • Bay Watcher
  • Still not hollowed!
    • View Profile
Re: if self.isCoder(): post() #Programming Thread
« Reply #178 on: January 08, 2012, 07:09:47 pm »

Short answer: it doesn't work because System.in.readln() does not exist.

Longer answer: You mean let someone enter a string into the console a la C++ cin, right?  I was going to say I've never used System.in.readln(), but it appears there's no such thing in Java...  So are you asking something else or are you using the wrong command?  I'll look into entering and reading from the console, but I've honestly never done it before in Java.  I was originally taught that if I want user input I should either pass it as a command line argument, read it from a file, or read it from a JOptionPane or other GUI element.

Beyond that, I'm not up to methods.  The only methods I'm using so far are main() and System.out.println(), both of which count as magic until I get around to the methods lesson.

What? Fuck hold on, BRB. FUCKING JAVA! Why you no consistent? This is why I always rage at Java, you need to spend 5 hours reading over the docs.
No, what I mean is that it will always return false because it is comparing the locations of the strings, rather than the content of the strings.

Stargrasper

  • Bay Watcher
    • View Profile
Re: if self.isCoder(): post() #Programming Thread
« Reply #179 on: January 08, 2012, 07:17:48 pm »

thus
Code: [Select]
boolean condition = (1 == 2);is totally legal, on the basis that the == operator returns a boolean.
Or this:
Code: [Select]
boolean condition = (true == false) == (false == false);

You know, there's a paragraph in the lesson somewhere that explains this.  It starts with the phrase "I lied to you".
Oops. Must have skipped that paragraph.

Yep, that works too.  You actually reminded me of something I forgot to put in the tutorial.  I'll have to edit it in.

If checking multiple condition with AND and the first is FALSE, then the second is not evaluated.  If checking multiple conditions with an OR and the first is TRUE, the second is not evaluated.
Code: [Select]
// The second statement is not evaluated in this situation
// because with the first being false, the overall statement
// cannot be true.
// So Java doesn't bother evaluating the rest
if ( false && true )

// Same here.  If the first statement is true, the whole statement
// cannot be false, so the second statement is not evaluated.
if (true || false)

Okay, you (hopefully) found the paragraph.  Do you still think I should move it earlier, re-write it, otherwise clarify it?

Short answer: it doesn't work because System.in.readln() does not exist.

Longer answer: You mean let someone enter a string into the console a la C++ cin, right?  I was going to say I've never used System.in.readln(), but it appears there's no such thing in Java...  So are you asking something else or are you using the wrong command?  I'll look into entering and reading from the console, but I've honestly never done it before in Java.  I was originally taught that if I want user input I should either pass it as a command line argument, read it from a file, or read it from a JOptionPane or other GUI element.

Beyond that, I'm not up to methods.  The only methods I'm using so far are main() and System.out.println(), both of which count as magic until I get around to the methods lesson.

What? Fuck hold on, BRB. FUCKING JAVA! Why you no consistent? This is why I always rage at Java, you need to spend 5 hours reading over the docs.
No, what I mean is that it will always return false because it is comparing the locations of the strings, rather than the content of the strings.

And...no...Java treats String so much like a primitive that it does the equals check for you correctly.  I tested this earlier with the following code and simply opted not to include it in the tutorial.
Code: [Select]
String s1 = "foo";
String s2 = "foo";
System.out.println(s1 == s2);
System.out.println(s1.equals(s2));
Both println() statements return TRUE;
Logged
Pages: 1 ... 10 11 [12] 13 14 ... 795