Jump to content

My first java program!


Guest K1u

Recommended Posts

This was my assignment in APcompsci this i consider as my real first java program because i did not get any help we were basically told to make a program that does these things and i did so here ya are please comment on my style on the second code.

The original one i made for class

// ***************************************************************

// File:  StringManips.java

// Author: Kiumarz Hashemi

//

// Purpose: Test several methods for manipulating string objects

// ***************************************************************



import java.util.Scanner;



public class StringManipsORIG

{

    public static void main (String[] args)

    {   

        String city;

        String state;

        Scanner input = new Scanner(System.in);

        String phrase = new String ("this is a string test.");

        int phraselength;

        int middleindex;    // index of the middle character in the string

        String firsthalf;   // first half of the phrase string

        String secondhalf;  // second half of the phrase string

        String switchedphrase; // a new phrase with original halves switched

    

        // compute the length and middle index of the phrase

        phraselength = phrase.length();

        middleindex = phraselength / 2;



        firsthalf = phrase.substring(0,middleindex);

        secondhalf = phrase.substring(middleindex, phraselength);

    

        // concatenate the firsthalf at the end of the secondhalf

        switchedphrase = secondhalf.concat(firsthalf);

        switchedphrase = switchedphrase.replace(' ','*');

        // print information about the phrase

        System.out.println();

        System.out.println ("original phrase: " + phrase);

        System.out.println ("length of the phrase: " + phraselength +

                    " characters");

        System.out.println ("index of the middle: " + middleindex);

        System.out.println ("character at the middle index: " + 

                    phrase.charAt(middleindex));

        System.out.println ("switched phrase: " + switchedphrase);

    

        System.out.println();

        

        String middle3 = phrase.substring(middleindex-1,middleindex+2);

        System.out.println ("Middle3:" +middle3);

        System.out.print("Enter your city: ");

         city = input.nextLine();

         System.out.print("Enter your state: ");

         state = input.nextLine();

         String hometown = state.toUpperCase() + city.toLowerCase() + state.toUpperCase();

         System.out.println ("Hometown: " + hometown);

         

         

        

   }

}

The one i messed around with and comment on the style i used its very easy for me to read it this way wondering if same for u

// ***************************************************************

// File:  StringManips.java

// Author: Kiumarz Hashemi

//

// Purpose: Test several methods for manipulating string objects

// ***************************************************************



import java.util.Scanner;



public class StringManips

{

    public static void main (String[] args)

    {   

            String city;

            String state;

        

        Scanner input = new Scanner(System.in);

            

            String phrase = new String ("this is a string test.");

        

        int phraselength;

        int middleindex;    // index of the middle character in the string

                

                String firsthalf;   // first half of the phrase string

                String secondhalf;  // second half of the phrase string

                String switchedphrase; // a new phrase with original halves switched

    

        // compute the length and middle index of the phrase

        

        phraselength = phrase.length();

        middleindex = phraselength / 2;



        firsthalf = phrase.substring(0,middleindex);

        secondhalf = phrase.substring(middleindex, phraselength);

    

        // concatenate the firsthalf at the end of the secondhalf

        

        switchedphrase = secondhalf.concat(firsthalf);

        switchedphrase = switchedphrase.replace(' ','_');

        

        // print information about the phrase



System.out.println();

        

        System.out.println ("0r1g1n4l phr4s3: " + phrase);



System.out.println ("l3ngth 0f th3 phr4s3: " + phraselength +

                    " ch4r4ct3rs");

        

        System.out.println ("1nd3x 0f th3 m1ddl3: " + middleindex);



System.out.println ("ch4r4ct3r 4t th3 m1ddle 1nd3x: " + 

                    phrase.charAt(middleindex));

        

        System.out.println ("sw1tch3d phr4s3: " + switchedphrase);

    

System.out.println();

        

            String middle3 = phrase.substring(middleindex-1,middleindex+2);

        

System.out.println ("Middle3:" +middle3);

        

        System.out.print("3nt3r y0ur c1ty: ");

         city = input.nextLine();

         

         System.out.print("3nt3r y0ur st4t3: ");

         state = input.nextLine();

         

            String hometown = state.toUpperCase() + city.toLowerCase() + state.toUpperCase();

         

         System.out.println ("H0m3t0wn: " + hometown);

         

System.out.println ("Created by- K1u");

        input.nextLine();

         

        

   }

}

Link to comment
Share on other sites

Good job on learning java.

Java seems a lot like javascript (except faster) to me.

</blabbing>

It seems like you have pretty good sense of formatting, maybe when I see some more of your apps then i will be able to yell at you about memory leaks and double freed pointers,or is that just us grumpy, mean C guys that have to worry about that :lol:.

Link to comment
Share on other sites

You're doing everything from within main which is rather ugly, but I suppose you haven't reached that part of the course yet. The main problem with sticking everything into one long function is that the function becomes LONG. And yes, even in Java, that's bad. It indicates that you're doing too much.

I feel you should've use main for nothing other than the fetching of data from the user, and passing it on to helpers. There would be one helper that deals with phase thing, and a second one that deals with City and State. Note that you're translating state to uppercase (=slow) twice.

I'll post a version of that program here leter today that actually creates an instance of the StringManipsORIG class in main, and will use that to do its thing.

I personally dislike the leetspeek.

I also personally feel that all comments, even single-line ones, should be on their own line.

Both issues obviously are a matter of taste.

Link to comment
Share on other sites

Good start mate, the first class in any language is always an achievement. That said, I agree with a lot of what Cooper said. Style is a matter of taste but there are a few things you might like to think about (keep in mind these are just some guidelines, feel free to ignore me).

1: Declare all instance variables at the beginning of a class, while all local variables should be declared at the beginning of their respective methods.

2: Good indentation makes code a lot more readable. So as a general rule of thumb, tab in once every time you open a brace, keep everything within that block aligned, then tab out once when you close the block.

3: Java has some pretty nifty (Yes, I said nifty) ways of extracting comments from code i.e. javadoc. However, javadoc requires specific types of comments, which are of the /** */ variety. More info on that can be found here: http://java.sun.com/j2se/javadoc/writingdoccomments/

4: Where to put braces? Well, I'm not even going to get into that one. Some people say you should open the block on the same line as the method declaration, others say on the line below...(the second group of people would be correct :P) but that again is taste.

Cheers.

Link to comment
Share on other sites

...

while all local variables should be declared at the beginning of their respective methods.

...

This isn't C!

Quote from Effective Java: "If a variable is declared before it is used, it is just clutter - one more thing to distract the reader who is trying to figure out what the program does. By the time the variable is used, the reader might not remember the variable's type or initial value. If the program evolves and the variable is no longer used, it is easy to forget to remove the declaration if it's far removed from the point of first use."

It is definitely annoying while reading someone elses code to be at the bottom of a method, see a variable you don't remember, then have to jump back up to the top to see what it is. It's also annoying when writingn code, if you decide you need a new variable near the end of the method, why go back up to the top to declare it then go back down to use it?

I guess that's just my opinion though.

Link to comment
Share on other sites

It is definitely annoying while reading someone elses code to be at the bottom of a method, see a variable you don't remember, then have to jump back up to the top to see what it is.

As opposed to reading through X lines of code to find where it is declared? I would have thought going straight to the top would be easier considering you would have a fair idea where it is.

It's also annoying when writingn code, if you decide you need a new variable near the end of the method, why go back up to the top to declare it then go back down to use it?

My main reason for doing this is I believe that it improves clarity. Not only in having easier to read code, but when someone reads the first part of the method, they can see exactly what is stored locally (this seems to make sense as most people don't read code backwards). Also, it improves consistency in the structure of the method while I don't think it hurts the æsthetics at all (this is obviously of lesser concern).

When it comes down to it, people are going to code in a particular style because they either see value in it or "that was what I read/was taught". In team environments, the value on consistency really comes out, especially when you have to go and maintain older code written by other developers.

Anyway, as I said in my previous post, they were just some guidelines that K1u may want to think about, not the meaning of life.

Cheers.

Link to comment
Share on other sites

The way i see it is you should always declare things at the start of a method. I can tell you know that if you hand any code in at a uni situation and you have declared things all through your code you will lose alot of marks for it. Just because the langauge allows you to doesnt mean you should. It makes it not only harder for you to maintain your code later on but it also makes it harder for other people to read your code and see what it is doing. Not to mention debuging a piece of code that has things declared all over the show would also be a pain in the ass.

Link to comment
Share on other sites

Where you declare variables depends on the language and standards, standards that come with the language and standards agreed upon within a certain project/group. This applies to indentation and braces too. What I'm saying is that there is no right way of doing things. If you cannot learn to adapt and instead insist on doing it "the right way" (as defined by you) you will become the most hated person around and don't be surprised if everyone goes out to lunch without telling you.

But where you put the declarations really shouldn't be an issue. If you are writing so long and complex functions that you get lost in them you are probably doing something wrong to begin with and should rethink the problem.

Link to comment
Share on other sites

As promised, here's my take on it:

// The use of this import means you require java 1.5 or later.

import java.util.Scanner;

//

// Before that, you'd do it like so:

// import java.io.BufferedReader;

// import java.io.InputStreamReader;

// import java.io.IOException;

// ...

// BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));

// try {

//              String readLine = reader.readLine();

// } catch (IOException ioe) {

//              System.out.println("Trouble: "+ioe);

// }

//



/**

 * Original abstract class used to demonstrate the manupulation of strings.

 * This class is made abstract to ensure nobody will create an object instance

 * of this particular class. Any attempt to do so will result in a compiler

 * error.

 *

 * @author      Kiumarz Hashemi

 * @version     1.0

 * @see         java.lang.String

 */

public abstract class StringManipsORIG {



        /**

         * Basic test method that shows how to work a String in Java.

         *

         * @param phrase        The phrase to conduct the rests with.

         */

        private static void stringTest(String phrase) {

                // Some basic validation.

                if (phrase.length() &lt; 3) {

                        System.out.println("Supplied phrase too short.");

                        return;

                }



                // Center point in the string.

                int middleindex = phrase.length() / 2;

                // first half of the phrase string

                String firsthalf = phrase.substring(0,middleindex);

                // second half of the phrase string

                String secondhalf = phrase.substring(middleindex);

                // concatenate the firsthalf at the end of the secondhalf

                String switchedphrase = (secondhalf + firsthalf).replace(' ','*');

                // Isolate the center 3 characters.

                String middle3 = phrase.substring(middleindex-1,middleindex+2);



                // print information about the phrase

                String result = "noriginal phrase: " + phrase +

                                "nlength of the phrase: " + phrase.length() + " characters" +

                                "nindex of the middle: " + middleindex +

                                "ncharacter at the middle index: " + phrase.charAt(middleindex) +

                                "nswitched phrase: " + switchedphrase +

                                "nnMiddle3:" +middle3;

                System.out.println(result);

        }



        /**

         * Properly format and display the hometown based on the supplied city and state.

         *

         * @param city  The city of the hometown.

         * @param state The state in which the city resides.

         */

        private static void displayHometown(String city, String state) {

                String upperState = state.toUpperCase();

                String hometown = upperState + city.toLowerCase() + upperState;

                System.out.println("Hometown: " + hometown);

        }



        /**

         * Entry point of the class.

         * Starts the string test, then requests the user's city and state,

         * and uses it to compile his properly formatted hometown.

         *

         * @param args  The arguments supplied when the class was started.

         */

        public static void main (String[] args) {  

                // Nobody *EVER* uses new String("blah");

                stringTest("this is a string test.");

  

                Scanner input = new Scanner(System.in);

                System.out.print("Enter your city: ");

                String city = input.nextLine();

                System.out.print("Enter your state: ");

                String state = input.nextLine();

                displayHometown(city,state);

        }

}

A more advanced way (and a better way I might add) is to let main do nothing but create an instance of this particular class and call a non-static method of it. From that point on, let the object deal with it.

For the most part you should try to keep your main method as small as possible. You don't want any logic *AT ALL* in there.

But that's for a later course day I'm sure. :)

Link to comment
Share on other sites

Where you declare variables depends on the language and standards, standards that come with the language and standards agreed upon within a certain project/group. This applies to indentation and braces too. What I'm saying is that there is no right way of doing things. If you cannot learn to adapt and instead insist on doing it "the right way" (as defined by you) you will become the most hated person around and don't be surprised if everyone goes out to lunch without telling you.

But where you put the declarations really shouldn't be an issue. If you are writing so long and complex functions that you get lost in them you are probably doing something wrong to begin with and should rethink the problem.

Thats the biggest load of bullshit i have ever read. It doesnt depend on anything, every langauges standard says to declare things at the start. Try and work on a project that has a few million lines of code and then chuck a few decleration in the middle and see how fast you start to get lost and how much harder it is to debug.

Link to comment
Share on other sites

Thank very much all you haven given me much help thankyou

And cooper thanks for making youre take on the code.

Thanks again i will try to post more advanced programs too :)

I personally dislike the leetspeek.

Lol i dont liek it that much either i was just messing with the code so i decided to turn the println statements into leetspeak lol

Link to comment
Share on other sites

But where you put the declarations really shouldn't be an issue. If you are writing so long and complex functions that you get lost in them you are probably doing something wrong to begin with and should rethink the problem.

dood actually where you put youre declarations does matter lol...matters alot actually

Link to comment
Share on other sites

Hate to break it to you guys, but jool is right on this one.

In Java, you're supposed to chop up your problem area into smaller parts. If the size of your method is so large that you can't keep track of the variables, you're doing too much in a single method. That goes for C aswell.

Java has 2 types of variables:

- Instance variables that exist as properties of the object (instantiated class).

- Method variables, that exist within the current method only.

There's no such thing as a 'global variable' in Java. So if you chuck in a few declarations in the middle, that 'middle' would have to be either your method, in which case the scope of the variable (the lines of code in the method that the variable can be accessed within, demarkated by accolades) is limited to at best the entire method, or a static block (more advanced Java here) which is basically a method anyways and has the same rules w.r.t. the scope of a variable.

So, the 'few declarations in between' can always be viewed upon as a declaration somewhere in a method. Your method should, barring mitigating factors like having a lot of if... else if... else if... or a very large switch statement, not exceed 50 lines. If you can't keep track of your variables that are only around for 50 lines you shouldn't be doing any programming.

In C, I feel it's a neatness thing to start the function in question with the declarations. Plus GCC warns about declarations mid-function because I believe standard C doesn't allow this. Doesn't change the fact that you should, if possible, avoid using globals, and keep your functions short. That makes keeping track of your variables a breeze, and shouldn't complicate matters when you add a few declarations in between.

Link to comment
Share on other sites

are we talking about something like

public static void main (String[] args) { 

varDecleration

...somecode

...moreCode

VarDecleration

...moreCode

..morecode

....

}

Because if we are, it doesnt matter if the functions are small or not, you should never do that no matter what but if you mean something like

public static void main (String[] args) { 

varDecleration

...someCode

...moreCode

for loop

varDeveration

...moreCode

...moreCode

...

}

Then yeh sure its fine, because you know that the var is only going to be used inside the for loop.

Link to comment
Share on other sites

So by your logic, my rendition of the stringTest method in the code above is incredibly wrong because I should start the method with declarations of all the String objects I will eventually use?

Link to comment
Share on other sites

Hate to break it to you guys, but jool is right on this one.

In Java, you're supposed to chop up your problem area into smaller parts. If the size of your method is so large that you can't keep track of the variables, you're doing too much in a single method. That goes for C aswell.

Java has 2 types of variables:

- Instance variables that exist as properties of the object (instantiated class).

- Method variables, that exist within the current method only.

There's no such thing as a 'global variable' in Java. So if you chuck in a few declarations in the middle, that 'middle' would have to be either your method, in which case the scope of the variable (the lines of code in the method that the variable can be accessed within, demarkated by accolades) is limited to at best the entire method, or a static block (more advanced Java here) which is basically a method anyways and has the same rules w.r.t. the scope of a variable.

So, the 'few declarations in between' can always be viewed upon as a declaration somewhere in a method. Your method should, barring mitigating factors like having a lot of if... else if... else if... or a very large switch statement, not exceed 50 lines. If you can't keep track of your variables that are only around for 50 lines you shouldn't be doing any programming.

In C, I feel it's a neatness thing to start the function in question with the declarations. Plus GCC warns about declarations mid-function because I believe standard C doesn't allow this. Doesn't change the fact that you should, if possible, avoid using globals, and keep your functions short. That makes keeping track of your variables a breeze, and shouldn't complicate matters when you add a few declarations in between.

lol ok i didnt know...The java book im reading and the teach always emphasis the position of declarations lol but im gonna go with what u say bcuz ur probbly more 1337 than my teacher lol.

Link to comment
Share on other sites

Trust me to be right, but do what the teacher says regardless. It tends to work better with your grades.

Yeah i probbly have liek a 98-100 in that class lol i pwn all those noobs in that class lol.

Link to comment
Share on other sites

Just wait until you reach the part where they deal with bit-shifting. :twisted:

I've actually had to use those things in practice once (in 7 years, which tells you how important they really are) which was rather fun. Most people try to forget that particular chapter as quickly as humanly possible. It's however a comparatively large chunk on the Java 1.4 certification exam, probably because most Java people find it difficult since they never had to deal with bits and bytes directly anyways.

Link to comment
Share on other sites

So by your logic, my rendition of the stringTest method in the code above is incredibly wrong because I should start the method with declarations of all the String objects I will eventually use?

Actually yeah it is. You should but hey your talking about one line of code here, not 100 ;) you see the difference? And yes in real world projects functions will get that big no matter what.

Link to comment
Share on other sites

And yes in real world projects functions will get that big no matter what.

See, that's where I disagree with you. A good programmer will not allow it to reach that point. When he sees a method he's working on grow(n) beyond control, he splits it up into smaller parts.

And make no mistake about it, I've worked on some really large projects that took a large development team more than a year to completely deliver. During that year requirements change, features needed to be added... the normal stuff that makes you loathe customers. We never had this ballooning method problem you claim will crop up in time. Maybe I've been very fortunate to have worked with the people that I have, though looking at some of them I kinda doubt it. ;)

Link to comment
Share on other sites

Cooper we are just going to have to agree to disagree on this one. I cant see any reasion for having to decalre things half way through your code. Look at it this way, im looking through your code for the first time a get half way through it and i see a something declared i continue on my way to see the same thing used a few times except now i have forgotten what type it is so i scroll back upto the top to take a quick look only to see it isnt there, so now i have to relook through some code to find where it was declared. All this could of been saved by just chucking the decleration at the top with all the others. Just because a langauge allways it doesnt mean you should do it. It is bad programming to chuck declerations where ever you want. It makes the code look ugly. And if your code is that nice that you allways have small functions that why not keep it looking nice by declaring things up the top. You say that your code isnt that big so it shouldnt be to hard to move the cursor up the top and declare it there.

Link to comment
Share on other sites

I was sure it would have been my comment about the braces that would have started a discussion, not the bloody variable declarations :P . I don't think Coopers code is "wrong" at all (it's syntactically and semantically correct), it's just written in a different style that has different benefits.

This sort of thing always seems to be an issue though. Usually because most people are a bit apprehensive (myself included) to move away from what they have learnt and developed over a significant period of time, to something else just on face value. Even more so if they have been getting good, consistent results already.

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...