Re: arrays
sdlt85@gmail.com wrote:
Hi everyone,
I have a question?
How can I store in to an array the values that the user enter, so
later I can compare the two sets of array that the user enter.
This is what I have but is not working:
System.out.print("This program is going to find the union " +
" or intersection of any two sets you enter" +
"\nPlease enter the first set: ");
for(int i=0; ;i++)
{
int userSetArray1[] = Integer.parceInt(userSetArray1[i]);
}
1. Do not use tabs in Usenet posts. It screws up formatting.
2. What is not working? Does you computer start smoking when it runs
this program? Does your Ethernet connection drop? Does this accidentally
trigger the launch of ICBMs? Or is it a mundane problem, like your code
doesn't compilable? If so, what is the error message given?
3. This is not a compilable example. I in fact see the following errors
without even copy/pasting into my IDE:
a. There is no method `Integer.parceInt'; I presume that you mean
`Integer.parseInt'.
b. There is no presence of a top-level class nor executable main method.
c. You are using a variable in its initialization procedure.
d. `Integer.parseInt' returns an `int'. `userSetArray1' is an
`int[]': these types are not convertible.
4. Conceptual errors:
a. System.out.print does not necessarily flush the output. Either
call flush() or use println() instead.
b. You are running an infinite loop which is probably not desirable.
c. No input is being handled.
5. A possible method that returns a set of integers representing user input:
public static int[] getUserSet(String prompt) {
System.out.println(prompt);
System.out.println("(Use any non-numeric text to stop");
LinkedList<Integer> numbers = new LinkedList<Integer>();
Scanner input = new Scanner(System.in);
while (input.hasNextInt()) {
numbers.add(input.nextInt());
}
input.next(); // Clear delimiting text.
return numbers.toArray(new int[0]);
}
Note that imports have not been included, that the code assumes Java 5+,
and that this makes several assumptions about input methods. For
documentation as to what is happening, the following documents are helpful:
<http://java.sun.com/javase/6/docs/api/index.html> (Java 6)
<http://java.sun.com/j2se/1.5.0/docs/api/index.html> (Java 5)
My signature is also helpful here.
--
Beware of bugs in the above code; I have only proved it correct, not
tried it. -- Donald E. Knuth