Java Scanner class and Standard In Troubles

January 25, 2009

I ran into a bit of trouble today with the Java Scanner class that I thought was worth mentioning. Personally I really like the Java Scanner class because it is a great way to easily read from standard input (stdin). In specific the issue I had was that I noticed the Scanner class allows you to close stdin. This is the part I found problematic. Consider the following code from Test.java:

import java.util.Scanner;
public class Test
{
    public static void main(String args[])
    {
     Scanner scanner = new Scanner(System.in);

     System.out.print("Enter a number: ");
     System.out.println("Your number was: " + scanner.nextInt());

     scanner.close();

     scanner = new Scanner(System.in);

     if(!scanner.hasNext())
     {
         System.out.println("Whoops! nothing to read!");
         System.exit(1);
     }

     System.out.println("Things seemed to  have worked correctly.");
    }
}

When you run this code what you will notice is that after you enter the first number the program goes straight into that if statement. This is not what we might expect however because the has<something> functions are supposed to hang until something is typed.

The reason for this is the call to scanner.close() which ends up closing standard in. To be honest I’m not sure how this would work on a Windows system, but I know it was a bit of a problem for me on my Linux box. The simple fix is to just not call .close() , but since it is normally good practice to close things you opened I didn’t think much of it when I first wrote the code. I guess we didn’t technically open stdin, so perhaps that is the correct way to look at it .

At any rate I wouldn’t call this a bug of Scanner, but simply something to look out for when using the Scanner class.

Happy coding 🙂 !

Advertisements

Rocks — One Dimensional Asteroids Game

December 17, 2008

Yes, you read the title correctly, I will be writing about a little game I wrote called “Rocks”. As far as I know, Rocks is the first implementation of one dimentional asteroids. This is indeed a great day in video gaming history. Well, not really, but it is a great day for people who take jokes much further than intended!

So, a bit of background… Rocks started as a joke while a fellow cs student and 2 of our professors were driving back from a conference. I was bored and looking to program something quickly, preferably a game. The idea of one dimensional asteroids was thrown around and I was interested in making it ASCII based. Thus, Rocks was born. Sadly, I didn’t have much time to work on it after that car ride (where my laptop battery died). Since then, the semester has ended and I was able to complete the game. So, behold, a Rocks screen shot (Full Resolution Screenshot):

Rocks Screenshot

Rocks Screenshot

Rocks has a dependency on the curses libraries, but most Linux systems have that sort of thing installed. I have a downloadable version of Rocks which has been released under the GPLv3. In the tar.gz file you will find a complied version of rocks for x86 Linux and all of the source code with a (very) simple Makefile.

If you happen to play it let me know what you think 🙂 . Rocks gets harder the longer you play and can actually get challenging. So if you think it’s too easy then play for a few more minutes and you will see it get harder!

Enjoy!

Rocks Download: rocks.tar.gz


Emulating Recursion on the TI-84+

November 30, 2008

Yes… it’s true I think about these things in my free time. It actually happened in the middle of a math class I was taking. We were talking about the Fibonacci sequence and I was thinking that it would be neat to have a recursive implementation on my calculator. Now, I know that the iterative approach is actually faster, but the idea of a true recursive implementation was a fun idea. Now, it may be possible using assembly programming for the calculator, but I don’t really know how to do that.

After a little bit of thinking I decided that programming with the calculator BASIC reminded me a bit of MIPS assembly (I can hear some people groan already). You see the calculator lists can be used as a make shift stack and since all the variables A – Z are global you can simply designate one of those as your “stack pointer”. So I adopted the convention that the S variable is the stack pointer and that the R variable is for returning values. Anything else is fair game. I suppose if I really wanted to put thought into this I would pick some of them as temporary and others for function arguments. However I didn’t want to spend that much time working on this.

The basic idea here is that when you want to call a function (IE another program) at the beginning of your function you simply preserve the state of any variables you wish to change by using the list. I happen to use L5, but you could use any list you wanted. The stack pointer starts at 0 and each time you add to the list to increment the stack pointer by the number of items you added. Then at the end of your function you restore the state of any variables you used and “return” by setting the R variable to be the return value.

Now this has some limitations. First of all the TI-BASIC is quite slow even on my 84+ Silver Edition. The second is that a list can only hold 1000 elements so your stack is essentially size 1000. That being said it is still fun to play around with the idea of recursion or the more broad idea of function calls. For instance I wrote a program to do prime factorization which uses a helper program to tell if a number is prime or not.

Here is the code of the main program FIB which is the recursive Fibonacci number finder:

:ClrList L6
:ClrHome
:
:Prompt A
:
:"SET STACK PTR
:1 => S
:
:"GET FIB NUM
:prgmFIBR
:Disp R

Now here is the program which does the real work, FIBR:

:"STOPPING
:"CONDITION
:If A<=2
:Then
:1 => R
:Return
:End
:
:"PUSH VARS
:"ON STACK
:A => L6(S)
:B => L6(S+1)
:T => L6(S+2)
:"Increase stack pointer
:S+3 => S
:
:A => B
:0 => T
:
:"FIBR(n-1)
:A-1 => A
:prgmFIBR
:T+R => T
:
:"FIBR(n-2)
:A-1 => A
:prgmFIBR
:T+R => T
:
:T => R
:
:"POP VARS
:"OFF STACK
:L6(S-3) => A
:L6(S-2) => B
:L6(S-1) => T
:
:"DEC. STACK
:"POINTER
:S-3 => S

If you actually went through the trouble of putting this into your calculator you run the program FIB and enter a positive integer. The program will then return the nth fibanocci number. This is a simple program but I think it gets at the idea of recursion. In any case it doesn’t have too practical a purpose it’s just for fun 🙂


Euler Project

November 20, 2008

As pointed out by Wes it has indeed been some time since I posted anything on this blog. About once a week it occurs to me that I would really enjoy writing about this or that, but I just haven’t had the time lately. Part of the reason is how long it actually takes me to get a post up. It typically takes me around 30 to 40 minutes to write something mildly interesting, and then another 10 or 20 to proof read it. It is not as if I couldn’t find that sort of time, but typically I only have it at night, and when I am tried I find it very hard to concentrate on what I am writing 🙂

In any case I want to write about Project Euler today. About a week ago my Professor introduced to to Project Euler. They have a list of computer science and math problems that they ask you to solve, and typically the problem involves you needing to have some sort of mathematical intuition as well as coding skill. One simply makes an account on their site and when you think you have a solution to the problem you submit your answer and the site tells you if you got the right answer or not. So far I have been working on the earlier problems in the list when time permits. For a lot of them I tend to hack together a solution in Python within 5 to 10 minutes. I have heard the later problems get harder, and I await the challenge. Project Euler meets the strange need to write random small computer programs that perform an operation which is “cool” to only a small group of people. I also like the mathematical challenges that some of the problems provide, and it gives me a good test of my problem solving skills, which I think are very important to any computer scientist. The other interesting part to these problems is that Project Euler guarantees that your program should find a solution in under one minute of run time. This adds an extra challenge because you can’t necessarily brute force the answer :).

While writing solutions to these problems I have noticed how much slower Python is than C in certain cases. I have read many different guides to optimizing Python code and applied optimizations everywhere I can, and still the C equivalent to my solutions  runs drastically faster. I am not suggesting that C is necessarily a better language or something. Certainly, one expects a compiled language to outperform a scripting language, but since I had never done any formal study before I found this quite interesting. I do enjoy the speed at which I can throw together the solutions in Python, and I’m glad I taught myself Python a year or two ago because I have used it many times since then.

Anyway, I have a lot more to write about, and have been keeping a list. Hopefully over Thanksgiving break I will be able to put in an entry or two. At the very least when this semester ends I will have plenty of time to write blog entries and plan to be more active during that time.


Back to C++

September 10, 2008

It has been a while since I have had the time to sit down and write something here so I figured now is as good a time as any. I actually have class in a bit, but I figured I would be able to get something down of mild interest before I leave.

As one of my final computer science classes before I graduate I am taking a class based largely in theory. Mainly we will be studying NP-Complete problems, but we will study some other topics as well, which I may blog about when the time arrives. Until a few days ago we did not actually have any homework assignments which involved programming 😦 .

The assignment we did get, though, was pretty interesting. The basic idea behind it is that you must take the string 123456789 and insert +’s, -‘s, or nothing in between digits. Also, for our class, you could also place a – or + sign in front as well (though the + doesn’t really do anything) . You must generate all possible combinations of this string and find the smallest possible positive integer that you can create in this way. This required us to implement an algorithm (which we learned in class) that can be used to generate all possible combinations of some arbitrary set (i.e. the power set). We were allowed to write this program in any language of our choosing. I joked around saying I would try and write it in MIPS assembly or LISP. I did seriously consider LISP, but I lacked the ambition to relearn it. In the end I decided to write this in C++.

My design of the problem wasn’t anything noteworthy, and that is not really the point of my writing this post. I simply really enjoyed writing C++ code again. It took me a little bit to get back in to the spirit of things, but once I remembered the little syntax quirks and general coding style I was loving every minute of it. This program did not take all that much time to program, nor was it particularly challenging. Perhaps I just have a sentimental feelings for C++ as it was always a language I had aspired to learn since I started programming in the 8th grade. I was extremely pleased that my college offered it as a course. Sadly, the intro level classes are now taught in Python, which I have mixed feelings about. I’m not sure if a language will come along that I will ever like more than C++, but who knows what is on the horizon.

C++ just seems to be the best combination of two worlds of programming that I enjoy. The low level access to memory, variables, other reasources of C, and with support for OO style programming. I know some would argue those should never be combined. For me I just like knowing that if I need to access the low level stuff it is readily available, and that I do not have to jump through hoops to use it. With an OO language I know that you are typically trying to write high level code, and I would say that is true for me most of the time. However, access to pointers can really come in handy in certain circumstances. Yes, I know there are workarounds for other languages, but it is convient to have them right at your finger tips.

Perhaps I am just holding on to my past, but I sure do enjoy coding in C++ 🙂 .


Spheriosity and Ant Build Files

August 18, 2008

While I was on vacation a few weeks ago I decided that I wanted all of the code in Spheriosity to look pretty inside an 80 character emacs buffer. I started out coding it in Eclipse (reluctantly) because it was the only way I could get the Java3D stuff to compile and I didn’t have time to play around with getting it to work command line. I planned to still use Eclipse even after the 80 character conversion, but alas the code does not like right in Eclipse anymore. So I decided to bite the bullet and start coding in emacs again.

This meant that I had to have a way to build the code from the command line so, naturally, I turned to ant since that seems to be the ‘Java way’ to compile projects larger than Hello World. I have very mixed feelings about Ant which is most of the reason for my post. The XML configuration does not do much for me. I don’t like the way XML config files (especially the way Ant does it) look. They all seem to be too syntax heavy for what they are trying to do. Prior to using Ant I had used make, which now that I have used Ant, I like even more than I did before. The simplicity of make is enough in itself to make (no pun intended) me want to use it. I want this project to be open source, and easy to build so I needed to use Ant. After messing around with things I was able to get Ant to do what I want well enough, but it seemed a lot harder than it needed to be. Maybe it is just because I am not used to it *shrugs*

Another thing about Ant which upset me is how long it takes to simply start running a target. I have had it take up to a second or two just to run a target that deletes the built source code. I could have typed in the remove command in that amount of time (with the aid of tab completion). This may sound like a trivial matter… a few second here or there, what’s the big deal? Well, when I am testing either the build script itself or parts of the code those few seconds for each recompile or clean or whatever start to take up a substantial amount of time.

Maybe I am judging it prematurely. Only time will tell. I will continue to use it and perhaps it will grow on me 🙂 .


Is C++ an Elitist Language?

August 9, 2008

Recently I made a post about some things in Java that I find to be a bit of an issue. The artcle was reposted on Javalobby and it started an interesting discussion in the comments section. Among other things, one comment in particular struck me as disconcerting:

When you use a language you should ask yourself what is the feeling of it. C++ is an elitist language with strong roots in the procedural C (that should compile in C++), and a big focus on performance. Java  is a full Object Oriented langage inspired mainly by C++ and smalltalk, which was for a long time pretty slow, and focus on writing big maintainable programs via simplicity and strong typing. ( A comment by Raphael_Lemaire @ http://java.dzone.com/articles/sometimes-java-makes-me-sad )

Specifically the part about C++ being elitist. Now, I love C++, so of course I am biased. However, I never thought of it as being elitist. The funny thing is that the syntax of C++ is very close to that of Java, does that mean Java is elitist? As far as I see it the real difference is that Java: offers you loads of libraries, memory management, and it allows the coder to not have to think about pointers. Lets look at each of these issues.

The first issue, of libraries, I don’t really consider much of an issue. Especially if you use open source libraries there are hundreds of libraries which are readily available. Certainly the Java libraries are nice, and most, if not all, are guaranteed to be cross platform. However, many of the C++ ones are as well so I also consider that argument to be a moot point. The fact that you have to compile them for each  different platform can be a problem at times, but I consider it a minor problem especially given the speed of modern computers.

The second issue of memory management is something that goes to Java’s favor. I think, however, that it is a minor issue in the scheme of things. Once you understand the basic idea of memory management, and as long as you use a good programming style which favors allocating and freeing memory in the same place, this isn’t as big of a deal. I have written that you can leak memory in Java too, so Java is not free of this nuisance either! Therefore Java coders who think that are impervious to problems with memory are just kidding themselves.

Third is the fact that in Java you don’t deal with pointers. Or, rather, you don’t have to think about them even though you deal with them all the time. This is more personal opinion than anything, but I never found pointers to be that difficult of a thing to deal with. Once you get an understanding of them it’s really a trivial matter. I know that some people make a fuss because you have to always be thinking ‘is this a pointer to an object, or the object’, but that consideration has never slowed me down. You make note of it once and then it stays the same throughout.

So what is it about C++ that makes it elitist? Is it the people that write code so convoluted that only an experienced pro can read it? I think this could be a big part of it. No matter what language you use people can always write unnecessarily confusing code. Languages like Java try to help prevent this, but I’m sure it can still be done. Having access to pointers can lead to code that is difficult to read, but I think the problem there has more to do with the coders than the language. Programmers should be wise enough to write readable code, and not blame the language.

Do you blame English when you can’t spell a word? I mean… silent letters, what is up with that? No, you probably blame yourself for not having put in enough time to learn the proper spelling. So why should we blame C++ for people that write obfuscated code? At the end of the day it all comes down to the coder, and whether they want to write good code or not.

The bottom line is that I don’t consider C++ an elitist language,  but rather a language that with some extra consideration can be just as easy to code in as Java.