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

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

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


     scanner = new Scanner(;

         System.out.println("Whoops! nothing to read!");

     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 🙂 !


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.

The Magic of Computers

September 28, 2008

I had some plans that were cancelled today so I found myself with some extra time, and decided to write about something that was on my mind a day ago.

When I think of magic I don’t typically think of computers. They are rather finite machines that can only do an assigned task. However, it was my initial enchantment with computers that led me in to the major I am in. Wondering exactly how a window was opened, wondering how the computer booted, wondering how to install software, etc. This is the stuff that kept me wanting more which brought me deeper in to the world of computers.

I find that as I move further in the computer science world, and in my experience as a coder, some of the magic gets lost amongst the code and the understanding of how things work. I no longer find it impressive when I compile my code and run it from a terminal. No longer do I stare at a scene in a video game and wonder how everything fits together. I can assemble and repair a computer and it doesn’t seem terribly difficult or nerve racking.

I started thinking about these things a day ago when I had to recompile my kernel to add support for an old floppy drive. For some reason it brought back memories of when I first compiled the Linux kernel (yay Gentoo Linux ^_^). I got such a sense of accomplishment out of watching my computer boot from the configuration I just devised out. That magic has been lost on me because since then as I recompile the kernel as if nothing is special about it. Even more than that I did it through several ssh tunnels I had configured to allow me off campus access to my dorm room computer. I gave none of this even a second thought I just knew it was what I had to do. The magic of all those things has been lost. I’m sure anyone who was around me when I learned about ssh, or more recently the -D, -L, and -R flags could have told you I was like a kid in a candy store. Absolutely enchanted by the assortment of options I had just been given, and never content just trying one particular flavour or style. I desired to know the ins and outs of ssh and every additional piece of information was as awesome as the last.

Why do I write all of this? Well, during my pondering I couldn’t help but wonder what would happen if I understood so much that I never found magic in computers. Even though certain aspects of computing no longer excite me the way it used to I know there are many more areas that are littered with things for me to explore. I remember reading an interview with one of the Gentoo devs on He was saying that now that he works on all this essential tools he longer sees the magic in computers. I don’t think he was particularly bothered by this, but it struck me as sort of a sad thing. I LOVE discovering new commands and gaining knowledge about computers. It is one of the things that keeps me coming back for more. I often feel that there is no way I could ever learn everything about computers (or come close), and I sincerely hope that is true.

I always enjoy seeing a new CS student delight in some of the awesome things you can do with ssh, or to see their excitement in finally getting a tricky program to just compile (let alone run). It reminds me much of myself, and I think it is those sorts of people that will be most fulfilled in jobs as computer scienctists, but also the people that will require the most fulfillment out of their job to continually enjoy working somewhere. With any luck I hope to find that in a job, but I don’t expect I will land a programmers dream job straight out of college either.

I suppose only time will tell, as they say 🙂 .

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 @ )

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.

How I Shortened the ‘iwlist scan’ Output

August 4, 2008

Edit [03-04-2012]: I had a request (see comments) to include the channel and frequency. I added them, but unfortunately, I didn’t see a way to  make the script output be 80 characters wide like the original. So, here are the two versions:

Additionally, now that I have looked at the code for the first time in a while, I must apologize for how poorly it is written :). After seeing what a mess I made the first time, I think I’d like to take a stab at cleaning it up and improving it a bit. So, hopefully, I’ll be able to write a more refined version in the coming months.

Edit [09-09-2012]: Updated link to script.

Edit [02-11-2009]: Updated the script to fix a small parsing bug.

In the past few years I have noticed that Linux has come a LONG way in support for wireless cards. I no longer read long stories about how 5 hours and 2 kernel patches later someone finally got their wireless card working.

In fact, I distinctly remember my first experience trying to get my wireless card to connect to a WPA network. It was my freshman year at college, and I spent almost an entire weekend digging through documentation, forum posts, config files, and google search results trying to get my laptop on the campus network through wireless. When all was said and done all I had was a script which was a simple bash script that ran all the commands I needed to connect. It had to be run as root (didn’t know about sudo) and it was a real hack. 3 and 1/2 years later and I simply boot up my laptop and it connects to any network I have predefined in my wpa_supplicant.conf file. I can walk around and it will automatically connect to new network, restores lost connections, etc.

One thing has always been a bit of a bother to me however. That is that the output of ‘iwlist scan‘ is quite lengthy. I can’t ever fit more than 2 wireless networks on a screen (unless I make my terminal super long)! Here is some sample output (MAC Address and actual network name hidden):

Cell 01 - Address: 00:00:00:00:00:00
   Protocol:IEEE 802.11bg
   Frequency:2.462 GHz (Channel 11)
   Encryption key:on
   Bit Rates:1 Mb/s; 2 Mb/s; 5.5 Mb/s; 6 Mb/s; 9 Mb/s
             11 Mb/s; 12 Mb/s; 18 Mb/s; 24 Mb/s; 36 Mb/s
            48 Mb/s; 54 Mb/s
   Quality=33/100  Signal level=-80 dBm
   IE: WPA Version 1
        Group Cipher : CCMP
        Pairwise Ciphers (1) : CCMP
        Authentication Suites (1) : PSK
      Extra: Last beacon: 36ms ago

I am not trying to start a flame war with the writers of iwlist. I think they have a very great tool, but sometimes I just want to know what networks are available in a simple form of output. So, since I had a bit of free time I decided to write a simple little perl script to grab the output of ‘iwlist’ and contort it until I got following output:

+ --- + ---------------------- + ------- + -------- + --- + ------ + --------- +
| #   | Name                   | Quality | Sig Lvl  | Enc | Enc T. | Auth T.   |
+ --- + ---------------------- + ------- + -------- + --- + ------ + --------- +
| 1   | "network 1"            | 39/100  | -77 dBm  | off | WEP    | N/A       |
+ --- + ---------------------- + ------- + -------- + --- + ------ + --------- +
| 2   | "network 2"            | 100/100 + -30 dBm  | on  | WPA v1 | PSK       |
+ --- + ---------------------- + ------- + -------- + --- + ------ + --------- +

So simply running my script will produce that nice, little, easy to read, fits-inside-an-80-character-terminal output. I am not entirely proud of all the perl code I used to write the script, but it works for what it does. I’m sure a true perl expert (which I am anything but) could have written it in under 10 lines, but hey, no one is perfect ;).

I often find myself torn when writing a short little utility script like this. I want to write good code, but I don’t want to spend all day writing a simple little script. I already took shortcuts in the form of using global variables, but I use function calls that only have one line of code in them. In retrospect I think it would have been smarter to just not worry about the functions, but it would take time to go convert it back to be functionless :-P. I will just have to live with the code for now, and be happy that it does what it does.

As another feature of the script it will give you the full output of a single network from the full ‘iwlist scan‘ output if you just specify the number of the network as a command line argument :).

Here is a link to the script, if you are interested: I had to post it as a .html file because apparently my school does not allow you to have perl files accessible from their apache server. No worries though. Some day I will have my own little web setup which I will manage and then I won’t have to worry about things like this 🙂

Anyway, hopefully this perl script will come in handy for one or two people or, at the very least, give the perl guru’s something to make fun of :). That’s all for now!

Sidenote: Since it’s so short I didn’t bother to put it under the GPL, but come on… it’s a small perl script for an open source utility. Obviously for this script to work you must have iwlist on your system, and perl installed 🙂