Forums Register Login

adding value to an array

+Pie Number of slices to send: Send
Hey all,

so i am having trouble figuring out how to add a value (that i have just prompted the user for) to an array..

___
import java.io.*;
import java.util.ArrayList;

public class prac7Rainfall1
{
public static void main(String args[]) throws IOException
{

int[] rainArray; // declare an array of integers
rainArray = new int[12];// create an array of integers
String myString;

//Reading from the keyboard
BufferedReader myInput = new BufferedReader(new InputStreamReader( System.in));

// assign a value to each array element and print
for (int i = 0; i < rainArray.length; i++) {
rainArray[i] = i;

System.out.print("Enter amount for Month 1: ");
myString = myInput.readLine (); //need to insert some code here that will allow me to add value to array


System.out.println(rainArray[i] + " ");



}

System.out.println();
}
}




thanks
+Pie Number of slices to send: Send
I don't know what you mean by "add a value" -- int addition, assignment, etc...
But it seems to me you have an int array and a String, so you need to
convert that String into an int. I wonder if java.lang.Integer has any
methods that might help (hint, hint)...
+Pie Number of slices to send: Send
Hey,

sorry,

i want to prompt the user for a value and then add that to an array and then print out all the values at the end that are in the array..

ignore the string bit because im not sure that is the best way of doing it..


thanks
gavin
+Pie Number of slices to send: Send
You still haven't defined "add that to an array":
1. Append a new value into an array, incrementing its size by one?
2. Take that number and add that to the value already held at a certain offset?
3. Store that number at a certain offset, overwriting what was there before?
+Pie Number of slices to send: Send
If you mean: making the array longer by one element and assigning the entered value to the new element, it's not going to work with a regular array.

Arrays in Java have a fixed length. If you need a variable length list of numbers, you should use the collection classes, such as ArrayList (which is already imported in your program, but you're not using it yet!).
+Pie Number of slices to send: Send
Use Integer.parseInt(myString) to convert the string to an integer which then you can assign to your array. Here however it is important that the data input by the user is an integer, otherwise your method will throw a NumberFormatException
straws are for suckers. tiny ads are for attractive people.
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com


reply
reply
This thread has been viewed 6876 times.
Similar Threads
Why mutable elements of Sets?
delete from an array
Need hlp wit array. plz help
determine the input type of the value of the function parameter map
Array question
More...

All times above are in ranch (not your local) time.
The current ranch time is
Mar 28, 2024 14:56:07.