2 parts: 1) integer array to string 2) string out to a jTextField

I am completely new to Java and Netbeans, but I'm writing my 1st
application that takes a "hex" character input from a jTextField,
then converts it to an "binary" integer array. I then do a lot of bit
manipulation, and generate a new "binary" integer array.
String myhex = jTextField1.getText();
    int len = myhex.length();
    int[] binarray = new int[len*4];
        for (int i = 0; i < len; i++) {
           if (myhex.charAt(i) == '0'){
              binarray[4*i]=0;
              binarray[4*i+1]=0;
              binarray[4*i+2]=0;
              binarray[4*i+3]=0;
           else if (myhex.charAt(i) ==
           // repeat for '1 to 9' and 'a-f/A-F'
           // generate new integer array(s) using various bits from binarrayI realize it might not be the best way to do the
conversion, but my input can be of arbitrary length,
and it is my first time trying to write Java code.
All of the above I've completed and it works...(thanks Netbeans
for making the gui interface design a real breeze!)
So I end up with:
binarray[0]=0 or 1
binarray[1]=0 or 1
binarray[2]=0 or 1
binarray[n]=0 or 1
Where n can be any number from 0 to 63...
I then manipulate the bits in binarray creating a new integer array
and for the sake of expediency let's call it "newbinarray".
newbinarray[0]=0 or 1
newbinarray[1]=0 or 1
newbinarray[2]=0 or 1
newbinarray[n]=0 or 1
Where n can be any number from 0 to 63...
I first need to know how to convert this "newbinarray" integer array to a string.
In the simplest terms if the first three elements of the array are [0][1][1],
I want the string to be 011.
Then I want to take this newly formed string and output it to a jTextField.
string 011 output in JTextField as 011
I've scoured the net, and I've seen a lot of complex answers involving
formatting, but I'm looking for just a simple answer here so I can finish
this application as quickly as possible.
Thanks,
Thorne Kontos

Here's an example, not using NetBeans:
import javax.swing.*;
public class TextDemo extends JPanel
    public TextDemo()
        int[] newbinarray = {0, 1, 1};
        StringBuffer sb = new StringBuffer();
        for (int value : newbinarray)
            sb.append(value);
        String st = new String(sb);
        this.add(new JTextField(st));
    private static void createAndShowGUI()
        JFrame frame = new JFrame("TextDemo");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(new TextDemo());
        frame.pack();
        frame.setVisible(true);
    public static void main(String[] args)
        javax.swing.SwingUtilities.invokeLater(new Runnable()
            public void run()
                createAndShowGUI();
}

Similar Messages

  • Converting a string to an integer array

    This is kind of a newbie question, but:
    If I have a string which looks like this: "12,54,253,64"
    what is the most effective/elegant/best/etc. way to convert it into an integer array (of course not including the ","s :-)
    Any suggestions are greatly appreciated.

    Thanks, I'll do that. I was looking at StringTokenizer and other things, but it seems they are not implemented in j2me?

  • How to convert 1D array of string to string

    How to convert 1D array of string to string.

    Maximus00, as Pavel indicated, there is a lesser known feature of "Concatenate Strings" that does exactly what your code is doing if the input is an array of strings. In one step! See attached image.
    LabVIEW Champion . Do more with less code and in less time .
    Attachments:
    ConcatenateArray ofStrings.gif ‏7 KB

  • Array of Ring to string value for creating a table

    I want to convert an array of ring to string and generate a table from it.
    But using property node for converting each ring is changing all the value of the table!
    each array represents different register!hence required to change  for different array! 
    i am hereby attaching a  Vi!
    Solved!
    Go to Solution.
    Attachments:
    Untitled 1.vi ‏1944 KB

    How about this simple solution? Array of a ring control to Array of string.
    /Y
    Message Edited by Yamaeda on 04-13-2010 08:36 AM
    LabVIEW 8.2 - 2014
    "Only dead fish swim downstream" - "My life for Kudos!" - "Dumb people repeat old mistakes - smart ones create new ones."
    G# - Free award winning reference based OOP for LV

  • Array to one line string

    hi i have an array
    as this
    0123456
    6789456
    but i want my array to be as 01234566789456...
    anyone can help me on tis

    Hi jeyanthi,
    if you connect your array to the "Concatenate Strings" function, then you get what you want.
    Mike

  • Converting Image to Byte Array and then to String

    Hi All...
    Can anyone please help me. I have got a problem while converting a Byte array of BufferedImage to String.
    This is my code, First i convert a BufferedImage to a byte array using ImageIO.wirte
    public String dirName="C:\\image";
    ByteArrayOutputStream baos=new ByteArrayOutputStream(1000);
    BufferedImage img=ImageIO.read(new File(dirName,"red.jpg"));
    ImageIO.write(img, "jpg", baos);
    baos.flush();
    byte[] resultimage=baos.toByteArray();
    baos.close();
    Then i tried to convert this byte array to a string
    String str=new String(resultimage);
    byte[] b=str.getBytes();
    This much worked fine. But when i reversed this process to re-create the image from that string. i found the image distroted.
    BufferedImage imag=ImageIO.read(new ByteArrayInputStream(b));
    ImageIO.write(imag, "jpg", new File(dirName,"snap.jpg"));
    I got this snap.jpg as distroted.
    Please help me i have to convert the image to a string and again i have to re-create the image from that string.

    To conver the bytearray to string use base64.encoding
    String base64String= Base64.encode(baos.toByteArray());
    To convert back use Base64.decode;
    byte[] bytearray = Base64.decode(base64String);
    BufferedImage imag=ImageIO.read(bytearray);

  • Como obtener un array dbl de un string de 2 bytes

    como obtener un array dbl de un string de 2 bytes
    Adjuntos:
    dbl.png ‏37 KB

    Hola, un string de dos bytes no puede contener un double ya que el dbl es un número de 8 bytes.
    Acaso estás recibiendo alguna medicion de un conversor de 16 bits (un instrumento externo, un PIC o algo así)? Si es así el valor correspondiente en la unidad de medición (V, A, RPM...) debe calcularse con
        bits recibidos / 65536 * máximo de la medición
    Ejemplo: en un voltímetro de 100V / 16 bits, un valor de 8000 (bits) equivale a una medición de 12.207V
    Proud to use LW/CVI from 3.1 on.
    My contributions to the Developer Zone Community
    If I have helped you, why not giving me a kudos?

  • Array error Ljava.lang.string;@3e25a5

    Hi,
    I have the following code, but it doesn't print anything, except the error "Ljava.lang.string;@3e25a5." The code compiles without any errors.
    class Array {
    public static void main (String[] arg) {
         String[] CharArray = {"I am stuck."};
         System.out.println (CharArray);     
    Thanks, in advance.

    That's not an error message. That's the kind of thing that arrays output when their toString method is called. If you pass an object (like an array) to the println method of PrintStream (that's what System.out is) it calls the object's toString method.
    If you want to print a nicely formatted array, use java.util.Arrays.toString. Like this:
    import java.util.Arrays;
    class Array {
      public static void main (String[] arg) {
        String[] charArray = {"I am stuck."};
        System.out.println (Arrays.toString(charArray));
    }By the way, you should follow Java naming conventions. Local variables, non-constant fields, and method names should start with a lower-case letter.

  • Array access notation with strings?

    I may be confused, but I thought you could use array access
    notation with strings. Can someone tell me why this code doesn't
    work (or suggest new code):
    the code is meant to rewrite the block of text in tText at a
    rate of one character per frame... (when the function is called
    once per frame) but it doesn't work.

    DZ-015,
    > I may be confused, but I thought you could use
    > array access notation with strings.
    It's made for objects, actually. The array access operator,
    [], allows
    you to access elements from an Array instance and also lets
    you access
    properties from any sort of object. The "trick" it provides,
    in this latter
    case, is that you can refer to these properties -- within the
    brackets --
    with strings, so it's often used to reference objects
    dynamically.
    > var sWorkingText:String = tText.text;
    Here you've declared a String variable and set it to the
    TextField.text
    property of some textfield. So far, so good.
    > var sNewText:String = oPhotoText[sPageFocus];
    Here, you've declared a String variable, but it seems that
    you're
    setting it to a property of the oPhotoText object. That's now
    how this
    works.
    The array access operator allows you to *use* strings to get
    at an
    object's properties:
    // functionally equivalent
    someObject.property1
    someObject["property" + 1];
    var x:Number = 1;
    someObject["property" + x];
    Does that help?
    David Stiller
    Adobe Community Expert
    Dev blog,
    http://www.quip.net/blog/
    "Luck is the residue of good design."

  • Saving an integer array into a .txt file

    hii, im only a beginner in java, so this is the only code i've learned so far for saving array elements into a file
         public static void saveNames(String [] name) throws IOException
                   FileWriter file = new FileWriter("Example\\names.txt");
                   BufferedWriter out = new BufferedWriter(file);
                   int i = 0;
                   while (i < name.length)
                             if (name[i] != null)
                                  out.write(name);
                                  out.newLine();
                                  i++;
                   out.flush();
                   out.close();
    However, this is only used for string arrays; and i can't call the same method for an integer array (because it's not compatible with null)
    I don't really understand this code either... since my teacher actually just gave us the code to use, and didn't really explain how it works
    I have the same problem for my reading a file code as well --> it's only compatible with string
         public static String [] readNames (String [] name) throws IOException
              int x = 0;
              int counter = 0;
              String temp = "asdf";
              name = new String [100];
              FileReader file = new FileReader("Example\\names.txt");
              BufferedReader in = new BufferedReader(file);
              int i = 0;
              while (i < array.length && temp != null)                    // while the end of file is not reached
                   temp = in.readLine();
                   if (temp != null)
                        name[i] = temp;                    // saves temp into the array
                   else
                        name[i] = "";
                   i++;
              in.close();                                   // close the file
              return name;
    Could someone suggest a way to save elements from an integer array to a file, and read integer elements of that file?
    Or if it's possible, replace null with a similar variable (function?), that is suitable for the integer array (i can't use temp != 0 because some of my elements might be 0)
    Thanks so much!!!!!

    because it's not compatible with nullI think it should be okay to just remove the null condition check since there are no null elements in a primitive array when writing.
    Use Integer.parseInt() [http://java.sun.com/javase/6/docs/api/java/lang/Integer.html] to convert the String into an Integer when you read it back and use Integer.toString() to be able to write it as a String.

  • Read part of an array element

    Hello All.
    As indicated in the title, I am trying to read part of an array element.
    What I'm doing is reading values from a LeCroy scope using a "write" than "read" I have returned the read values into an array but the issue is the scope returns a value "1, 52.33E-3"
    I simply want the element to be 52.33 that way I can use that for other calculations.
    For example my array is.
    "1, 34.334E-3"
    "1, 53.343E-3"
    "1, 143.232E-"
    And I want it to be
    34.334
    53.343
    143.232
    Thanks!
    Solved!
    Go to Solution.

    Another option is to use Spreadsheet String to Array and use the comma as the delimiter.  It can actually change your string into an array of numbers.  Then you just index out the number you want.
    There are only two ways to tell somebody thanks: Kudos and Marked Solutions
    Unofficial Forum Rules and Guidelines

  • Only a part of an array is choosed

    Hi Guys!
    I've got  an array only a part of this array is choosed  but i want to choose all the array:
    The code:
    function Move-EmptyDir{
    [CmdletBinding()]
    param (
    [Parameter(Mandatory = $true)][string]$Source,
    [Parameter(Mandatory = $true)][string]$Destination,
    [ValidateNotNullOrEmpty()][regex]$NoMatch
    $EmptyFolders=@()
    $AllFolders= (Dir $Source -Force -Recurse) | Where-Object{$_.Attributes -match "Directory"}
    $ExistFolders= $AllFolders | Group-Object -Property Exists | Where-Object{$_.Name -match "True"} #verify
    $Inexisting= $AllFolders | Group-Object -Property Exists | Where-Object{$_.Name -match "False"}
    if($Inexisting.Count -gt 0){
    ForEach($Not in $Inexisting){
    Write-Warning "The Folder $Not is not existing"
    Foreach($Item in $ExistFolders.Group){
    $MeltinCount= $Item.GetFileSystemInfos().count #0= no element(s)
    $SimCount= (($ExistFolders.Group | Group-Object -Property Parent) | Where-Object{$_.Name -eq $Item.Name}).Count #0=no subfolders
    if($MeltinCount -eq $SimCount){
    $EmptyFolders+= $Item
    else{
    Write-Warning "The Folder $Item is have file(s)"
    $Moved= @()
    $Moving= $EmptyFolders.Length -1
    While($Moving -ne -1){
    $OneFolder= $EmptyFolders[$Moving] #<---------Maybe the problem is near here
    Write-Host $OneFolder.name -BackgroundColor Red
    if($OneFolder.GetFileSystemInfos().count -gt 0){ #Parent have some directory(but 0 files)
    Write-Warning "This Folder $OneFolder is not empty"
    $Moving--
    elseif($OneFolder.Name -match $NoMatch){
    Write-Warning "The Folder $OneFolder Match the Exceptions"
    $Moving--
    else{
    if($OneFolder.parent.Name -match $NoMatch){
    Write-Host "The Parent Folder of $OneFolder Match the Exceptions" -BackgroundColor Green
    $Moved += $OneFolder
    $Place = $OneFolder.FullName -replace "^$([regex]::Escape($Source))", $Destination
    if((Test-Path $Place) -eq $false){
    New-Item -Path $Place -ItemType Directory
    Remove-Item -Path $OneFolder.fullname -Force -ErrorAction SilentlyContinue
    Write-Verbose ('Moved folder "{0}" to "{1}"' -f $OneFolder.FullName, $Place)
    $Moving --
    else{
    Remove-Item -Path $OneFolder.FullName -Force -ErrorAction SilentlyContinue
    $Moving --
    $Where= 'C:\temp'
    $ToGo= 'C:\estinto'
    $MatchList= '0','1','8','9','Scansion'
    $Kind= 'Empty'
    if(Test-Path $Where){
    #$TheMatch = Select-Match -FullList $MatchList
    $Folders = Move-EmptyDir -Source $Where -Destination $ToGo -NoMatch 'F' -Verbose
    $Drives = ForEach($Item in $Folders){
    Select-Object -Property @(
    @{ Name = 'Name'; Expression = { $Item.Name } }
    @{ Name = 'Percorso'; Expression = { $Item.Parent.FullName } }
    #$Drives
    #Get-Report $Drives $Kind
    else{
    Write-Error 'Invalid Path' -Category ResourceUnavailable
    My folder structure Temp>F1>F2>F3>E4 & Temp>G1>G2 F1& G1 have files, F2 have only F3,F3 have only E4, E4& G2 empty
    Please create this structure and run the code one time: E4 is not choosed
    Thanks

    I do not use ISE much myself, but it seems to me that others have reported problems here that resulted from variables from an earlier run remaining in existence when a script is re-run when ISE was used.
    Of course, that would appear to be only part of your problem, as, ideally, the script should be able to find all empty folders when run only once.
    One thing you could do that might help would be to display all variables before the first run, between the two runs, and after the second run. When you see what values are contained after the first run, this might give a clue as to why or how the script
    seems to manage to get farther on the second try.
    This sounds like it may possibly be a one-off situation. Although "F" precedes "G" alphabetically, the file/folder system is not necessarily maintained in alphabetical order. If the "G" folders are processed before the "F" folders, then it seems likely that
    F4 is the very last folder processed. Perhaps it is being processed correctly, but the results are just not being properly recorded.
    Let us know how you get along with this.
    Al Dunbar -- remember to 'mark or propose as answer' or 'vote as helpful' as appropriate.

  • Suggestion: Macros or a way to unroll loops? Integer array input? Shader Model 3 and 4?

    I think it would be nice if pixel bender supported a way to unroll loops. In it's current state certain shaders are really awkward to write or just get ugly when they're converted for flash player. I know it wouldn't be that hard for the developers to just unroll constant sized loops. Things such as:
    for (int i = 0; i < 10; ++i)
      if (foo) { ... }
    can be unrolled easily. Either that or add in some code generation feature that allows this with a preprocessor system. Or better yet add in support for loops since it only requires shader model 3 or equivelant from GLSL.
    This brings me onto another point. Is there going to be support for Shader Model 4? I'm talking about bitwise operations and integer types. Even if you don't allow native support for byte array adding texture sampling for bytes, shorts, and integers would be nice. Also allowing this to work in flash would be nice with the ability to tell the user they don't have shader model 4 or be able to detect compatability and use a different shader.
    Integer arrays would be nice to allow to as input then to the shader. I noticed the reference manual already mentioned:
    "NOTE: Pixel Bender 1.0 supports only arrays of floats, and the array size is a compile-time constant. Future versions of Pixel Bender will allow arrays to be declared with a size based on kernel parameters, which will enable parameter-dependent look-up table sizes."
    Again support for these features in flash player would be really nice.
    Targetting the lowest GPUs is really limiting the true power of pixel bender. I wrote this for fun: http://assaultwars.com/pictures/raycasting6.png which is just a simple real-time voxel raycaster. However, it could be so much more powerful if pixel bender supported more of the GPUs features. Even simple things like custom functions would be really handy in flash player. I'm thinking of this more oriented toward flash games too where more powerful features are unlocked based on the user's GPU.
    If this is already planned for a future pixel bender release then nevermind. I didn't see a developers blog or any news about future versions.
    Interesting:
    http://forums.adobe.com/thread/36659?tstart=60
    Apparently Kevin said "Look for them in a future version of the language as cards that support  these features become common." in regards to bitwise operators aka Shader Model 4.

    Here's an example, not using NetBeans:
    import javax.swing.*;
    public class TextDemo extends JPanel
        public TextDemo()
            int[] newbinarray = {0, 1, 1};
            StringBuffer sb = new StringBuffer();
            for (int value : newbinarray)
                sb.append(value);
            String st = new String(sb);
            this.add(new JTextField(st));
        private static void createAndShowGUI()
            JFrame frame = new JFrame("TextDemo");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.add(new TextDemo());
            frame.pack();
            frame.setVisible(true);
        public static void main(String[] args)
            javax.swing.SwingUtilities.invokeLater(new Runnable()
                public void run()
                    createAndShowGUI();
    }

  • Odd string algorithm (string is for Runtime for linux/unix browser popup)

    I was given this code snippet from this forum in an attempt to popup a web brower in linux/unix operating systems. It doesn't work.
    I have never seen the part of code in bold (the for loop) below, so I can't really make sense of it (the '?' and ':' are new operators to me). When I print the StringBuffer, I show some memory addresses, so I suspect the bold code to be the problem (perhaps needs to specify array indexes?).
    If anyone can either decipher the bold code for me or offer a solution that would work, I would be very grateful.
    Thanks!
    static boolean showInBrowser(String url)
        String os = System.getProperty("os.name").toLowerCase();
        Runtime rt = Runtime.getRuntime();
        try
                if (os.indexOf( "nix") >=0 || os.indexOf( "nux") >=0)
                  String[] browsers = {"epiphany", "firefox", "mozilla", "konqueror",
                      "netscape","opera","links","lynx"};
                  StringBuffer cmd = new StringBuffer();
    for (int i=0; i<browsers.length; i++)
    cmd.append( (i==0 ? "" : " || " ) + browsers +" \"" + url + "\" ");
                  rt.exec(new String[] { "sh", "-c", cmd.toString() });
                  //System.out.println(cmd.toString());
               else
                 return false;
        catch (IOException e)
            e.printStackTrace();
            return false;
        return true;
    }

    ?: is like an if-else operator: i==0?foo:bar is
    if(i==0) value_of_expression = foo else value_of_expression = bar.
    You probably get memory addresses because in the loop "browsers" should really be browsers
    Plain "browsers" just keeps giving you the memory address of the array (or if you want to get nitpicky the hash code which is not really the address.)

  • Writing an integer array to a file...

    Okay, so I just wanna write a sorted integer array to file... but I'm having a problem or two.
    int[] array = read(new File("C:\\college work\radixsort.txt");
    radixSort(array, array.length);That text file is a list of 30 numbers.
    After the radixSort method is called the values in the text file are sorted into the correct order. Then I want to write the sorted values to a text file radixSorted.txt
    I had too many problems with printArray() so I figured this could be easier.
    I have tried FileInputStream and FileWriter but no luck.
    I don't want the answer, but just something to help point me in the right direction.
    Thank you.

    pri.println(char[] x) looks like the one I am looking for.
    I have modified the code. I've placed only the println part inside the loop now, but it's just the pri.println(char[], array) now. I'm nearrrrly there! (I think).
    try
                   PrintWriter pri = new PrintWriter(new FileWriter("C:/college work/radixsort.txt", true));
                   for (int h = 0; h < array.length; h++)
                        pri.println(char[], array);
              catch (Exception e)
                   e.printStackTrace();
                   System.out.println("No such file exists.");
              finally
                   pri.close();
              }Edited by: JayJay88 on Nov 8, 2008 1:16 PM

Maybe you are looking for

  • Random wireless crashes ( need help urgently)

    Hi, I'm using a WRT54GSv4 router and I have two computer connected to it. One pc is connected by wire and the other computer ( IBM t60p labtop, integrated Intel Pro/wireless 3945abg, running MS Vista OS ) by wireless. the wired one is working flawles

  • Trying to figure out whether I can use an ASA cluster in Transparent mode to facilitate VRF based network ??

    Hi Guys, I had to re-post this here because I did not get any comments earlier.. hopefully I'll get something here.. :) I'm investigating the ways that I can use 2 x ASA (5525x) to accommodate Multi-tenancy situation with overlapping addresses. Unfor

  • Converting XML string to internal table

    Hello everyone, I am trying to convert an XML string to an internal table. The format of the XML string is as follows: <node label="Compressors" NODE_ID="783" checked="1" expandStatus="false">    <node label="Nail guns" NODE_ID="78543" checked="1" ex

  • Missing letters when typing-als​o lack of spaces

    When I type normally, I have dropped or missing letters and missing spaces. I have changed keyboards but it didn't help.   Ths is what it looks like when I type normally. Otherwise, I need t type very sloly and that just doesn't ork frme.

  • Upgrade from Mac OS X 10.6.8 to Snow Leopard

    Ok, it's true - I haven't upgraded my laptop in a LOOONG time. I have Mac OS x 10.6.8 and I was told I needed to upgrade to Snow Leopard 10.6.3. But whenever I try it, my laptop just turns off and restarts, I get the gray screen with the apple but th