geekhack

geekhack Community => Off Topic => Topic started by: SavvyBird on Sat, 13 December 2014, 22:01:59

Title: Java programming help.
Post by: SavvyBird on Sat, 13 December 2014, 22:01:59
Hello, I know I'm asking for help on my homework which I shouldn't be doing, but I'm desperate and I've been working on this program for about 3 days now. I am 80% of the way done, and I just need help on creating a bell curve with a set of values. If anybody has any input on this, your help would be greatly appreciated.

I need to display/draw/make a Gaussian curve/bell curve in acsii asterisk's *. from a set of values
5 5 5 5 6 6 7 7 7 11 26 27 29 29 30 32 35 38 40 41 44 44 44 47 48 49 50 50 54 56 56 58 60 61 62 62 63 64 65 67 68 71 72 73 74 74 74 77 78 78 80 82 84 84 86 89 90
there are 57 values
the mean of the values is 50
In my code, the values are stored into an integer array.
I found an example of what I am trying to do.

http://www.java-samples.com/showtutorial.php?tutorialid=380 

here is my code I know it's sloppy! I'm a BEGINNER :p :-[ java programmer.
http://hastebin.com/tovuwadigu.java
Title: Re: Java programming help.
Post by: SuperBobKing on Sat, 13 December 2014, 22:15:14
Can you be more specific as to what you are having trouble with? I don't want to look over everything in detail. I did notice you weren't using try/catch/finally for the file operations. It is a good practice to do it so that if something goes wrong the stream will still be closed. I won't tell you exactly what to do but I am willing to help.
Title: Re: Java programming help.
Post by: SavvyBird on Sat, 13 December 2014, 22:23:59
Can you be more specific as to what you are having trouble with? I don't want to look over everything in detail. I did notice you weren't using try/catch/finally for the file operations. It is a good practice to do it so that if something goes wrong the stream will still be closed. I won't tell you exactly what to do but I am willing to help.
I'm having trouble trying to figure out how to use my values to display out a bell curve.
How do I properly use the values and mean to make a bell curve. I'm Honestly stumped I don't know how to start.

sorry I thought "throws IOException" was the same as try and catch. Our professor never properly told us how to open files and catch errors he just told us to google it  :-\
Title: Re: Java programming help.
Post by: user 18 on Sat, 13 December 2014, 22:29:16
The exception that the class throws is what you would need to catch. If for example you try to open a file and the file cannot be opened, instead of crashing the program, it would throw an exception. A try/catch or try/catch/finally would be used to catch that exception and deal with it gracefully. If the exception is not dealt with gracefully, the program will crash anyway, regardless of the exception being thrown or not.

There's definitely more to it than that, but I feel as though that's a decent enough overview to point you in the right direction regarding error handling.

Good luck!
Title: Re: Java programming help.
Post by: SavvyBird on Sat, 13 December 2014, 22:49:14
The exception that the class throws is what you would need to catch. If for example you try to open a file and the file cannot be opened, instead of crashing the program, it would throw an exception. A try/catch or try/catch/finally would be used to catch that exception and deal with it gracefully. If the exception is not dealt with gracefully, the program will crash anyway, regardless of the exception being thrown or not.

There's definitely more to it than that, but I feel as though that's a decent enough overview to point you in the right direction regarding error handling.

Good luck!
Thank you! I'll read more about it later

okay im trying dissect and use this example code while trying to use my values

however it wont compile

// Demonstrate random Gaussian values.
import java.util.Random;
class RandDemo2 {
public static void main(String args[]) {
Random r = new Random();
double val;
double sum = 0;
int bell[] = new int[10];
for(int i=0; i<100; i++) {
val = r.nextGaussian();
sum += val;
double t = -2;
for(int x=0; x<10; x++, t += 0.5)
if(val < t) {
bell[ x ]++;
break;
}
}
System.out.println("Average of values: " +
(sum/100));
// display bell curve, sideways
for(int i=0; i<10; i++) {
for(int x=bell; x>0; x-)
System.out.print("*");
System.out.println();
}
}
}

RandDemo2.java:23: error: illegal start of expression
for(int x=bell; x>0; x-)
                                   ^
RandDemo2.java:23: error: not a statement
for(int x=bell; x>0; x-)
                                  ^


I dont understand x- is doing
Title: Re: Java programming help.
Post by: SuperBobKing on Sat, 13 December 2014, 22:51:59
http://docs.oracle.com/javase/tutorial/index.html
That link is one of the best places to go for java tutorials. The one on exception handling is under "Essential Classes" "Exceptions".

As far as showing a bell curve from those numbers, just graphing each one clearly wouldn't make a bell curve. The thing that makes the next most sense would be to graph the frequency of each number, but that doesn't look like it would work either. If you were to graph avg-abs(avg-theNumber) I think that would make one.

Were you not given more details about what to do? It doesn't seem like there is much reasoning behind giving you a set of numbers and telling you to make a specific trend fit them. It seems like the assignment is trying to get you to figure out the problem and not how to solve it.

Also, I don't think you need to include java.lang. It should be done automatically unless I am getting it confused with something else.

EDIT: You posted the last one while I was typing this and I didn't read it thoroughly. x- should be x--.
Title: Re: Java programming help.
Post by: trizkut on Sat, 13 December 2014, 22:52:17
The exception that the class throws is what you would need to catch. If for example you try to open a file and the file cannot be opened, instead of crashing the program, it would throw an exception. A try/catch or try/catch/finally would be used to catch that exception and deal with it gracefully. If the exception is not dealt with gracefully, the program will crash anyway, regardless of the exception being thrown or not.

There's definitely more to it than that, but I feel as though that's a decent enough overview to point you in the right direction regarding error handling.

Good luck!
Thank you! I'll read more about it later

okay im trying dissect and use this example code while trying to use my values

however it wont compile

// Demonstrate random Gaussian values.
import java.util.Random;
class RandDemo2 {
public static void main(String args[]) {
Random r = new Random();
double val;
double sum = 0;
int bell[] = new int[10];
for(int i=0; i<100; i++) {
val = r.nextGaussian();
sum += val;
double t = -2;
for(int x=0; x<10; x++, t += 0.5)
if(val < t) {
bell[ x ]++;
break;
}
}
System.out.println("Average of values: " +
(sum/100));
// display bell curve, sideways
for(int i=0; i<10; i++) {
for(int x=bell; x>0; x-)
RandDemo2.java:23: error: illegal start of expression
for(int x=bell; x>0; x-)
                                   ^
RandDemo2.java:23: error: not a statement
for(int x=bell; x>0; x-)
                                  ^

System.out.print("*");
System.out.println();
}
}
}

I dont understand x- is doing

It should be "x--".  x-- is the equivalent of "x = x-1"
Title: Re: Java programming help.
Post by: SavvyBird on Sat, 13 December 2014, 22:55:44
The exception that the class throws is what you would need to catch. If for example you try to open a file and the file cannot be opened, instead of crashing the program, it would throw an exception. A try/catch or try/catch/finally would be used to catch that exception and deal with it gracefully. If the exception is not dealt with gracefully, the program will crash anyway, regardless of the exception being thrown or not.

There's definitely more to it than that, but I feel as though that's a decent enough overview to point you in the right direction regarding error handling.

Good luck!
Thank you! I'll read more about it later

okay im trying dissect and use this example code while trying to use my values

however it wont compile

// Demonstrate random Gaussian values.
import java.util.Random;
class RandDemo2 {
public static void main(String args[]) {
Random r = new Random();
double val;
double sum = 0;
int bell[] = new int[10];
for(int i=0; i<100; i++) {
val = r.nextGaussian();
sum += val;
double t = -2;
for(int x=0; x<10; x++, t += 0.5)
if(val < t) {
bell[ x ]++;
break;
}
}
System.out.println("Average of values: " +
(sum/100));
// display bell curve, sideways
for(int i=0; i<10; i++) {
for(int x=bell; x>0; x-)
RandDemo2.java:23: error: illegal start of expression
for(int x=bell; x>0; x-)
                                   ^
RandDemo2.java:23: error: not a statement
for(int x=bell; x>0; x-)
                                  ^

System.out.print("*");
System.out.println();
}
}
}

I dont understand x- is doing

It should be "x--".  x-- is the equivalent of "x = x-1"

Thank you!

it outputs now

Im trying to modify this code  now

Title: Re: Java programming help.
Post by: SuperBobKing on Sat, 13 December 2014, 23:07:44
Most of that code is for making the numbers to display. If you just take the part for displaying the asterisks and replace bell with your array of numbers, all that will do is graph each number which as I already said clearly won't make a bell curve since the numbers keep going up and a bell curve goes up then down. There really isn't any point in trying to modify that since the only line you wouldn't have to change significantly (not counting curly braces) is System.out.println('*');.
Title: Re: Java programming help.
Post by: SavvyBird on Sat, 13 December 2014, 23:30:09
Most of that code is for making the numbers to display. If you just take the part for displaying the asterisks and replace bell with your array of numbers, all that will do is graph each number which as I already said clearly won't make a bell curve since the numbers keep going up and a bell curve goes up then down. There really isn't any point in trying to modify that since the only line you wouldn't have to change significantly (not counting curly braces) is System.out.println('*');.

yeah thats the issue
but this is the code that controls when ti goes up then down right?
for(int x=0; x<10; x++, t += 0.5)
if(val < t) {
bell[ x ]++;
break;
}
Title: Re: Java programming help.
Post by: swill on Sat, 13 December 2014, 23:32:12
Can you be more specific as to what you are having trouble with? I don't want to look over everything in detail. I did notice you weren't using try/catch/finally for the file operations. It is a good practice to do it so that if something goes wrong the stream will still be closed. I won't tell you exactly what to do but I am willing to help.
I'm having trouble trying to figure out how to use my values to display out a bell curve.
How do I properly use the values and mean to make a bell curve. I'm Honestly stumped I don't know how to start.

sorry I thought "throws IOException" was the same as try and catch. Our professor never properly told us how to open files and catch errors he just told us to google it  :-\

BTW, this is how exceptions work in Java... 

Exceptions can happen as a result of something you have done, or you can explicitly throw them.  If an exception happens in a function and you don't handle the exception in that function, you have to specify in the function declaration that the function 'throws' any error that you are not handling.  In this case I have created a function called 'do_something' which throws an 'IOException'.  Instead of doing something that naturally causes an exception (like maybe trying to write to a file which is read only or something like that), I am just manually throwing an error (so you see how that works).

Then in my main function I have I have a try/catch/finally block to illustrate how you should handle exceptions in your code...

I hope this clears up how exceptions work in Java.  There is a lot packed into this little example, but it should be a pretty good example to learn from.

Code: [Select]
import java.io.*;

public class Test {
    public static void main(String[] args) {
        System.out.println("I am in the main function...");
        try {
            System.out.println("I am in the try...");
            do_something();
        } catch(IOException e) {
            System.out.println("I just caught the IOException...");
            System.out.println("The error was: "+e.getMessage());
        } finally {
            System.out.println("Finally gets run regardless if there is an error or not...");
        }
    }

    public static void do_something() throws IOException {
        throw new IOException("This is an IOException!");
    }
}

Compile this code with:
Code: [Select]
$ javac Test.java

And run it with:
Code: [Select]
$ java Test
I am in the main function...
I am in the try...
I just caught the IOException...
The error was: This is an IOException!
Finally gets run regardless if there is an error or not...
Title: Re: Java programming help.
Post by: SuperBobKing on Sun, 14 December 2014, 00:11:44
Most of that code is for making the numbers to display. If you just take the part for displaying the asterisks and replace bell with your array of numbers, all that will do is graph each number which as I already said clearly won't make a bell curve since the numbers keep going up and a bell curve goes up then down. There really isn't any point in trying to modify that since the only line you wouldn't have to change significantly (not counting curly braces) is System.out.println('*');.

yeah thats the issue
but this is the code that controls when ti goes up then down right?
for(int x=0; x<10; x++, t += 0.5)
if(val < t) {
bell[ x ]++;
break;
}

No. The frequency of the numbers produced by the nextGaussian method is already a bell curve centered at zero. That snippet is just to categorize each number, so that numbers that fall into the same category will be treated as the same number. If that code wasn't there then there wouldn't be enough repeat numbers to make the bell curve clear.

In case you missed it I said a couple posts up how I think you can get a bell curve from your list of numbers.

I added some indentation to the sample and added comments to explain it.
Code: [Select]
import java.util.Random;
class RandDemo
{
public static void main(String args[])
{
Random r = new Random();
double val;
double sum = 0;
int bell[] = new int[10];
//This loop runs a hundred times to generate a hundred numbers
for(int i=0; i<100; i++)
{
val = r.nextGaussian();
sum += val;
/*
* This loop is what categorizes each number that is generated.
* There are 10 categories, one for each slot in the bell array.
* The categories in the array are sorted from smallest numbers to
* largest numbers. The first category is all numbers less than -2,
* which is why t starts at -2. The variable t is the upper limit
* for the category the number is being tested to see if it falls
* in. The size of each category is .5, which is why t goes up by
* .5 with each iteration. X indicates which category the number is
* being tested for. It starts testing at the smallest category,
* which is all numbers less than two. So in the loop's first
* iteration it will check to see if the number is less than two.
* If the number is less than two, it adds one to the amount of
* numbers that fall into the first category, and uses break to
* stop checking the other categories. If the number is not less
* than t, it will add one to x and .5 to t. The second category is
* all numbers >=-2 and less than -1.5. If the number is less than
* negative two the loop would have already stopped, so there is no
* need to check that. If the number is less than -1.5 then it adds
* one to the amount of numbers in the second category and stops the
* loop.
*/
double t = -2;
for(int x=0; x<10; x++, t += 0.5)
if(val < t)
{
bell[x]++;
break;
}
}
System.out.println("Average of values: " + (sum/100));
// display bell curve, sideways
for(int i=0; i<10; i++)
{
for(int x=bell[i]; x>0; x—)
System.out.print("*");
System.out.println();
}
}
}
Title: Re: Java programming help.
Post by: SavvyBird on Sun, 14 December 2014, 03:59:46
Can you be more specific as to what you are having trouble with? I don't want to look over everything in detail. I did notice you weren't using try/catch/finally for the file operations. It is a good practice to do it so that if something goes wrong the stream will still be closed. I won't tell you exactly what to do but I am willing to help.
I'm having trouble trying to figure out how to use my values to display out a bell curve.
How do I properly use the values and mean to make a bell curve. I'm Honestly stumped I don't know how to start.

sorry I thought "throws IOException" was the same as try and catch. Our professor never properly told us how to open files and catch errors he just told us to google it  :-\

BTW, this is how exceptions work in Java... 

Exceptions can happen as a result of something you have done, or you can explicitly throw them.  If an exception happens in a function and you don't handle the exception in that function, you have to specify in the function declaration that the function 'throws' any error that you are not handling.  In this case I have created a function called 'do_something' which throws an 'IOException'.  Instead of doing something that naturally causes an exception (like maybe trying to write to a file which is read only or something like that), I am just manually throwing an error (so you see how that works).

Then in my main function I have I have a try/catch/finally block to illustrate how you should handle exceptions in your code...

I hope this clears up how exceptions work in Java.  There is a lot packed into this little example, but it should be a pretty good example to learn from.

Code: [Select]
import java.io.*;

public class Test {
    public static void main(String[] args) {
        System.out.println("I am in the main function...");
        try {
            System.out.println("I am in the try...");
            do_something();
        } catch(IOException e) {
            System.out.println("I just caught the IOException...");
            System.out.println("The error was: "+e.getMessage());
        } finally {
            System.out.println("Finally gets run regardless if there is an error or not...");
        }
    }

    public static void do_something() throws IOException {
        throw new IOException("This is an IOException!");
    }
}

Compile this code with:
Code: [Select]
$ javac Test.java

And run it with:
Code: [Select]
$ java Test
I am in the main function...
I am in the try...
I just caught the IOException...
The error was: This is an IOException!
Finally gets run regardless if there is an error or not...

Thank you for this information

So, with throws IOException, I'm just throwing the error if there were to be one, and it is ignored plus the user will have no idea what the error was.

While with try/catch/finally

I will try my code and if there is an error, it catches the error. This way I could tell the user if I wanted to what the error is, depending on the situation.

right? haha Im going to still work on it. I dont want to fall behind on this
Title: Re: Java programming help.
Post by: SavvyBird on Sun, 14 December 2014, 04:05:16
Most of that code is for making the numbers to display. If you just take the part for displaying the asterisks and replace bell with your array of numbers, all that will do is graph each number which as I already said clearly won't make a bell curve since the numbers keep going up and a bell curve goes up then down. There really isn't any point in trying to modify that since the only line you wouldn't have to change significantly (not counting curly braces) is System.out.println('*');.

yeah thats the issue
but this is the code that controls when ti goes up then down right?
for(int x=0; x<10; x++, t += 0.5)
if(val < t) {
bell[ x ]++;
break;
}

No. The frequency of the numbers produced by the nextGaussian method is already a bell curve centered at zero. That snippet is just to categorize each number, so that numbers that fall into the same category will be treated as the same number. If that code wasn't there then there wouldn't be enough repeat numbers to make the bell curve clear.

In case you missed it I said a couple posts up how I think you can get a bell curve from your list of numbers.

I added some indentation to the sample and added comments to explain it.
Code: [Select]
import java.util.Random;
class RandDemo
{
public static void main(String args[])
{
Random r = new Random();
double val;
double sum = 0;
int bell[] = new int[10];
//This loop runs a hundred times to generate a hundred numbers
for(int i=0; i<100; i++)
{
val = r.nextGaussian();
sum += val;
/*
* This loop is what categorizes each number that is generated.
* There are 10 categories, one for each slot in the bell array.
* The categories in the array are sorted from smallest numbers to
* largest numbers. The first category is all numbers less than -2,
* which is why t starts at -2. The variable t is the upper limit
* for the category the number is being tested to see if it falls
* in. The size of each category is .5, which is why t goes up by
* .5 with each iteration. X indicates which category the number is
* being tested for. It starts testing at the smallest category,
* which is all numbers less than two. So in the loop's first
* iteration it will check to see if the number is less than two.
* If the number is less than two, it adds one to the amount of
* numbers that fall into the first category, and uses break to
* stop checking the other categories. If the number is not less
* than t, it will add one to x and .5 to t. The second category is
* all numbers >=-2 and less than -1.5. If the number is less than
* negative two the loop would have already stopped, so there is no
* need to check that. If the number is less than -1.5 then it adds
* one to the amount of numbers in the second category and stops the
* loop.
*/
double t = -2;
for(int x=0; x<10; x++, t += 0.5)
if(val < t)
{
bell[x]++;
break;
}
}
System.out.println("Average of values: " + (sum/100));
// display bell curve, sideways
for(int i=0; i<10; i++)
{
for(int x=bell[i]; x>0; x—)
System.out.print("*");
System.out.println();
}
}
}

Thank you so much for you comments.
It really helped me understand this snipit of code. Because of this, I was able to modify this data, and apply my values into the code.
I was able to display a bell curve which represented the one my professor showed in class.


I know its not a perfect bell curve but this is what he wanted.
Now I have to display this bell curve vertically, I believe I need to use a two dimensional array for this.

*********
*
****
****
********
******
*********
*********
******
*
Title: Re: Java programming help.
Post by: iri on Sun, 14 December 2014, 06:39:59
OP, install IntelliJ Idea. It will help you with typos and many other things.
Title: Re: Java programming help.
Post by: swill on Sun, 14 December 2014, 12:54:26
Can you be more specific as to what you are having trouble with? I don't want to look over everything in detail. I did notice you weren't using try/catch/finally for the file operations. It is a good practice to do it so that if something goes wrong the stream will still be closed. I won't tell you exactly what to do but I am willing to help.
I'm having trouble trying to figure out how to use my values to display out a bell curve.
How do I properly use the values and mean to make a bell curve. I'm Honestly stumped I don't know how to start.

sorry I thought "throws IOException" was the same as try and catch. Our professor never properly told us how to open files and catch errors he just told us to google it  :-\

BTW, this is how exceptions work in Java... 

Exceptions can happen as a result of something you have done, or you can explicitly throw them.  If an exception happens in a function and you don't handle the exception in that function, you have to specify in the function declaration that the function 'throws' any error that you are not handling.  In this case I have created a function called 'do_something' which throws an 'IOException'.  Instead of doing something that naturally causes an exception (like maybe trying to write to a file which is read only or something like that), I am just manually throwing an error (so you see how that works).

Then in my main function I have I have a try/catch/finally block to illustrate how you should handle exceptions in your code...

I hope this clears up how exceptions work in Java.  There is a lot packed into this little example, but it should be a pretty good example to learn from.

Code: [Select]
import java.io.*;

public class Test {
    public static void main(String[] args) {
        System.out.println("I am in the main function...");
        try {
            System.out.println("I am in the try...");
            do_something();
        } catch(IOException e) {
            System.out.println("I just caught the IOException...");
            System.out.println("The error was: "+e.getMessage());
        } finally {
            System.out.println("Finally gets run regardless if there is an error or not...");
        }
    }

    public static void do_something() throws IOException {
        throw new IOException("This is an IOException!");
    }
}

Compile this code with:
Code: [Select]
$ javac Test.java

And run it with:
Code: [Select]
$ java Test
I am in the main function...
I am in the try...
I just caught the IOException...
The error was: This is an IOException!
Finally gets run regardless if there is an error or not...

Thank you for this information

So, with throws IOException, I'm just throwing the error if there were to be one, and it is ignored plus the user will have no idea what the error was.

While with try/catch/finally

I will try my code and if there is an error, it catches the error. This way I could tell the user if I wanted to what the error is, depending on the situation.

right? haha Im going to still work on it. I dont want to fall behind on this

Not quite.  With Java, you always have to catch the error somewhere.  If you want to propagate the error up to the caller you have to specify the 'throws' in the function declaration, but then you are putting the obligation on the caller to either handle the error or propagate it to its caller.  Usually, you don't want to propagate an error too far or things get confusing.  In Java, if there is an exception (error) that is not caught it will crash your program with the error (and you will likely get a very poor mark in your class).  You want to handle all errors as early as you can (or makes sense).

Is that clear?
Title: Re: Java programming help.
Post by: swill on Sun, 14 December 2014, 13:13:23
Thank you so much for you comments.
It really helped me understand this snipit of code. Because of this, I was able to modify this data, and apply my values into the code.
I was able to display a bell curve which represented the one my professor showed in class.


I know its not a perfect bell curve but this is what he wanted.
Now I have to display this bell curve vertically, I believe I need to use a two dimensional array for this.

*********
*
****
****
********
******
*********
*********
******
*

So I am not doing your homework for you, I am going to give you a solution in python which you will have to think through and figure out how to apply it to Java.  Yes, you can use a two dimension array for this.  If your prof wants you to use a two dimension array, then do that, the same logic could be applied.  I am using a single array and I am using strings with the data in it to represent the data of your bell curve (oriented the wrong way as you have illustrated) as my input data.

I have this code saved in a flip_data.py file:

Code: [Select]
#!/usr/bin/env python

if __name__ == "__main__":
data = [
"*********",
"*",
"****",
"****",
"********",
"******",
"*********",
"*********",
"******",
"*"
]

# find the longest string
longest = 0
for d in data:
if len(d) > longest:
longest = len(d)

# now 'longest' is set to the longest length

# now we are going to loop through the data and progressively check
# if a bar should be drawn in the horizontal version of the data
# a bar should only be drawn if the length is longer than the
# corresponding row as we move backwards through the lengths.
for l in reversed(range(longest)):
row = ''
for d in data:
row += ' ' # I added this to make the output prettier
if len(d) > l:
row += '*'
else:
row += ' '
print(row)

You can test it by running:

Code: [Select]
$ python flip_data.py
 *           * *   
 *       *   * *   
 *       *   * *   
 *       * * * * * 
 *       * * * * * 
 *   * * * * * * * 
 *   * * * * * * * 
 *   * * * * * * * 
 * * * * * * * * * *

Cheers and have fun...
Title: Re: Java programming help.
Post by: SavvyBird on Mon, 15 December 2014, 02:21:38


Not quite.  With Java, you always have to catch the error somewhere.  If you want to propagate the error up to the caller you have to specify the 'throws' in the function declaration, but then you are putting the obligation on the caller to either handle the error or propagate it to its caller.  Usually, you don't want to propagate an error too far or things get confusing.  In Java, if there is an exception (error) that is not caught it will crash your program with the error (and you will likely get a very poor mark in your class).  You want to handle all errors as early as you can (or makes sense).

Is that clear?

I just read more and watched videos on this I think I understand now.
thank you


Also I was able to turn my bell curve using a two dimensional array.