0

Im trying to obtain a series of numbers from a for loop using JOptionPane. The for loop works fine i run into trouble with the array. How do i get it print the numbers in a JTextField? My code is the following:

int value = Integer.parseInt(JOptionPane.showInputDialog("Please enter the amount of numbers you want to input"));
        int[] holy = new int[value];
        StringBuilder water = new StringBuilder();

        for(int i = 1; i<=value; i++){
            int num = Integer.parseInt(JOptionPane.showInputDialog("Enter a number"));
            holy[i]= num;
        }
        for(int j = 0; j<holy.length; j++){
            water.append(holy[j]);
            tfholy.setText(water.toString());
        }
  • Okay, good, fine ... what's the question? – MadProgrammer Mar 05 '18 at 04:59
  • 1
    Off by 1 error. Java arrays are 0 based, not one based. `for (int i = 1; i <=value; i++)` will cause an `IndexOutOfBounds` error accessing `holy[i]`. – AJNeufeld Mar 05 '18 at 04:59
  • 1
    You may also want to take a look at [`StringJoiner`](https://docs.oracle.com/javase/8/docs/api/java/util/StringJoiner.html) or even [What's the simplest way to print a Java array?](https://stackoverflow.com/questions/409784/whats-the-simplest-way-to-print-a-java-array) – MadProgrammer Mar 05 '18 at 05:00
  • @Daniela Welcome to StackOverflow. Your question needs a question. There is no good answer to "I want to [do that]" since it's not a question. At best, a good answer is "Okay". People will be more likely helpful in the community if you ask good questions for which good answers exist. The reference to read: https://stackoverflow.com/help/how-to-ask – Frederik.L Mar 05 '18 at 05:03
  • I changed the code to for(int i = 0; i<=value; i++) but it is still giving me the same error and now it does an extra loop @AJNeufeld – Daniela Villamizar Mendoza Mar 05 '18 at 05:10
  • You corrected the error at one end, but left it at the other. You need `i < value`, or you will access one element beyond the length of your array. And don’t edit the question text, to fix the mistakes; that will leave any future reader confused as to what the problem was, or what the question was asking. – AJNeufeld Mar 05 '18 at 05:10
  • That was such a dumb mistake. Thank you for your patience with me. – Daniela Villamizar Mendoza Mar 05 '18 at 05:17
  • Happy to help. “Given enough eyeballs, all bugs are shallow.” – AJNeufeld Mar 05 '18 at 05:19

0 Answers0