• Post Reply Bookmark Topic Watch Topic
  • New Topic

ArrayList issues.  RSS feed

 
Danny Treart
Ranch Hand
Posts: 37
Chrome Java Netbeans IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I can't seem to initialize this ArrayList properly.



I was hoping to be able to build the ArrayList "list" with a size to match the user's input, but after I've done this and check the list.size() I keep getting 0. So, I just wanted to store the integers from 0-input in my ArrayList and output each of the elements in the list once I've done so. That wouldn't work for me either. I tried using the list.get() method instead of the foreach loop, and still wouldn't work. This just keeps printing "Done."

It looks like I'm doing this correctly, as far as initializing it, etc. I'm confused. Thoughts or input by chance?
 
Matthew Brown
Bartender
Posts: 4568
9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You need to add elements to an ArrayList using the add() method. set() is used to update an element that has already been added.
 
Joanne Neal
Rancher
Posts: 3742
16
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You also need to change your for loop condition. At the moment it will only enter the loop if you enter 1. That is why you weren't getting the IndexOutOfBoundsException that you would have got if you had entered the loop.
 
Danny Treart
Ranch Hand
Posts: 37
Chrome Java Netbeans IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Awesome, think I figured it out. Appreciate the help.

Unfortunately, I'm kind of stumped in another area here using a generic class... Right now I'm supposed to return the standard deviation of two different types (integers and doubles). Passing the list of integers to the stdev method, it won't let me set "deviation" to what is in the list because it is of the wrong type ("T"). Do I have to "unbox" it, convert it to integer, etc. I need to do some math with the the values stored in the array list...

 
Paul Clapham
Sheriff
Posts: 22828
43
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Well, no, if you have an ArrayList<T> then the elements of that list are of type T. You can't assume they are ints because they might be something else. So your code to get values out of the list would be something like this:



I have to say that if you're working with ints then <T extends Number> wasn't the type I would have chosen. There isn't much you can do with a Number object, really. Why don't you have an ArrayList<Integer>?
 
Danny Treart
Ranch Hand
Posts: 37
Chrome Java Netbeans IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yeah, it seems like it would make more sense that way.

Here are the instructions from my professor:
Write a generic class MyMathClass with at type parameter T where T is a numeric object
(Integer, Double or any class that extends java.lang.number) Add a method
standardDeviation (stdev) that takes an ArrayList of type T and returns a standard deviation
as type double. Use a for each loop where appropriate.
Hard code a couple of test arrays into your Demo file. You must use at least 2 different types
such as Double and Integer.
Your call will be something like:
System.out.println(“Standard Deviation 0-9 “ + MyMathClass.stdev(a));
Your class and method headers will be:

Research java’s Number class to see what useful method we are gaining access to.
 
Danny Treart
Ranch Hand
Posts: 37
Chrome Java Netbeans IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I was kind of assuming I needed to use the .intValue() method from the Number class, and assign them to a new array and calculate the standard deviation that way in the stdev method...

 
Matthew Brown
Bartender
Posts: 4568
9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you look at the Number class, it's got a doubleValue() method. So you know your T objects will always have that because they extend Number.

It also has an intValue() method, but since you're calculating the standard deviation you're going to want a double value at some point so might as well use that.
 
Danny Treart
Ranch Hand
Posts: 37
Chrome Java Netbeans IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Think I've figured it out. However, I have one last question and this one is probably the simplest. I can't figure out the best method of prompting the user again after an InputMismathException.



If there is an InputMismatchException thrown, wouldn't it skip directly out of the try block at "input = sc.nextInt();" and bounce into the catch block, setting the inputValid to false and restarting the loop? What is the best method to accomplish this?
 
Tony Docherty
Bartender
Posts: 3271
82
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The problem you have with your code is the while statement isn't testing whether or not validInput is false it is assigning the value false to it. This is one of the reasons (apart from legibility) why you shouldn't test if a boolean value == true or == false. It is true or false so if you are testing for true you can just use or if testing for false you can use
 
Danny Treart
Ranch Hand
Posts: 37
Chrome Java Netbeans IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hmm...For some reason, I'm still having the same issue...

 
Paul Clapham
Sheriff
Posts: 22828
43
Eclipse IDE Firefox Browser MySQL Database
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you want that code to be repeated, then why not just use a while-loop instead of an if statement?
 
Danny Treart
Ranch Hand
Posts: 37
Chrome Java Netbeans IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Lmao. Apparently I just need to give up. The same thing is happening no matter how I try it. Hmm..
 
Paul Clapham
Sheriff
Posts: 22828
43
Eclipse IDE Firefox Browser MySQL Database
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You had a perfectly good do-while loop, except you had some problems with syntax unrelated to it, which Tony pointed out. So you fixed the syntax and also changed the do-while loop to an if-statement. What was up with that?
 
Danny Treart
Ranch Hand
Posts: 37
Chrome Java Netbeans IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


Won't break out of the loop =/

The way I see it (which is obviously wrong), the do-while loop starts, tries getting the input, if input is wrong type it throws it to the catch block immediately, outputs the message and sets inputValidYet to false. While inputValidYet is NOT true, we loop again. But if the input is the correct type, shouldn't inputValidYet be set to true in the try block, which should skip the catch block, and end the loop. I'm such an idiot. Sometimes it is the simplest thing that I can't visualize or grasp.
 
Paul Clapham
Sheriff
Posts: 22828
43
Eclipse IDE Firefox Browser MySQL Database
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Actually your reasoning is pretty much correct. (Except that part about you being an idiot -- it's quite common for all of us to overlook the obvious.) So if the loop is never ending, that means that inputValidYet is never set to true. Which means that the input is never the correct type. That probably seems counter-intuitive to you and maybe you haven't considered the possibility. So why don't you put in some debugging code to see whether inputValidYet is ever set to true?
 
Danny Treart
Ranch Hand
Posts: 37
Chrome Java Netbeans IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


Enter the amount of integers to find standard deviation:
10...
Sorry, invalid input. Try again.
End of catch block, inputValidYet = false and the input = 0
Last line in do-while loop, inputValidYet = false and the input = 0
Enter the amount of integers to find standard deviation:
Sorry, invalid input. Try again.
End of catch block, inputValidYet = false and the input = 0
Last line in do-while loop, inputValidYet = false and the input = 0
Enter the amount of integers to find standard deviation:
Sorry, invalid input. Try again.
End of catch block, inputValidYet = false and the input = 0
Last line in do-while loop, inputValidYet = false and the input = 0
Enter the amount of integers to find standard deviation:
ETC....

This is pretty embarrassing, but it is something I need to figure out. As you can see, I tried resetting "input" to 0 in each block, and added some printlns that show the state of inputValidYet. I don't understand why it is immediately throwing an exception every time it comes to "input = sc.nextInt();"

(Thank you for the patience and help by the way!!)
 
Paul Clapham
Sheriff
Posts: 22828
43
Eclipse IDE Firefox Browser MySQL Database
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Kind of embarrassing for me as well... I was a professional Java programmer for years, but I don't know how to use a Scanner properly. Thing is, professional Java programmers don't write command-line code like that. Or if they do, it's just quick-and-dirty code for people who don't mind if it throws an exception if they type the wrong thing. Command-line applications have been pretty much obsolete these last 20 years, except in schools where students still get taught this kind of thing. (To be fair to the teachers, alternative methods of input are much harder for students to learn.)

Anyway since you're only asking for one number, I would suggest just typing a number and hitting the enter key. Nothing more than that. I recall from other posts around here that sc.nextInt() only reads the number and you have to deal with the enter key separately, or something ugly like that, but right now this issue is causing you to focus on an annoying side issue rather than letting you get on with computing standard deviations.

Hopefully somebody who understands Scanner better than I do can chip in here.
 
Junilu Lacar
Sheriff
Posts: 11481
180
Android Debian Eclipse IDE IntelliJ IDE Java Linux Mac Spring Ubuntu
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
From the JavaDocs for Scanner:
When a scanner throws an InputMismatchException, the scanner will not pass the token that caused the exception, so that it may be retrieved or skipped via some other method.

So you should probably do something like sc.next() in your catch block. Or sc.nextLine(). One or the other should work.
 
Danny Treart
Ranch Hand
Posts: 37
Chrome Java Netbeans IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Paul Clapham wrote:Kind of embarrassing for me as well... I was a professional Java programmer for years, but I don't know how to use a Scanner properly. Thing is, professional Java programmers don't write command-line code like that. Or if they do, it's just quick-and-dirty code for people who don't mind if it throws an exception if they type the wrong thing. Command-line applications have been pretty much obsolete these last 20 years, except in schools where students still get taught this kind of thing. (To be fair to the teachers, alternative methods of input are much harder for students to learn.)


Thanks for pointing this out actually, I was kind of curious in a weird way about how often scanners were used in the professional realm (or really, command-line apps in general). So people in the industry tend to use the I/O streams, buffered readers, etc? (I need to study up on that stuff), right?

Junilu Lacar wrote:From the JavaDocs for Scanner:
When a scanner throws an InputMismatchException, the scanner will not pass the token that caused the exception, so that it may be retrieved or skipped via some other method. So you should probably do something like sc.next() in your catch block. Or sc.nextLine(). One or the other should work.


Thank you for your help, can you please explain your reasoning in more detail? Paul mentioned something about dealing with the enter key separately, and the sc.next()/sc.nextLine() kind of came to my mind vaguely. Anymore information on this?
 
Junilu Lacar
Sheriff
Posts: 11481
180
Android Debian Eclipse IDE IntelliJ IDE Java Linux Mac Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Danny Treart wrote:So people in the industry tend to use the I/O streams, buffered readers, etc? (I need to study up on that stuff), right?

The majority of the projects that I've developed are web apps. Anymore, frameworks like Spring take care of most if not all of the application configuration. Other programs that handle backend processing are usually deployed to Linux and run in the background and nohup'ed. They are usually started with a shell script that sets the environment up, usually from values sourced in from properties/configuration files. If we do allow for command line arguments, those are usually processed by the startup shell script. Linux shell scripting is a good skill to learn as it comes in handy. If you work in Windows, then PowerShell, I guess. Most corporate environments I know have *nix servers. I guess this is a long-winded way of saying that I don't really deal with I/O streams, buffered readers and the like if I can help it. I leave that kind of stuff to the developers of frameworks and utility libraries; I just program to the APIs they provide to make my life easier.

can you please explain your reasoning in more detail? Paul mentioned something about dealing with the enter key separately, and the sc.next()/sc.nextLine() kind of came to my mind vaguely. Anymore information on this?

No, I was hoping you would provide that additional information by telling us how it went when you tried adding sc.next or sc.nextLine() in your catch block. Apart from that, I thought the portion of the JavaDocs that I cited before was pretty straightforward: if you get an input exception, you have to use another nextWhatever() method to get past the token that caused the error.
 
Tony Docherty
Bartender
Posts: 3271
82
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Danny Treart wrote:Thank you for your help, can you please explain your reasoning in more detail? Paul mentioned something about dealing with the enter key separately, and the sc.next()/sc.nextLine() kind of came to my mind vaguely. Anymore information on this?

These are two separate issues.

1. The ever looping code issue is because of the following: Your code asks the Scanner for the nextInt() so the code blocks until the user enters a value. If the value is illegal (ie not a valid int) then an InputMismatchExcpetion is thrown and the input line is not consumed (see Junilu's post). Your code then loops back and calls nextInt() again. This time the code doesn't block waiting for an input because there is still the original input waiting to be used, hence it immediately throws another InputMismatchExcpetion and the cycle repeats forever.

If you add a call to nextLine() in the catch block this will consume the input and when you next call nextInt() it will block waiting for input.

2. The comment about not dealing with the enter key is because of the way Scanner works and will only effect code if you make repeated calls to get input from a Scanner where you have a call such as nextInt() followed by a call nextLine() . In this type of scenario if you ask the user to enter a valid number (eg their age) and then ask for a string input (eg their name) the code will not block waiting for their name to be entered as the call to nextInt() does not consume the Enter key character so the call to nextLine() sees the Enter key, consumes it and returns an empty string. The trick here is to follow calls to nextInt() with a call to nextLine() to remove the Enter key character.

Note: this is not relevant to your code the way it is currently written.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!