Printing an array to JLabel

Let me preface this post by saying that I am a novice programmer. I realize my code my be subpar ..to say the least :)
I wrote a small practice program that when run, prints 5 sets of random numbers (ex. A3KRM-QP4S7-5GMBR-OY68B-Q8GBZ).
That part works fine on the command line, however I wanted to incorporate swing and display the output on a form. This is where I'm running into a problem. I'm trying to place output from a character array into a string and then print that to a label. The result is its printing a bunch of squares (ASCII?).
Here is where I'm creating my sets of random numbers, in the method "myGenerator()".
class keygen
//initialize random number generator
Random rand = new Random();
//initialize arrays          
char data[] = new char[36];
char key[] = new char[5];
//initialize integers and strings          
char keys[] = new char[30];
int a = 0, n = 35, q = 65, z = 48;
//CONSTRUCTOR
keygen()
//main method
public char[] myGenerator()      
//Populate charater array with numbers and letters
for (int x = 0; x <=25; x++)
data[x] = ((char)q);
q++;          
for(int x = 26; x <=35; x++)
data[x] = ((char)z);
z++;
//Print 5 groups of random characters
do
for (int b = 0;  b < 5; b++)
System.out.print(data[rand.nextInt(n+1)]);
f++;
System.out.print("-");
a++;
f++;
}     while (a < 4);
do
System.out.print(data[rand.nextInt(n+1)]);
a++;
f++;
}     while (a < 10);
return keys;
}Here is where I'm trying to add the output to the main form in a label (in the frmMain() constructor).
class frmMain extends JFrame
//add main menu bar to JFrame
private jmbMainMenu mmb;
private JFrame _mainFrame;
private JLabel mylabel = new JLabel();
void init()
setTitle("SandBox");
setJMenuBar(mmb = new jmbMainMenu() );
setSize (500,300);
setVisible(true);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e)
System.exit(0);
frmMain()
//Labels
setLayout(new FlowLayout(FlowLayout.CENTER, 50, 50));
String str1 = new String(new keygen().myGenerator());
mylabel.setText(str1);          
this.add(mylabel);
}My next step is to add a "Generate" button that displays a new random code when clicked, but I need to find out and understand what I'm doing wrong here first. Feel free to rip apart the code, and I'll appreciate any feedback.
Thanks!

I do have a main, I just didn't add it in my first post,
public class keyUtil
     public static void main (String[] args)
     new frmMain().init();
}I forgot to take out the "f" variable. I was using it earlier and forgot to remove it from the code. I can also see how my loop is confusing.
Mel,
Your absolutely right. Originally I tried doing something like this,
do
     for (int b = 0;  b < 5; b++)
          keys[f] = (data[rand.nextInt(n+1)]);
          f++;
          keys[f] = ("-");
          a++;
          f++;
}     while (a < 4);
do
          keys[f] = (data[rand.nextInt(n+1)]);
          a++;
          f++;
}     while (a < 10);
     return keys;Thats where the "f" came from. "f" was originally initialized to 0. I thought this would put a new character into each element of the "keys" array, but it didn't seem to work. I will go back and try this again.
Edited by: jd3cker on Jun 14, 2009 3:40 PM
Edited by: jd3cker on Jun 14, 2009 3:45 PM

Similar Messages

  • Possible to make arrays of JLabels?

    I would like to make arrays of JLabels, Iconimages, and Jpanels, but I can't find how to do it.
    Is it eaven possible?
    How can I proceed instead...?

    Why not????
    Infact you can make an array of any premitive type or of any object... Just you need to use this syntax...
    dataType[] arrVarName = new dataType[size];
    for example,
    JLabel[] lblArr = new JLabel[10];
    This will create the new array of JLabel type of 10 elements size... You can initialize each element like this:
    for(int i = 0; i < lblArr.length; i++){
    lblArr[i] = new JLabel("Hello " + i);
    and you can print each element like this:
    for(int i = 0; i < lblArr.length; i++){
    System.out.println(lblArr.getText());
    Okay... Still if you are having any doubt you are always welcome

  • Array of JLabel HELP

    how would I create an array of JLabels?

    If you are not sure of how many object you want to place within the array, ArrayLists can grow dynamically. Here is how to use it:
    java.util.ArrayList arraylist = new java.util.ArrayList();
    //To Add Your Class:
    YourClass yourClass = new YourClass();
    arraylist.add(yourClass);
    //To Use Your Class:
    YourClass yourClass = (YourClass)arrayList.get(0);

  • How to print an array out a while loop?

    Hi all,
    I'm very new with Labview (6h of Practice) and I meet a problem.
    I create a while loop in which a read the first characters of each line of three files and put it in an 2D array (3 rows and 50 lines).
    My goal is to print this array on the VI's panel in a Table or in a Multicolon Listbox. How to do this? In the While loop or out?
    I use Labview 6i.
    Thanks for your help

    Hi,
    I don't see any problems. I suppose that you can get a 2D array of strings from files.
    Now there are three solutions.
    1. Use of Arrays.
    Right-click on the wire with your 2D array and select "Create->Indicator" from pop-up menu. Now you have a 2D array on the front panel which will show you your data.
    2. Use of Tables.
    Select table control from "Controls->List&Tables". Paste it on the front panel of your vi. Right-click on it and select "Change to indicator" from pop-up menu. Then wire this indicato to your 2D array in the block diagram.
    3. Use of Multicolumn listboxes.
    Paste the multicolumn listbox to the front panel. On the block diagram right-click on it and select "Create->Property node" from pop-up menu. The property node of your control will appea
    r in the diagram. Right-click on it and change property to "Item Names" By selectring "Properties->Item Names" from pop-up menu. Now Right-click on the property node once again and select "Change to write" or "Change all to write" to toggle your property into write mode. Then wire your 2D array to this property node.
    The example is attached.
    Good luck.
    Oleg Chutko.
    Attachments:
    Tables.vi ‏26 KB

  • Using array create JLabel

    i have one problem about using addKeyListener, i'm using array to create JLabel but once i've compile it, it came out a message as i shown, so where is my problem, hope someone can fix it for me and explain it for me, thank you
    ---------- Capture Output ----------
    "C:\Program Files\Java\jdk1.6.0_03\bin\javac.exe" Login.javaLogin.java:78: not a statement
    inputTextName[1]KeyPressed( event );
    ^
    Login.java:78: ';' expected
    inputTextName[1]KeyPressed( event );
    ^
    2 errors
    Terminated with exit code 1.---------- Capture Output ----------
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class Login extends JFrame
         //JLabel[] lblName = {"lblName1","lblName2"};
         JLabel[] labelName;
         //JTextField[] txtfldName = {input1,input2};
         JTextField[] inputTextName;
         //JLabel[] array = new JLabel[veryLargeNumber];
         JButton[] btnName = new JButton[3];
    public void userInterface()
         this.setBackground(Color.blue);
         this.setTitle("Log in");
         this.setSize(285,130);
         this.setVisible(true);
         Container contentPane = getContentPane();
         contentPane.setLayout(null);
         labelName[0] = new JLabel();
         labelName[0].setText("ID: ");
         labelName[0].setBounds(16, 16, 130, 21);
         this.add(labelName[0]);     
         inputTextName[0] = new JTextField();
         inputTextName[0].setText(" ");
         inputTextName[0].setBounds(50, 16, 150, 21);
         inputTextName[0].setHorizontalAlignment(JTextField.LEFT);
         this.add(inputTextName[0]);
         labelName[1] = new JLabel();
         labelName[1].setText("Password: ");
         labelName[1].setBounds(16, 48, 104, 21);
         this.add(labelName[1]);
         inputTextName[1] = new JTextField();
         inputTextName[1].setText(" ");
         inputTextName[1].setBounds(50, 48, 150, 21);
         inputTextName[1].setHorizontalAlignment(JTextField.LEFT);
         this.add(inputTextName[1]);
         btnName[0] = new JButton();
         btnName[0].setText("login");
         btnName[0].setBounds(120,80,65,20);
         this.add(btnName[0]);
         btnName[1] = new JButton();
         btnName[1].setText("exit");
         btnName[1].setBounds(190,80,65,20);
         this.add(btnName[1]);
         inputTextName[1].addKeyListener(
             new KeyAdapter() // anonymous inner class
                // method called when user types in cartonsJTextField
                public void keyPressed( KeyEvent event )
                  inputTextName[1]KeyPressed( event );
             } // end anonymous inner class
          ); // end call to addKeyListener
    //call function
         public Login()
              userInterface();          
         public static void main (String args[])
              Login application = new Login();
               application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
         }Edited by: slamgundam on Oct 24, 2007 11:48 PM

    slamgundam wrote:
    the purpose is try to get the text in the inputTextField
    inputTextName[1].addKeyListener(
        new KeyAdapter()
             // method called when user types in cartonsJTextField
             public void keyPressed( KeyEvent event )
                   String str = inputTextName[1].getText();
                   System.out.println(str);
    );

  • How to print from Array by skipping some indexes

    Hi,
    Upon doing some kind of computations I had an array a1[][][] whose values are as follows:
    a1[0][0][1]=10;
    a1[1][1][2]=20;
    a1[1][1][4]=3;
    a1[1][1][2]=20;Upon doing some computations, i definetly be getting the multiple copies with same index values and the values present in that index.
    Now that my question is, i dont to print multiple copies that had same index and the value(ie; i dont want to print a1[1][1][2]=20 twice)
    How could that be done?
    Thanks in advance

    i had an array a[][] which has the following values
    1 2 3 1 2 4
    2 3 4 5 6 2
    2 3 5 4 2 4i had one more array b[][] which has the following values
    21 22 23
    65 66 98
    65 88 23array a1's index will be the output values that are generated from arraya[][], ie; 1 2 that are present in a[][] will act as an index of a1[][] ie a1[1][2]=21.
    now that array a1[][] will get the following values
    a1[1][2]=21;
    a1[3][1]=22;
    a1[2][4]=23;
    a1[2][3]=65;
    a1[4][5]=66;
    a1[6][2]=98;
    a1[2][3]=65;
    a1[5][4]=88;
    a1[2][4]=23now that i dont want to print the a1[2][4]=65 twice or a1[2][3]=65 twice ... that is i dont want to print the multiple copies .
    I hope this gives clear idea what my question is.
    Thanks again
    Edited by: netbeans2eclipse on Sep 27, 2008 9:24 PM

  • How to print JTextPane containing JTextFields, JLabels and JButtons?

    Hi!
    I want to print a JTextPane that contains components like JTextFields, JLabels and JButtons but I do not know how to do this. I use the print-method that is available for JTextComponent since Java 1.6. My problem is that the text of JTextPane is printed but not the components.
    I wrote this small programm to demonstrate my problem:
    import javax.swing.*;
    import javax.swing.text.*;
    import java.awt.*;
    import java.awt.print.PrinterException;
    public class TextPaneTest2 extends JFrame {
         private void insertStringInTextPane(String text,
                   StyledDocument doc) {
              try {
                   doc.insertString(doc.getLength(), text, new SimpleAttributeSet());
              catch (BadLocationException x) {
                   x.printStackTrace();
         private void insertTextFieldInTextPane(String text,
                   JTextPane tp) {
              JTextField tf = new JTextField(text);
              tp.setCaretPosition(tp.getDocument().getLength());
              tp.insertComponent(tf);
         private void insertButtonInTextPane(String text,
                   JTextPane tp) {
              JButton button = new JButton(text) {
                   public Dimension getMaximumSize() {
                        return this.getPreferredSize();
              tp.setCaretPosition(tp.getDocument().getLength());
              tp.insertComponent(button);
         private void insertLabelInTextPane(String text,
                   JTextPane tp) {
              JLabel label = new JLabel(text) {
                   public Dimension getMaximumSize() {
                        return this.getPreferredSize();
              tp.setCaretPosition(tp.getDocument().getLength());
              tp.insertComponent(label);
         public TextPaneTest2() {
              StyledDocument doc = new DefaultStyledDocument();
              StyledDocument printDoc = new DefaultStyledDocument();
              JTextPane tp = new JTextPane(doc);
              JTextPane printTp = new JTextPane(printDoc);
              this.insertStringInTextPane("Text ", doc);
              this.insertStringInTextPane("Text ", printDoc);
              this.insertTextFieldInTextPane("Field", tp);
              this.insertTextFieldInTextPane("Field", printTp);
              this.insertStringInTextPane(" Text ", doc);
              this.insertStringInTextPane(" Text ", printDoc);
              this.insertButtonInTextPane("Button", tp);
              this.insertButtonInTextPane("Button", printTp);
              this.insertStringInTextPane(" Text ", doc);
              this.insertStringInTextPane(" Text ", printDoc);
              this.insertLabelInTextPane("Label", tp);
              this.insertLabelInTextPane("Label", printTp);
              this.insertStringInTextPane(" Text Text", doc);
              this.insertStringInTextPane(" Text Text", printDoc);
              tp.setEditable(false);
              printTp.setEditable(false);
              this.getContentPane().add(tp);
              this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              this.setSize(400,400);
              this.setVisible(true);
              JOptionPane.showMessageDialog(tp, "Start printing");
              try {
                   tp.print();
              } catch (PrinterException e) {
                   e.printStackTrace();
              try {
                   printTp.print();
              } catch (PrinterException e) {
                   e.printStackTrace();
         public static void main(String[] args) {
              new TextPaneTest2();
    }First the components are shown correctly in JTextPane, but when printing is started they vanish. So I created another textPane just for printing. But this does not work either. The components are not printed. Does anybody know how to solve this?
    Thanks!

    I do not know how I should try printComponent. From the API-Doc of JComponent of printComponent: This is invoked during a printing operation. This is implemented to invoke paintComponent on the component. Override this if you wish to add special painting behavior when printing. The method print() in JTextComponent is completely different, it starts the print-job. I do not understand how to try printComponent. It won't start a print-job.

  • Having trouble printing an array of prime numbers that has been resized

    HI, im having trouble with my printPrimeNumbers() method printing the current state of an array, I can only get it to print the original state it was in. The array is inside of a primeNumbers object. I used checkAndResize to resize that array. my printPrimeNumbers method must be void without a parameter. How could i get my PrintPrimeNumbers method to print out a resized array without modifying the parameter? Any ideas.
    Here is my PrimeNumbers class:
    * Created by IntelliJ IDEA.
    * User: Kevin
    * Date: Mar 4, 2007
    * Time: 1:53:56 AM
    * To change this template use File | Settings | File Templates.
    package primes;
    public class PrimeNumbers {
        private boolean [] sieve;
        public PrimeNumbers(int  upper) {
            initializeSieve(upper);
        public int getNthPrime (int n){
        int prime = 0;
        double num;
        if (n >= sieve.length)
            checkAndResize(n + 1);
        for (int i = 0; i < sieve.length; i++){
            if(sieve)
    prime++;
    if (prime == n)
    return i;
    if (prime < n && i == sieve.length -1)
    checkAndResize(2*sieve.length);
    return -1;
    public int getNumberPrimeNumbers(int n){
    int primes = 0;
    for (int i =0 ; i < sieve.length ; i ++){
    if (n > sieve.length){
    checkAndResize(n);
    if(sieve[i])
    primes++;
    else if (sieve[i])
    primes++;
    return primes;
    public int getSieveSize ()
    return sieve.length;
    public boolean isPrime (int n) {
    if (n > sieve.length){
    checkAndResize(n);
    //initializeSieve(n);
    return sieve[n];
    // prints out the prime numbers inside sieve
    public void printPrimeNumbers() {
    int n = 0;
    boolean first = true;
    System.out.print("[");
    for(int i = 0; i < sieve.length - 1; i++){
    n++;
    if(sieve[i] == true && n != sieve.length - 1) {
    if(first) first = false;
    else System.out.print(" ");
    System.out.print(i);
    System.out.println("]");
    // checks length of sieve with N and then resizes sieve if nessecary.
    private void checkAndResize (int n){
    if ((n + 1) >= sieve.length){
    initializeSieve(2*n);
    private void setMultiples (int k) {
    for (int i = 2*k; i < sieve.length; i += k)
    sieve [i] = false;
    private void initializeSieve (int upper){
    if ( upper < 2)
    sieve = new boolean [2];
    else
    sieve = new boolean [upper + 1];
    sieve[0] = false;
    sieve[1] = false;
    for (int i =2 ; i< sieve.length; i ++ )
    sieve[i] = true;
    int bound = (int) Math.ceil(Math.sqrt(sieve.length));
    for (int i = 2 ; i < bound ; i ++)
    if (sieve[i])
    setMultiples (i);
    private String booleanToString (boolean value)
    if (value)
    return "T";
    else
    return "F";
    public String toString (){
    StringBuffer buf = new StringBuffer("[");
    for (int i = 0; i < sieve.length -1 ; i ++)
    buf.append(booleanToString (sieve[i]) + " " );
    buf.append(booleanToString (sieve[sieve.length -1]) + "]");
    return buf.toString();
    here is the client code
            PrimeNumbers test = new PrimeNumbers(16);
            System.out.println(test);
            System.out.println("There are " + test.getNumberPrimeNumbers(16) +
                    " prime nummbers in the sieve from 1 to 15. \n");
            System.out.println("There are " + test.getNumberPrimeNumbers(26) +
                    "  prime numbers in the resized sieve from 1 to 25.");
            System.out.println("\nThe first 25 prime numbers are:");// makes sense why it doesnt work
            test.printPrimeNumbers();
            System.out.println("\nThe 13th prime number is: " + test.getNthPrime(13));
            System.out.println();
            System.out.println("The number 3001 is prime:  " + test.isPrime(3001));do you see how my methods resized it?
    here is the output:
    [F F T T F T F T F F F T F T F F F]
    There are 6 prime nummbers in the sieve from 1 to 15.
    There are 15 prime numbers in the resized sieve from 1 to 25.
    The first 25 prime numbers are:
    [2 3 5 7 11 13 17 19 23 29 31 37 41 43 47]// this is only the first 15 elements
    The 13th prime number is: 41
    The number 3001 is prime: true
    thanks for taking your time to look at this

    What's the problem?
    You say that there are 15 prime numbers in the range 1-25. Your method printPrimeNumbers() prints the last calculated primes, and that is 15. So the program works.

  • Print out array to JTextArea

    Hello!
    I having trouble to print out the array to a JTextArea.
    This is an asignment so please do not spoonfeed me with code.
    To test that I have added elements correctly in my array I sat it up to print out in console, wich works fine.
    Please give me a hint on what I need to do in order to make it work. Below you see the code that is important for this part of the program.
    Part of my controller:
    //User press "Show Runners" button
              else if(user_action.equals("Show Runners")) {
                   //Call method in model class
                   model.showRunnersBy_startNR();
                   //Display (I will use this once I print out to JTextArea)
                   //view.setDisplayArea(""+model.showRunnersBy_startNR());
              }//End if statementPart of my model
    //showRunnersBY_startNR
         public void showRunnersBy_startNR() {
              for(int i = 0; i <store.getIndex_runner(); i++) {
                   System.out.println(store.global_runner.getRunners());     //Print out in console for now to see that the input and output is working correctly
    //I should have this as "public String showRunnersBy_startNR()" instead with a return statment, correct?
    //I tryed the above but did only manage to print out my latest input in the JTextArea
    Part of my view// Sets the text displayed on the display area
         public void setDisplayArea(String message){
              display.setText(""+message);

    Hello again!
    I see :)
    part of my model
         //showRunnersBY_startNR
         public void showRunnersBy_startNR() {
              for(int i = 0; i <store.getIndex_runner(); i++) {
                   view.setDisplayArea(store.global_runner.getRunners());     
              }part of my view     // Sets the text displayed on the display area
         public void setDisplayArea(String message){
              display.append(""+message+"\n");
         }SetText() seemed to only print out the last one added to the array, so I I used the "append" instead.
    Thanks for the hint.
    Regards
    Martin                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • Print out array

    The code does not print out like it shoud. What am I doing wrong? Thank you for help
    public class test {
        public static void main(String ... args) {
            String text = "array";
            char[] textArray = text.toCharArray();
            System.out.println("     text >" + text);
            System.out.print("textArray >" + textArray);
    }output:
         text >array
    textArray >[C@addbf1

    Once again this is printing out correctly, to get your desired syntax you could loop through the array e.g
    public class test {   
       public static void main(String ... args) {
             String text = "array";
             char[] textArray = text.toCharArray();
             System.out.println("text > " + text);
             System.out.print("textArray > ");
             for(int i = 0;i<textArray.length;i++){
                 System.out.print(textArray);
    }Calypso                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • Can we print an array of dates on the chart X-Axis?

    Hi,
    I have a requirement in which I have to print all the dates in the selected date range on the chart axis even though I donu2019t have the data for all the dates in my DB.I did not find any direct solution in Crystal Report Designer (2008, XI) except we can use "time scale" option in axes tab of chart option but this option also does not provide the required behavior completely.
    After implementing this option I get the date range on chart but from the date I have data in the DB and to the date I have the data in the DB.
    For Example, though I have selected the date range from 2nd April to 8th April, dates in the chart are starting from 5th April since I have the data in the DB of 5th April and 8th April.
    To overcome this limitation of crystal report I thought of creating an array of dates of the selected date range. I can create the array of dates in crystal report but donu2019t know how to use this array in chart to show the summary data.
    I also want to base my Group on this array since I want to show all the dates in group even with count zero.
    Thanks & Regards,
    Amrita

    Hi Sourashree,
    I am using the following formula to create an array of dates.
    numbervar dateDiff:={?eDate}-{?bDate};
    dateTimeVar array dateArray;
    numbervar i;
    for i :=1  to  7 do
        redim preserve dateArray<i>;
    if(i=1) then
        dateArray<i>:={?bDate}
    else
        dateArray<i>:={?bDate}+i;
    This formula is a print time formula since when I specify "WhileReadingRecords" array remains blank (I have confirmed this by returning any single value from the array).
    I can not base my Group and Chart on any Print Time formula since these two get calculates at read time.
    Can you please let me know if there is any other way of creating the array at read time? Or should I create the array in main report and then pass it to sub report?
    Regards,
    Amrita

  • Print specific array index

    How do i print out a specific slot of the array created from the following function? I can print them all by putting the dynamic counter varible in the index parameter but if i put a number instead of the dynamic "counter" variable in the index parmeter then the io exception is thrown. this function gets called every time a node in an XML document is encountered. Just printing the same index multiple time would be acceptable as this is just a learning script.
      private void showData (String s)
        throws SAXException
            try {
                arr0[numCt]=s;
                out.write(arr0[0]);
                //out.write (s);
                out.flush ();
                numCt++;
            } catch (IOException e) {
                throw new SAXException ("I/O error", e);
        }

    SAX parsing has nothing to do with your array problem. It should not be in your example.
    Your example is not small.
    It does not compile.
    It uses deprecated methods, and you know it does.
    You shouldn't even be trying to parse an xml document if you can't iterate over and access data from an array properly. There is a link to the tutorials at the top of the New To Java forums.
    Also, from your previous post you don't even know the syntax of this language. You can't just toss a bunch of code into a text document and hope to get something useful.
    Also, do not berate people trying to help you and do not demand answers. Your lack of understanding is your own fault not ours. You would be wise to reread posts you don't comprehend, or purchase learning materials to fill the gaps in your knowledge.
    Here is a working example with arrays throwing out all the XML garbage that shouldn't even be in your example.
    There are two examples: One example uses your swiss army knife method. And the other "better" example uses discrete methods that perform individual functions denoted by their names.
    If you continue to be an ass to this forums contributors don't expect answers.
    import sun.plugin.dom.exception.InvalidStateException;
    public class BooksLibrary {
        private int numCt = 0;
        private String[] arr0 = new String[100];
        public static void main(String argv[]) {
            System.out.println("Tour way: \n");
            yourWay();
            System.out.println("\n\nReasonable way: \n");
            reasonableWay();
        private static void yourWay() {
            BooksLibrary bl = new BooksLibrary();
            bl.fillArray();
        private void fillArray() {
            for(int i=0; i < arr0.length; i++) {
                showData("" + i);
            System.out.println();
            Is this method showing data? yes
            Should this method also add data to the array? no
            Should this method only show the data in index zero and not the data in the index that was just assigned? no
            What is the purpose of this method?
        private void showData(String s) {
            arr0[numCt] = s;
            System.out.print(arr0[0] + " ");
            numCt++;
        private static void reasonableWay() {
            BooksLibrary bl = new BooksLibrary();
            try {
                bl.showLastAddedData();
            } catch (Exception e) {
                System.out.println("No Data Added");
            try {
                bl.showAllAddedData();
            } catch (Exception e) {
                System.out.println("No Data Added");
            for(int i=0; i<5; i++) {
                bl.addData("" + i);
            try {
                bl.showLastAddedData();
            } catch (Exception e) {
                System.out.println("No Data Added");
            try {
                bl.showAllAddedData();
            } catch (Exception e) {
                System.out.println("No Data Added");
            //try to add too much data
            try {
                for(int i=0; i < 1000; i++) {
                    bl.addData("" + i);
            } catch (Exception e) {
                e.printStackTrace(System.out);
        private void addData(String s) {
            arr0[numCt++] = s;
        private void showLastAddedData() {
            if(numCt <= 0) {
                throw new InvalidStateException("No data has been added to array yet");
            System.out.println(arr0[numCt - 1]);
        private void showAllAddedData() {
            if(numCt <= 0) {
                throw new InvalidStateException("No data has been added to array yet");
            for(int i = 0; i < numCt; i++) {
                System.out.print(arr0[i] + " ");
            System.out.println();
    }

  • Printing an array of objects

    Can someone help me write a method that will print out an array of objects,
    thanks

    What happens with Smile2Me?
    If you want to print your "card" i think you should override his "toString" method in order to print there the data thast you want. If the "Card" class have two string to be printed (for example), you could write this method:
    public String toString() {
    return myString1 + " ; " + myString2;
    and then when you print them you will get this information printed.
    Hope this helps
    Zerjio

  • Print entire array in a label

    How will I print an entire array in a label? I'm creating a CPU scheduling simulator using VB and I need to display all inputs for convenience.
    I tried this:
    Public Class CPUscheduling
    'Declaring Variables
    Dim i = 0
    Dim arrival(i) As Integer
    Dim burst(i) As Integer
    Dim pCount(i) As Integer
    'These are my arrays
    ''' CONDITIONING '''
    Private Sub add_Click(sender As Object, e As EventArgs) Handles add.Click
    'HERE IS WHERE I'M TRYING TO PRINT ARRAY VALUES TO LABEL WITH NO SUCCESS
    arrival(i) = Val(arrivalTextbox.Text)
    arrivalLabel.Text = arrival(i).ToString
    arrivalTextbox.Clear()
    'Outputs text from Arrival textbox to display then clears textbox contents
    burst(i) = Val(burstTextbox.Text)
    burstLabel.Text = arrival(i).ToString
    burstTextbox.Clear()
    'Outputs text from Burst textbox to display then clears textbox content
    End Sub
    End Class
    But what happens is everytime I click "Add" button, it replaces the old values already displayed at the Label section. I want to have that continuous list effect.
    Thank you! :)

    Hi,
    as a first step, enabling unnessary faults is not a good idea. Unfortunatelly, this is the default project setting, i.e. it is not your fault. Open the project properites, and on the "compile" tab, switch the Option Strict setting to "On".
    You will have compile errors now because you don't treat data types appropriately. Choose the right data types for variables. If you need to perform conversions, be aware if the conversion can fail.
    In addition, do not use the VB6 emulation layer with functions like Val(). To convert a String to an Integer value, call Integer.TryParse. As it's name says, it tries to parse the String. This is necesary because not every String can be interpreted as an
    Integer value. TryParse  is a function. The return value is of type Boolean (True or False). It tells you if the conversion was successful. If yes, you can make the code continue execution, otherwise show a message box informing the user about the situation.
    Regarding your question...: You can use the &-operator to concatenate two strings to a new string. So you can do with the text in the label and the one you want to add. However, are you sure that a label is the right place to show several inputs? For
    showing multiple items, a Listbox is normally used.
    Armin

  • Unable to print the array method that returns an array

    public class ReturnAtrray {
         public static void main(String[] args) {
              int[] b= {1, 3, 5};
              System.out.println(incrementArray(b,2));
         public static int[] incrementArray(int [] a, int increment)
              int[] tmp = new int[a.length];
              for(int i = 0; i <a.length; i++ )
                   tmp= tmp[i] + increment;
              return tmp;     

    You are correct: Java is always pass by value. In the case of an array it is a reference to the array that is passed by value. This means that there is a way to increment the array values "in place". As an alternative to what you are doing now consider:
    // untested
    public class ReturnAtrray {
        public static void main(String[] args)
            int[] b= {1, 3, 5};
            incrementArray(b,2);
            for(int i = 0; i < b.length; i++)
                System.out.print(b[i] + " ");
        public static void incrementArray(int [] a, int increment)
            for(int i = 0; i <a.length; i++)
                a[i] = a[i] + increment;
    }

Maybe you are looking for

  • Price Varaince With ref to Purchase Order  for Good Receipt

    I want to set the Tolerance limit for GR using PO Price.I don't want to receive goods more than 500$ of PO Price ..In SPRO -MM- IM - Tolerance key for GR , There are two variance , one for Variance in the purchase order price quantity - Tolerance key

  • Collect IDOC into one single XML

    Hello All, I have done IDOC to FILE(XML) scenario.....its working fine..................now client wants to collect the IDOCs and send them in single XML. Any one done this requirement please help me. With out using BPM can we achive this requirement

  • Oracle  application server 10 g multimedia library

    Hi Friends, Do you have any experience about Oracle Application Server 10g Multimedia Tag Library? Does embedVideo and mediaUrl tag support livelife pict stream from IP video/camera? Welcome any information for this topic. we do not interested in fil

  • Mac Mini server question

    I'm working on replacing the Mac Mini server in a small office configuration where the Mini is acting as a fileserver, a Filemaker Pro server and Time Machine backup server. There are 8 machines in the office using the server. The files being shared

  • Changing capture time

    Hi, I just discovered the time changing functions and tried to get some times corrected but ended being quite confused. After importing a photo it shows 12:00 o'clock (24h system, i.e. noone). I then adjusted the time +1 hour and LR now says 13:00 o'