Re: Try, catch? array help
Hi alkamenes,
Just quickly popped on and noticed that noone had replyed yet, I don't have long, but hopefully I can give you a quick answer.
Looking at you code, I'm not entirely sure I understand your question. You are using a for loop and using the value of the variable "value" to access to index of an array. This means you already have the index which the random number is at (and are printing it out). Do you mean you wish to provide a number and it finds the index which the number is at?
e.g.
Output:
value[ 0 ] = 28
value[ 1 ] = 1
value[ 2 ] = 10
value[ 3 ] = 15
user enters "10" and 2 is displayed? If so, you will need to use a collection, such as an ArrayList. A collection is an object and has built in methods attached to it, such as indexOf(Object) (just cast/wrap the int as an Integer). - ArrayList (Java 2 Platform SE 5.0)
ArrayList <Integer> myArray = new ArrayList<Integer>();
Use the .add method to add a new entry, the ArrayList will grow dynamically as you add more enteries.
As for validating the users input, I would read the input into a validation method which receives a String and returns an int. Inside this method you can do conversions and check that it is greater than 4. Using a try/catch statement would handle (albeit not very nicely) the user putting in anything other than an int, but not the size being less than 4, as it does not look like this will cause your code to throw an error. As your code is, you would need to either wrap the whole thing in a try block because other exceptions would be thrown further down because the variable size has not been initialized, or just around the section where you set size to the user's input and set size to a default value in catch. e.g
Code :
int size = 4; //default value
try{
int size = input.nextInt();
}catch (Exception e){}
if (size < 4){
size = 4;
}
(How do you put tabs in a code block??)
Though I say it again, a validation method would be a lot nicer.
Anyway, I hope this quick reply at least will help point you in the right direction, I'll check back once I get home and can actually sit down for more than 2 mins.
P.S. Don't forget to start your class name with a capital!
Code :
public class ArrayChange{
Re: Try, catch? array help
P.P.S, To update a specified index in the array list, use .set(int index, Object element)