Forum Stats

  • 3,840,134 Users
  • 2,262,571 Discussions
  • 7,901,154 Comments

Discussions

How to Store JTextField Values in the Array

User_AYF65
User_AYF65 Member Posts: 135 Red Ribbon
edited Aug 30, 2015 9:58AM in New To Java

Hi,

I am trying to write a code to store JTextField values in an array.I know how to convert JtextField in to integer. But after that we have different integer variables. I cant figure out how to store values of these different integer variables into an array using a loop.

public class ArrAvg{

public static void main(String[ ] args) {

  int arr[10] = new int[10];

  inputNumbers(arr);

 

}

void int inputNumbers(int arr[10]) {

  int i;

  JTextField field1 = new JTextField();

  JTextField field2 = new JTextField();

  JTextField field3 = new JTextField();

  String value1 = field1.getText();

  String value2 = field2.getText();

  String value3 = field3.getText();

  val1 = Integer.parseInt(value1);

  val2 = Integer.parseInt(value2);

  val3 = Integer.parseInt(value3);

  for(i=0; i<10; ++i) {

    arr[i] = val1 (this should be replaced by val2 and after that by val3 ?????????? i dont know how to do this)

}

}

Some body please guide me.

Zulfi.

juancarlos3782-JavaNet

Best Answer

  • Unknown
    edited Aug 28, 2015 3:44PM Answer ✓
    I have stored text field in ArrayList so i should traverse the ArrayList. But when i am converting the contents of Arraylist into integer, i am getting type mismatch despite the fact that my ArrayList is of String type.
    
    

    Yes - the ArrayList is for String but you created an Iterator for Object

    Iterator itr=al.iterator();//getting Iterator from arraylist to traverse elements  
    

    That 'al.iterator()' method returns Iterator<E>; for your use case E => String. See the API

    https://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html

    But you assign it to 'Iterator' which is NOT a generic so only Objects are returned.

    So you have to cast the return to String.

    Create your iterator instance as Iterator<String>.

    Is there any way to avoid 'Iterator'?
    

    Why avoid it? Just use the proper iterator.

    The class has a 'size' and a 'get(int index)' method. So you can use a for loop from zero to 'size' but just use the iterator.

Answers

  • Unknown
    edited Aug 26, 2015 1:14PM
    I cant figure out how to store values of these different integer variables into an array using a loop.
    

    You can NOT use a loop to store items if each item has a unique name.

    If you had your JTextFields in an array then you could loop through that array, extract the value and store the value into a new array.

    Just hardcode the array.

  • User_AYF65
    User_AYF65 Member Posts: 135 Red Ribbon
    edited Aug 27, 2015 1:52PM

    Hi,

    Thanks for your response. Sorry I cant understand what you mean by:

    If you had your JTextFields in an array then you could loop through that array, extract the value and store the value into a new array.

    Just hardcode the array.

    However, I have written a following code. Its generating an exception.

    import javax.swing.*;

    import java.awt.*;

    public class ArrAvg{

    public static void main(String[ ] args) {

      int[ ] arr = new int[10];

      inputNumbers(arr);

     

    }

    static void  inputNumbers(int [ ] arr) {

      int i; int sum = 0;

      JTextField[ ] arrJText = new JTextField[10];

      String[ ] strVal = new String[10];

      for (i=0;i<10; ++i)

         arrJText[i] = new JTextField();

     

    for (i=0;i<10; ++i)

         strVal[i] = new String( );

    int option = JOptionPane.showConfirmDialog(null,null, "Enter all your values",

    JOptionPane.OK_CANCEL_OPTION);

    if (option == JOptionPane.OK_OPTION)

    {

         strVal[i] = arrJText[i].getText();

         arr[i] = Integer.parseInt(strVal[i]);

    }

      for( i=0; i<10; ++i){

         sum = sum+ arr[i];

      }

      JOptionPane.showMessageDialog(null, " " + sum);

    }

    }

    I am getting following exception:

    >java ArrAvg

    Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 10

            at ArrAvg.inputNumbers(ArrAvg.java:33)

            at ArrAvg.main(ArrAvg.java:9)

    >

    Somebody please guide me.

    Zulfi.

  • Unknown
    edited Aug 27, 2015 4:28PM
    Thanks for your response. Sorry I cant understand what you mean by:
    
    If you had your JTextFields in an array then you could loop through that array, extract the value and store the value into a new array.
    Just hardcode the array.
    

    1. create an array (e.g. an ArrayList)

    2. add the first textfield to the array

    3. add the second, third, etc to the array

    4. create an array for the integers that match each textfield - the size is the same as the other array

    5. now you can loop through the array of testfields, determine the integer value and store it in the second array without knowing the names of the textfields.

  • User_AYF65
    User_AYF65 Member Posts: 135 Red Ribbon
    edited Aug 28, 2015 2:39PM

    Hi,

    Thanks for your steps. I think i followed them except 5.

    < now you can loop through the array of testfields, determine the integer value and store it in the second array without knowing the names of the textfields.>

    I have stored text field in ArrayList so i should traverse the ArrayList. But when i am converting the contents of Arraylist into integer, i am getting type mismatch despite the fact that my ArrayList is of String type.


    Following is my code

    import java.awt.*;

    import java.util.ArrayList;

    import java.util.*;

    public class ArrAvg extends JFrame{

    public static void main(String[ ] args) {

      int[ ] arr = new int[10];

      inputNumbers(arr);

     

    }

    static void  inputNumbers(int [ ] arr) {

      int i; int sum = 0;

    ArrayList<String> al=new ArrayList<String>();

      JTextField[ ] arrJText = new JTextField[10];

      for (i=0;i<10; ++i)

         arrJText[i] = new JTextField();

      Object[] message = {

        "Input value 1:", arrJText[0],

        "Input value 2:", arrJText[1],

        "Input value 3:", arrJText[2],

        "Input value 4:", arrJText[3],

        "Input value 5:", arrJText[4],

    };

    int option = JOptionPane.showConfirmDialog(null,null, "Enter all your

    values", JOptionPane.OK_CANCEL_OPTION);

    if (option == JOptionPane.OK_OPTION)

    {

         al.add(arrJText[0].getText( ));

    al.add(arrJText[1].getText( ));

    al.add(arrJText[2].getText( ));

    al.add(arrJText[3].getText( ));

    al.add(arrJText[4].getText( ));

    }

    i=0;

    Iterator itr=al.iterator();//getting Iterator from arraylist to traverse elements 

      while(itr.hasNext()){ 

       arr[i] = Integer.parseInt(itr.next());

    i++ ;

      } 

     

      }

     

    }

    Is there any way to avoid 'Iterator'?

    >javac ArrAvg.java

    ArrAvg.java:41: error: incompatible types: Object cannot be converted to String

       arr[i] = Integer.parseInt(itr.next());

                                         ^

    Note: Some messages have been simplified; recompile with -Xdiags:verbose to get

    full output

    1 error

    >javac -Xdiags:verbose ArrAvg.java

    ArrAvg.java:41: error: no suitable method found for parseInt(Object)

       arr[i] = Integer.parseInt(itr.next());

                       ^

        method Integer.parseInt(String,int) is not applicable

          (actual and formal argument lists differ in length)

        method Integer.parseInt(String) is not applicable

          (argument mismatch; Object cannot be converted to String)

    1 error

    >

    Some body please guide me.Also I am not using 'message' but still i am getting messages with text fields, why?

    Zulfi.


  • Unknown
    edited Aug 28, 2015 3:44PM Answer ✓
    I have stored text field in ArrayList so i should traverse the ArrayList. But when i am converting the contents of Arraylist into integer, i am getting type mismatch despite the fact that my ArrayList is of String type.
    
    

    Yes - the ArrayList is for String but you created an Iterator for Object

    Iterator itr=al.iterator();//getting Iterator from arraylist to traverse elements  
    

    That 'al.iterator()' method returns Iterator<E>; for your use case E => String. See the API

    https://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html

    But you assign it to 'Iterator' which is NOT a generic so only Objects are returned.

    So you have to cast the return to String.

    Create your iterator instance as Iterator<String>.

    Is there any way to avoid 'Iterator'?
    

    Why avoid it? Just use the proper iterator.

    The class has a 'size' and a 'get(int index)' method. So you can use a for loop from zero to 'size' but just use the iterator.

  • User_AYF65
    User_AYF65 Member Posts: 135 Red Ribbon
    edited Aug 28, 2015 10:55PM

    Hi,

    Thanks for your response. I have changed the code to this:

    i=0;

    Iterator<String> itr=  al.iterator();//getting Iterator from arraylist to traverse elements 

      while(itr.hasNext()){ 

       arr[i] = Integer.parseInt(itr.next());

    i++ ;

      } 

    It has compiled but I got following exception:

    >java ArrAvg

    Exception in thread "main" java.lang.NumberFormatException: For input string: ""

            at java.lang.NumberFormatException.forInputString(NumberFormatException.

    java:65)

            at java.lang.Integer.parseInt(Integer.java:592)

            at java.lang.Integer.parseInt(Integer.java:615)

            at ArrAvg.inputNumbers(ArrAvg.java:41)

            at ArrAvg.main(ArrAvg.java:10)

    >

    Zulfi.

  • User_AYF65
    User_AYF65 Member Posts: 135 Red Ribbon
    edited Aug 30, 2015 9:58AM

    Hi,

    Its working now. I was not passing message Object array in JOpt*.showConfirmDialog(...).

    The code is:

    import javax.swing.*;

    import java.awt.*;

    import java.util.ArrayList;

    import java.util.*;

    public class ArrAvg extends JFrame{

    public static void main(String[ ] args) {

      int[ ] arr = new int[10];

      inputNumbers(arr);

     

    }

    static void  inputNumbers(int [ ] arr) {

      int i; int sum = 0;

    ArrayList<String> al=new ArrayList<String>();

      JTextField[ ] arrJText = new JTextField[10];

      for (i=0;i<10; ++i)

         arrJText[i] = new JTextField();

      Object[] message = {

        "Input value 1:", arrJText[0],

        "Input value 2:", arrJText[1],

        "Input value 3:", arrJText[2],

        "Input value 4:", arrJText[3],

        "Input value 5:", arrJText[4],

    };

    int option = JOptionPane.showConfirmDialog(null,message, "Enter all your values",

    JOptionPane.OK_CANCEL_OPTION);

    if (option == JOptionPane.OK_OPTION)

    {

         al.add(arrJText[0].getText( ));

    al.add(arrJText[1].getText( ));

    al.add(arrJText[2].getText( ));

    al.add(arrJText[3].getText( ));

    al.add(arrJText[4].getText( ));

    }

    i=0;

    Iterator<String> itr=  al.iterator();//getting Iterator from arraylist to traverse elements 

      while(itr.hasNext()){ 

       arr[i] = Integer.parseInt(itr.next());

       sum=sum + arr[i];

    i++ ;

      } 

      JOptionPane.showMessageDialog(null,"Sum=" + sum);

      }

     

    }

    >javac ArrAvg.java

    >java ArrAvg

    >

    Thanks for your guidance.

    Zulfi.

This discussion has been closed.