Register for your free account! | Forgot your password?

Go Back   elitepvpers > Off-Topics > Tutorials
You last visited: Today at 14:13

  • Please register to post and access all features, it's quick, easy and FREE!

Advertisement



Java Beginner code written better

Discussion on Java Beginner code written better within the Tutorials forum part of the Off-Topics category.

Reply
 
Old   #1
 
elite*gold: 0
Join Date: Feb 2010
Posts: 475
Received Thanks: 370
Java Beginner code written better

n fact this is no tutorial as I won't show you how to build a program or accomplish a predefined result.
This will just be a (short) list of code, that works, but could be written shorter and looks better.

This "tutorial" is aimed at the very new Java coders as I think that most people who do Java for a while will have figured this out by themselves.
Each part consists of 2 code-blocks. 1 with "someMethod()" containing the code a beginner might write.
Then the 2nd code-block with a "betterMethod()" containing the shorter/cleaner code.


Changing a boolean to true or false depending on its current value.
How it COULD be written:

Code:
 private boolean playerTurn;
    
    public void someMethod(){
        if(playerTurn == true){
            playerTurn = false;
        } else {
            playerTurn = false;
        }
    }
Better it would be when the if-statement was rewritten like:

Code:
 if(playerTurn){
Because that does the same thing.

But the betterMethod is:

Code:
 private boolean playerTurn;
    
    public void betterMethod(){
        playerTurn = !playerTurn
    }
So playerTurn is Not playerTurn. True becomes not true => false, and false becomes not false => true.


Strings that could be null but you need to use equal
First of all you should try to initialise your Strings with an emptry String if it shouldn't contain anything.
That way you won't encounter NullpointerExceptions there. If for whatever reason you could get nullStrings, you may write:

Code:
 private String possiblyNull;

    public void someMethod(){
        if(possiblyNull != null){
            if(possiblyNull.equals("good")){
                System.out.println("The string is ok.");
            } else {
                System.out.println("The string is not ok.");
            }
        } else {
            System.out.println("The string is not ok.");
        }
    }
You can't do possiblyNull.equals("good") Before checking for null because if the String turns out to be null, an exception will be thrown.
This method totally works fine. It's just bad that you have to write System.out.println("The string is not ok."); 2 times.
...And the method is quite large for the amount of stuff it's really doing.
This can better be written as:

Code:
 private String possiblyNull;

    public void betterMethod(){
        if("good".equals(possiblyNull)){
            System.out.println("The String is ok");
        } else {
            System.out.println("The String is not ok");
        }
    }
Unless you need to treat a null differently, the you have no choice but the first method.
By turning the statement around, possiblyNull can be null without causing the program to crash.
"good".equals(null) Will just return false.


Arrays of whatever and filling it.
Believe me you will not be the first one to fall for this..."mistake". I too did this for a very long time. Imagine if you have to keep 50 scores in your program, so you create an array of 50 integers.
And you also have to store 10 players, so you have another player array.
Both arrays should be filled at the start. the scores with 0 and the players with "new Player()".

You may write it as:

Code:
private int[] scores;
    private int[] players;

    public void someMethod(){
        scores = new int[50];
        players = new Player[10];
        
        for(int i=0 ; i<scores.length ; i++){
            scores[i]=0;
        }
        for(int i=0 ; i<players.length ; i++){
            players[i]=new Player();
        }
    }
Again nothing wrong with it, I did it for over a year like that.
But actually that can be much shorter with the use of the Arrays class:

Code:
  private int[] scores;
    private int[] players;

    public void betterMethod(){
        scores = new int[50];
        players = new Player[10];

        Arrays.fill(players, new Player());
    }
int types have a 0 in them by default so you shouldn't have to do anything for that.
And that's it, the Arrays class does the work for you. You may need to import java.util.Arrays; if the compiler is complaining. Arrays also contains methods for sorting, changing an array in a List and other useful methods.
The Collections class has pretty much the same methods but for Collections.


Know the StringBuilder
This won't be with someMethod and betterMethod. I just want to let you know the StringBuilder class.
Because when you start learning java, Strings are used A LOT. Your teacher propably wants you to make stuff with the console as your "GUI". --> String based propably.
It won't be the first teacher that gives you the assignment to do stuff with Strings like
put a character in the middle of the String. word.substring(0,i) + "inTheMiddle" + word.subString(i, word.length());
Reverse the string (teacher now thinks: "Oh that will involve some nice looping, let's make the students think hard")
Remove certain letters in the String.

Unfortunately the String class is, relatively, limited in its functionallity. Luckily there is the StringBuilder class which has a good amount of very useful methods you can use to change a String.
It's created like so:

Code:
String sentence = "What a long sentence.";
StringBuilder sb = new StringBuilder(sentence );
Then you can do all the things you want to do with the String with the StringBuilder:
reverse
Code:
sb.reverse();
insert "very" between "a" and "long"
Code:
sb.insert(7, "very ");
remove a letter
Code:
sb.deleteCharAt(7);
[color=red]replace a letter[/color]
Code:
sb.setCharAt(7, 'k');
or all this stuff, without the StringBuilder, you were looping or messing with subStrings. This is just much easier.
To get a normal String from the StringBuilder you just call the .toString() method on it, and it will return the String it currently has.


That'll be it for now, thanks for reading.
I hope you learned something new here.
XxXchowXxX is offline  
Old 02/19/2012, 19:21   #2
 
-J0ker-'s Avatar
 
elite*gold: 0
Join Date: Dec 2008
Posts: 1,390
Received Thanks: 333

copy and paste ?
Thats poor dude
-J0ker- is offline  
Reply


Similar Threads Similar Threads
Beginner Java: Displaying a 2D background
02/19/2012 - Tutorials - 0 Replies
Displaying a 2D Background Difficulty: 2 / 10. Assumed Knowledge: basic knowledge of the Java language. Information: This tutorial will teach you how to create a basic API and display an image. What is an API..? An application programming interface (API) is an interface implemented by a software program that enables it to interact with other software. It facilitates interaction between different software programs similar to the way the user interface facilitates interaction between...
Java Code Search Request
01/06/2012 - General Coding - 9 Replies
Hallo Ich bin noch nicht ganz fit mit java, deswegen wollte ich euch bitten mir ein wenig hilfe zu geben. Und zwar werden seit gestern die Packete von DarkOrbit verschlüsselt, die ich natürlich entschlüsseln möchte. Nun hatte ich versucht den Weg zu verfolgen, bin zwar ein wenig weiter gekommen, doch immer noch nicht am Ziel. Das ganze kommuniziert über ein XMLSocket. Hier die HauptDatei: http://do.a.bpcdn.net/spacemap/main.swf
[Source Code] Zahlensystem Rechner [Java]
11/07/2011 - General Coding - 2 Replies
Schaut es euch an und ich wäre froh wenn ihr Verbesserungsvorschläge habt Auch wenn ihr Fragen habt bin ich natürlich bereit diese zu beantworten. Eine Erklärung zu dem Code befindet sich in den Kommentaren. Vllt kann es jemand gebrauchen, vllt aber auch nicht :P import java.awt.*; import java.awt.event.*; import javax.swing.*; import java.lang.Object.*;
Best code language for a beginner?
12/01/2010 - General Coding - 1 Replies
Hello coder community. I'm wondering what the best language for a beginner is to learn? Why, and where is it useful? Can i find online tutorials somewhere, in English? I'm a total beginner, i have opened programs like c+ and visual studio's only once or twice!
[Java] Code-Beispiele für String, Arrays und und...
06/02/2010 - Coding Tutorials - 9 Replies
Joa, da ich Heute meine Informatik Prüfung in der Uni hatte ( und es sollte wohl min. eine 2 raus gekommen sein ) hatte ich Gestern so in ner Stunde einige Code Beispiele für verschiedene Dinge geschrieben. Eins war wie man Strings verarbeiten kann, was man mit Arrays anstellen kann und noch so paar Allgemeine Sachen zur Vererbung und Klassen. Man sollte das hier nicht unbedingt als Tutorial sehen da ich euch eigentlich hier einfach nur Code reinhau den ihr direkt Ausführen könnt wenn ihr...



All times are GMT +2. The time now is 14:13.


Powered by vBulletin®
Copyright ©2000 - 2024, Jelsoft Enterprises Ltd.
SEO by vBSEO ©2011, Crawlability, Inc.
This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

Support | Contact Us | FAQ | Advertising | Privacy Policy | Terms of Service | Abuse
Copyright ©2024 elitepvpers All Rights Reserved.