Stories
Slash Boxes
Comments

News for nerds, stuff that matters

Slashdot Log In

Log In

[ Create a new account ]

SamTheButcher (574069)

SamTheButcher
  (email not shown publicly)

"The aim of an argument or discussion should not be victory, but progress." - Joseph Joubert

"If you want really want to hurt your parents and don't want to be gay, go into the arts" - Kurt Vonnegut

I'm the mysterious American guest in cottage #8. And I'd like more towels, please. -artifex2004

Journal of SamTheButcher (574069)

[programming] Last assignment for the semester.

[ #154686 ]
Wednesday December 06 2006, @01:53AM
Programming

Got it done. Early. :)

Next week is the final. I'm guessing tomorrow we'll do...um...I have no idea.

We didn't get to ArrayLists in class, so I'm assuming they'll not be on the final. After that is two-dimensional arrays. However, I'm going to finish reading out the chapter because there's a chapter supplement titled "Search and Sort Algorithms", covering Linear Search, Binary Search, Big-O Notation, Selection Sort, Exchange (Bubble) Sort, and Quicksort. I'm betting that those will come in handy sometime. ;)

Ok, on to the assignment and code.

Chapter 8 Java Assignment

1. CREATE a class called Experiment
a. Add an import statement to use java.io.*
b. Add the main() method in this class
i. Declare a named constant (final variable) called ARRAY_SIZE set to a value of 10
ii. Declare an integer array using ARRAY_SIZE to set the number of elements
c. Add a static void function popArray() with two parameters: an integer array ary[] and an integer size
i. Add the throws statement for java.io.IOException
ii. Add a for loop with iterations limited by the parameter size
1. Use a try/catch catching a NumberFormatException exception
2. Prompt the user for a whole number data reading
3. Use the BufferedReader's readLine() method to place the entered value into a String variable and into each array element
iii. In the main() method, use an appropriate try/catch to call the popArray() method
d. Add a static void function prnArray() with two parameters: an integer array ary[] and an integer size
i. Use a for loop to display all values in the array
ii. In the main() method, call prnArray()
e. Add a static double method getAvg() with two parameters: an integer array ary[] and an integer size
i. Use a for loop to calculate the average of all values in the array
ii. Return the average
iii. In the main() method, call getAvg() to retrieve the average data reading and display it with printf()
f. Add a static int function getMax() returning the maximum value using a for loop and call it from main() to display the value as in e.iii
g. Add a static int function getMin() returning the minimum value using a for loop and call it from main() to display the value as in e.iii

Experiment.java

/**
*
* Experiment
*
* @author Sam O
* @version 20061206
*/
 
import java.io.*; // needed for input
 
public class Experiment
{
    public static void main(String[] args)
    throws java.io.IOException
    {
        final int ARRAY_SIZE = 10;
        int myArray[] = new int[ARRAY_SIZE];
        double avg = 0.0;
        int maximum = 0;
        int minimum = 0;
 
        try
        {
            popArray(myArray, ARRAY_SIZE);
        }
        catch(NumberFormatException n)
        {
            System.out.print("ERROR: I don't know what I'm doing.\n");
        }
 
        prnArray(myArray, ARRAY_SIZE);
 
        avg = getAvg(myArray, ARRAY_SIZE);
 
        System.out.printf("The average is " + avg + ".%n");
 
        maximum = getMax(myArray, ARRAY_SIZE);
 
        System.out.printf("The largest number is " + maximum + ".%n");
 
        minimum = getMin(myArray, ARRAY_SIZE);
 
        System.out.printf("The smallest number is " + minimum + ".%n");
 
    }
 
    public static void popArray(int ary[], int size) // function to populate array
    throws java.io.IOException
    {
        try
        {
            int i;
            String inputStr;
 
/*
            * Prompt user for input
            */
            System.out.println("For this exercise, you will need to enter " + size + " integers : ");
 
            for (i = 0; i < size; i++)
            {
                System.out.print("Please enter an integer : ");
 
//needed for conversion capabilities
                InputStreamReader isr = new InputStreamReader(System.in);
 
//needed to use readLine()
                BufferedReader br = new BufferedReader(isr);
 
// inputStr = br.readLine();
 
                ary[i] = Integer.parseInt(br.readLine());
 
            }
        }
        catch(NumberFormatException n)
        {
            System.out.print("ERROR: An integer number was not entered.\n");
        }
 
    }
 
    public static void prnArray(int ary[], int size) // function to print array element values
    {
        int i;
 
        for (i = 0; i < size; i++)
        System.out.println("The number in ary[" +i +"] is " + ary[i]); // print the element values
    }
 
    public static double getAvg(int ary[], int size) // function to get the average
    { // of all array element values
        int i;
        double average = 0;
 
        for (i = 0; i < size; i++)
        {
            average = average + ary[i];
        }
 
        average = average / size;
 
        return average;
    }
 
    public static int getMax(int ary[], int size) // function to get the largest number
    { // from all array element values
        int i = 0;
        int maxNum = 0;
 
        maxNum = ary[0];
 
        for (i = 1; i < size; i++)
        {
            if (maxNum < ary[i])
            maxNum = ary[i];
        }
 
        return maxNum;
    }
 
    public static int getMin(int ary[], int size) // function to get the smallest number
    { // of all array element values
        int i = 0;
        int smallNum = 0;
 
        smallNum = ary[0];
 
        for (i = 1; i < size; i++)
        {
            if (smallNum > ary[i])
            smallNum = ary[i];
        }
 
        return smallNum;
    }
 
}

Blast away. :)

For the record, I know I'm not looping back around when incorrect data is input to have the user re-enter. I'm going to try to do that tomorrow before class.

This was a fun one, too. Easy, but fun. :)

This discussion has been archived. No new comments can be posted.
The Fine Print: The following comments are owned by whoever posted them. We are not responsible for them in any way.
 Full
 Abbreviated
 Hidden
More | Login
Loading... please wait.
  • If you want to see programming at its rawest, for embedded computers, check out what I'm working on :-)

    http://www.alioth.net/Projects/Z80/romwriter.asm [alioth.net]

    It's not as scary as it looks :-)
    • Oh, I've been reading here and there. My main comment is: 0_o

      Actually, it's not that bad. :) I'm not there yet, but it doesn't intimidate me like it might have at some point.
  • i know this was probably not covered in class, nor in your text, but this might be something to think about. right now your popArray() method is tightly coupled to how user input is collected, which if you look at the feature of that method, you'd think that it simply adds to your array, but it *also* handles user input.

    in the "real world" i would advise breaking this up... have a separate method (class, whatever makes sense) handle user input, validating it etc. and then have your popArray() only handle ar
    • Come on, I've been hammering him on separating out the I/O functions over the last few assignments. No fair stealing my complaint.

      My big problem when I read the assignment was that I read popArray as POP Array like dealing with a stack and not as in POPULATE Array. So, this goes to my next pet peeve in Java: Unnecessary abbreviations.

      Yeah, it might make for a longer method or variable name that slows down your typing a bit, but use the whole word to avoid confusions (yes, I'm the self-declared expert on
      • I don't know that I would've named it popArray just because I have the word "pop" in my brain related to stack stuff, too. Maybe fillArray would've been a better choice on my teacher's part. :) I don't know how you'd classify this as an unnecessary abbreviation on Java's part, though. It's a programmer-defined method name.

        My note with the current popArray implementation with the catch is that you'll wind up with an underpopulated array if a number isn't entered and you crash out of your input loop.

        How would
        • This goes first off to the separation of the I/O routine from the rest of it.

          What I'd do is have an additional flag and integer value to track two things. (However, because your variables are only in the main function it gets more complicated.) First off, a boolean indicating validArray would be useful. An integer holding the length of the array before the failure would also be useful. Maybe you could return the int from popArray and use that to determine validArray and do your averages and what not ins
          • Looking at the code I'd do this: ...

            From there you could check for those values in your popArray and exit out returning a shortened array.

            The cool thing is, I pretty much understand what you're saying.

            As for the commute we're actually quite close to the airport (5-10 mins) so yeah that'd make it more attractive I guess. :-D

            I was thinking like a weekly thing, in on Sunday night, out on Friday night. I'll need a place to stay. You got an extra room? :)

      • sorry. i haven't been paying attention (too busy building said system above)... and haven't been around in journal land much.
      • When I read 'popArray' I thought it had something to do with Gary Glitter.
    • Yeah, how *dare* you steal TCO's complaint!

      And Helix(1)'s. And FK's. :)

      I'm just glad he finally spec'd it out for us this way. I actually had the prompt in main() until I read the spec closer and he has "2. Prompt the user for a whole number data reading" in the popArray section.

      I know about decoupling and breaking things down to their most basic-est parts, I just don't have the occasion to use them much. I'm trying to stay on-spec without a lot of backtalk. Not that I don't want to create more work for
      • I know about decoupling and breaking things down to their most basic-est parts, I just don't have the occasion to use them much

        Heh... I'd say you have had a chance with every lab. (grin) You turned this one in yet?
  • ArrayLists and the rest of the Collections objects are very important datastructures I use on like an hourly basis. Definitely learn those. As far as sorting, you want to use quicksort 99% of the time, and I've never needed to know it (or O notation) since college. Just use java's "sort()" functionality (though learning how to use 'comparable' and 'comparator' is kinda nice when you want to sort your own objects)
    • As far as sorting, you want to use quicksort 99% of the time, and I've never needed to know it (or O notation) since college.

      Wow, that's interesting to know. I guess I saw RailGunner going on about a bubble sort or something sometime and thought it might have more application ItRW.

      I suppose I want to know them from a conceptual standpoint, kind of like recursion. If I don't use them, I'll at least know why and how they work.

      I'm getting to where I want to know things for the sake of knowing them, not because
      • FK is right about quicksort - O(n log n) - it probably gets used the most often, though I have had cases where Insertion Sort has made the most sense.

        I previously mentioned Bubble Sort because it's extremely easy to implement, and often for small data sets the performance is "Good Enough". It's also small, as I'd suppose that the majority of people using quick sort in C++ are using the STL sort [sgi.com], but for tiny embedded projects linking in the STL may not be feasible.

        Why does it matter?

        If you're trying
        • Thanks for the further explanations. The stuff about O(n log n) is scrambling my brain at the moment, but hopefully that'll get sorted out sooner rather than later. :) That's another reason I want to read the book on these subjects - hopefully it'll help clear some of these topics up for me.
          • Yeah, big 'O' notation seems to be a bit above the class level that you're at. At least they aren't going to throw little 'o', big sigma and little sigma at you at the same time...

            Long story short: O() delivers the LONGEST possible running time for the given algorhythm when looped n times and is generally the only one of any real world value. You evaluate the rate of change of what's inside the O() to determine. ln(n) raises very slowly as n gets bigger. n^2 raises fast as n gets bigger and n^n increase
  • titled "Search and Sort Algorithms", covering Linear Search, Binary Search, Big-O Notation, Selection Sort, Exchange (Bubble) Sort, and Quicksort. I'm betting that those will come in handy sometime. ;)

    Yes, they will. Now that you've gotten further in your class, you may look again at that Sudoku Solver I sent you - that's an implementation of a depth first search.
    • Now that you've gotten further in your class, you may look again at that Sudoku Solver I sent you - that's an implementation of a depth first search.

      Well, once I finish the reading. :)

      Thanks for your help and encouragement. :)
  • I don't agree with the use of the size variable here. I would say always query the length of the array from the array directly and don't store it in a separate variable. Variable values change and array sizes change. I don't see how coupling them makes sense.

    Unfortunately, in the assignment you were told to do this, but I'd steer you away from doing that in the future. :)
    • Thanks for the tip. It's important to know what's right and wrong, and why. :)

      I would rather get the length of the array from the array itself, but hey. Not my course to teach. :)