Array to int

Hey fellas,
I am trying to work out how to convert an array to an int. I have made several squares (using AWT) in an array. Now if I click on one of the squares it should create a line from the clicked square to the next square. See my code below:
public void paint( Graphics gc )
if ( currentPosition[i][j] == 1 )
gc.setColor(Color.red ) ;
if (addnewline == 1)
gc.drawLine( dot[i][j], 60, 400, 300 );
The problem is with the drawLine. It only accepts ints and I have an array variable in there. Is there any other way I could approach this ?
Edited by: shad on Feb 19, 2008 9:10 AM

but your array has data in those indexes...right?
As long as the j is an integer and your array has data in there that is an int itself. But to me it looks like you only need to hold the current place of the one clicked and the next one to be clicked...I guess I am not quite sure what you are doing, but the array looks like it is not needed.

Similar Messages

  • FINDING MEDIAN FOR AN ARRAY OF INTS WITH EVEN NUMBER OF VALUES

    okie dokie fellas i know this has got to be easy but i hjave been sittin at my comp forever workin on projects that are due and my head isn't all there anymore...could someone please clue me in on how im supposed to write the logic to find the median of an array of integers if the array contains an even number of values...I know I have to average the 2 values on either side but i cant figure it out at all...sorry i know its dumb but thnaks to anyone who helps
    package pgm3deClercqMatt;
    * @author Owner
    * To change the template for this generated type comment go to
    * Window>Preferences>Java>Code Generation>Code and Comments
    import java.sql.*;
    import javax.swing.*;
    import java.awt.*;
    import java.util.*;
    import java.text.*;
    public class ExamStatistics
         public static void main(String[] args)
              DbConnection db = new DbConnection("pgm3");
              boolean moreRecords;
              String query = "SELECT * FROM pgm3Data ORDER BY ExamGrade";
              ResultSet rs = db.processQuery(query);
              int nbrGrades = 0;
              ResultSetMetaData rsmd = null;
              try
                   rsmd = rs.getMetaData();
              catch(SQLException sqlex)
                   JOptionPane.showMessageDialog(null, "SQLException getting ResultSet data or metadata");
                   System.exit(0);
              int s[] = new int[200];
              DecimalFormat decimal = new DecimalFormat("#,##0.00");
              int n = 0, aboveNinety = 0, numberAboveNinety = 0;
              double sum = 0, avgGrade = 0, medianGrade = 0;
              try
                   moreRecords = rs.next();
                   if(!moreRecords)
                        JOptionPane.showMessageDialog(null, "pgm3Data Result Set is Empty.");
                        System.exit(0);
                   while(moreRecords)
                        s[n] = rs.getInt(1);
                        n++;
                        moreRecords = rs.next();
                   }// end of while loop
                   System.out.println("n = " + n);
                   System.out.println("s[0]= " + s[0]);
                   System.out.println("s[n-1]= " + s[n-1]);
                   //FIND AVERAGE OF ARRAY
                   for(int j=0; j<n; ++j)
                        sum += s[j];
                        avgGrade = sum/n;
                   //FIND NUMBER OF GRADES ABOVE OR EQUAL TO 90
                   for(int j=0; j<n; ++j)
                        if(s[j]>=90)
                             numberAboveNinety++;
                   //FIND MEDIAN EXAM GRADE
                   for(int j=0; j<n ; ++j)
                        if(Math.abs(medianGrade - Math.floor(medianGrade))<1.e-10)
                              medianGrade = s[(j+1)/2];
                        else
                             medianGrade =    <HERE IS WHERE THE PROB IS
              }// end of try block
              catch(SQLException sqlex)
                   JOptionPane.showMessageDialog(null, " SQLException getting ResultSet data or metadata");
                   System.exit(0);
              String output = "";
              output = "Number of Exam Grades: " + n;
              output += "\nHighest Exam Grade: " + maxOfArray(s, n) + "\nLowest Exam Grade: " + minOfArray(s, n)
                        + "\nAverage Grade: " + decimal.format(avgGrade) + "\nNumber of exam grades above 90: "
                        + numberAboveNinety + "\nMedian Exam Grade: " + medianGrade;
              JOptionPane.showMessageDialog(null, output);
              System.exit(0);
         }// end of main
         static int maxOfArray(int z[], int n)
              int j, max = z[0];
              for(j=1; j<n; ++j)
                   if(z[j]>max)
                        max = z[j];     
              return max;
         static int minOfArray(int z[], int n)
              int j, min = z[0];
              for(j=1; j<n; ++j)
                   if(z[j]<min)
                        min = z[j];     
              return min;
    }// end of ExamStatistics
    class DbConnection
         //     class DbConnection creates and manages the db connection,
         //     processes queries, and returns result sets for processing
         private Connection connection = null;
         private String url="jdbc:odbc:";
         private Statement statement;
         private String username = "";
         private String password = "";
         private ResultSet rs;
         private int nbrResultSets = 0;
         //     Constructor Argument is the registered name of the database
         DbConnection(String dbName)
              try
              {// load driver to allow connection to database
                   Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
                   connection = DriverManager.getConnection ((url+dbName), username, password );
              catch (ClassNotFoundException cnfex)
                   fatalError("ClassNotFoundException on connection attempt");
                   System.exit(0);
              catch (SQLException sqlex )
                   fatalError("SQLException -- Unable to Connect to db");
                   System.exit(0);
         } // end of constructor
         ResultSet processQuery(String query)
         //     process a single SQL query and return the resulting data set
              rs = null;
              try
                   statement = connection.createStatement();
                   rs = statement.executeQuery(query);
              catch (SQLException sqlex)
                   fatalError("SQLException on query or processing");
              return rs;
         void endConnection()
              try
                   connection.close();
              catch (SQLException e)
                   fatalError("SQLException on attempt to close connection");
         //     simple local fatal error handler
         private void fatalError(String msg)
              JOptionPane.showMessageDialog(null,msg);
              System.exit(0);
    } // end of class DbConnection

    sorry to anyone who thinks what i'm doing is a joke
    first of all i'm a student and secondly i'm taking
    java in a summer session so things don't get
    explained as well as they should. And how is this our problem?
    I'm doing the best
    i can. The for loop was because the array that I
    defined to hold 200 values was being filled by a
    database with a supposed unknown number of values but
    less than 200 so i waslooping through to get each
    value and put it in order and the conditional
    statement was supposed to test to see if the incoming
    median was an integer and was in the final write-up
    put into it's own boolean method returning false if
    there was no median and you needed to take the
    average of the next lowest and highest values. BThere's always a median. The definition I sent you tells you what it is.
    But
    thnak you very much to the people that actually help
    on here and don't try to bash people who have put
    effort into writing their code, however shitty it may
    look to them. You can't control what people say about your stuff. Everyone who criticizes your work isn't making a personal attack. They're telling you something that you should be learning from. Your problem is that you can't separate yourself from your work.
    No one knows absolutely everything and
    people who decide to talk down on others when they
    are using this forum as a last resort need to grow
    up.Grow up? That's what you need to do. If you think for a moment that you'll never be criticized once you leave that ivory tower you're sadly mistaken. You need to figure out how to separate yourself from your code.
    %

  • Is it only one chance i can initialize array with int [] a={3,2,1}

    is it only one chance i can initialize array with int [] a={3,2,1}
    ===============================
    class InitializeArrayTest
         int [] a;     //i need keep a[] global
         public static void main(String args[])throws IOException
                   //a=new int[] { 3, 2, 1};//can not complie<========why here is wrong
                   a=new int[3];//also can not
                   a={3,2,1};     //I want to use {3,2,1} as data for simple test purpose here for other method
    }

    so if static means only one instance allowed
    for what reason there is no compiler error in the
    coding below
         static int [] preSort;
         public B(int i)
    int []preSort=new int; //<======why no syntax
    You are declaring a new local variable called preSort, which has scope to the end of the constructor.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • What's the simplest way to pass an array of ints to a class

    Did I word that right when I called it a "class"? Anyway, doing the obvious doesn't work i.e. from the (String[] args) that occurs in every java program, I thought that using (int[] arg), where arg is an array of ints would work, but it doesn't appear to be as simple as that.

    Here's my code:
    // Construct a shape from user input
    class Shape {
    int sides;
         void Shape(int[] specs) {
              sides = specs[0];
    class CreateShape {
         public static void main(String[] args) {
              if(args.length < 3) {
                   System.out.println("usage: CreateShape [number of sides], [side1], [side2], ...");
                   return;
              int arg[] = new int[args.length];
              int i = 0;
              for(String s : args) {
                   System.out.println("is is: "+i);
                   arg[i] = Integer.parseInt(s);
                   i++;
              if(arg[0] != args.length + 1) {
                   System.out.println("You did not specify the correct number of sides");
                   System.out.println("usage: Shape [number of sides], [side1], [side2], ...");
                   return;
              Shape shape = new Shape(arg);
    }I'm just getting one error now:
    Shape.java:33: cannot find symbol
    symbol : constructor Shape(int[])
    location: class Shape
    Shape shape = new Shape(arg);
    ^
    1 error
    Edited by: psvm on Mar 31, 2008 11:43 AM

  • Is there an example vi for converting an array of boolean to list an array of Int based on a selected T/F state?

    I would like to use arrays to minimize code.
    I am trying to generate an array of int base on an array of boolean randomly selected.

    You can try using 'Boolean to 0,1.vi', found in the Boolean palette: this vi converts a scalar, array or cluster of booleans to a scalar, array or cluster of word (I16 integers).
    To use it, simply wire an array of booleans (indicator) to its left, and an array of integers (control) to its right et voilà.
    Roberto
    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?

  • How to display an Array of ints in an Array of TextFields

    I'm trying to create an array of textfield's, and then create an array of ints and display one of those ints in each textfield. Can anyone please help me?

    Yea after you create the array of textfields and ints, do a for loop with textfield.length limit.
    for(int i = 0; i < textfield.length; i++){
    look in the JTextField API for how to put int into
    a text. I know, but if this is for a class, you have
    figure it out. (You might have to use the Integer object to convert it to a string
    I hope this helps. If you still can't get it, post some code and I'm sure someone will help you through it.
    gl
    kimoS

  • How to convert String array into int.

    void getSoldSms(Vector vecSoldSms)
         String str[]=new String[vecSoldSms.size()];
         String words[]=new String[str.length]; // String array
              for(int i=0;i< vecSoldSms.size();i++)
                   str=(String)vecSoldSms.get(i);
              }               //End for
              for(int i=0;i<str.length;i++)
              words = str[i].split("\\|\\|");
              System.out.println();
              for(int j=0;j<1;j++)     
              int count[str.length]=Integer.parseInt(words[i]);
              System.out.print(count[j]*advance_count);
              } // end inner for loop
              }          //End for
         }          //End function getSoldSms
    how do i convert words which is a string array into int type. i kno string can be converted into int using interger.parseint. but wat abt string arrays??? plz help me out with the above code.

    i did tht its still giving the same errorFor Heaven's sake, what about taking a second to try to understand the code you're copying first? If you really can't fix the error yourself, you have a more serious problem than just convertingStrings to ints.
    And if you want { "1", "2", "3" } to be 123:
    StringBuffer b = new StringBuffer();
    for (int i = 0; i < array.length; i++) {
      b.append(array);
    int result = Integer.parseIn(b.toString());

  • Make Array of int's from a String

    Hi,
    Trying to transform a String into an array of ints. The following works, but seems a little longwinded for what must be quite a common function - specifically line 9 in the code (turning a char into an int). Can anyone suggest an easier way?
    public class IntArray {
        public static void main( String[] args ) {
            if ( args.length == 1 ) {
                String s = args[ 0 ] ;
                int sLength = s.length() ;
                int[] argIntArray = new int[ sLength ] ;
                for ( int j = 0 ; j < s.length() ; j++ ) {
                    // This line ...
                    argIntArray [ j ] = Integer.parseInt( s.charAt( j ) + "" );
                for ( int j = 0 ; j < argIntArray.length ; j++ ) {
                    System.out.println( argIntArray[ j ] );
            } else {
                System.out.print( "Please enter an int" );
    }Thanks,
    Rich

    I'm not sure how common it is, but since you are assuming that the input is a String that represents an int...
    public class IntArray {
         public static void main( String[] args ) {
              if ( args.length == 1 ) {
                   String s = args[ 0 ] ;
                   int sLength = s.length() ;
                   int[] argIntArray = new int[ sLength ] ;
                   for ( int j = 0 ; j < s.length() ; j++ ) {
                        // This line ...
                        argIntArray [ j ] = s.charAt( j ) - '0' ;
                        //I suggest checking for <0 or >9
                   for ( int j = 0 ; j < argIntArray.length ; j++ ) {
                        System.out.println( argIntArray[ j ] );
              } else {
                   System.out.print( "Please enter an int" );

  • Exception creating Array of int

    Hi,
    I was trying to create an Array of int. I wrote the following code:
    int[] a = {1,2};
    Class componentClass = (a.getClass()).getComponentType();
    Array a1 = (Array) Array.newInstance(componentClass,5);
    When running it, I got the following exception:
    java.lang.ClassCastException: [I
         at com.ingeneo.seizer.testsuite.AAA.cache.TestCache.main(TestCache.java:24)
    Exception in thread "main"

    Here it is:
    package com.ingeneo.seizer.testsuite.ABC.cache;
    import java.lang.reflect.Array;
    public class TestCache
    public static void main(String[] args)
    int[] a = {1,2};
    Class componentClass = (a.getClass()).getComponentType();
    Array a1 = (Array) Array.newInstance(componentClass,5);

  • Convert jstring to char array or int array

    Hi all, please help with the following code. I've tested this code with hard coded char array and it works. Now I have to get the char array from parameter "param1" which is passed from Java.
    The following code compiled with error message:
    error C2223: left of '->GetStringUTFChars' must point to struct/union
    JNIEXPORT void JNICALL Java_DongleSet_DongleWrite(JNIEnv *env,jobject obj,jstring param1){
    char HaspBuffer[500]=(char)env->GetStringUTFChars(param1,NULL);
    int Service=MEMOHASP_WRITEBLOCK;
    int SeedCode=300;
    int LptNum=0;
    int Pass1=pass1;
    int Pass2=pass2;
    int p1=0;
    int p2=12;
    int p3=0;
    int p4=(int)HaspBuffer;
    hasp(Service,SeedCode,LptNum,Pass1,Pass2,&p1,&p2,&p3,&p4);
    I've tried this:char HaspBuffer[500]=env->GetStringUTFChars(param1,NULL);
    And this:char HaspBuffer[500]=(*env)->GetStringUTFChars(param1,NULL);
    All give me errors.
    Please help.

    char * HaspBuffer=(*env)->GetStringUTFChars(param1,NULL); When writing pure C, you have to supply the JNIEnv as first arg to every JNIEnv function pointer.char * HaspBuffer=(*env)->GetStringUTFChars(env, param1, NULL);Look here: http://developer.java.sun.com/developer/onlineTraining/Programming/JDCBook/jnistring.html

  • Array static int help

    static int[]      insert(int x, int i, int[] a)
    insert takes an item x, an index i, and an array a, and returns a new array containing all the elements of a with one additional element, namely x, at position i.
    ok im trying to add 2 ints to the array?
    and i dont understand what im doing wrong this is what i tried and it says error bc it needs an int in the return.
    its suppose to do this
    a = new int[3]; a[0] = 5; a[1] = 2; a[2] = 7;
    a.length3
    b = insert(-42, 1, a); // -42 is passed into x and 1 is passed into i
    b.length4
    b[1]-42
    b[2]2
    this is what i have written that is wrong...
    public static int[] insert(int newZ, int newX, int[] a){
    int totals = 1;
    int z = newZ;
    int x = newX;
    for (int i = 0; i < a.length; i++){
    totals = (a[i]+ z + x);
    return totals;
    }

    Hi,
    This forum is exclusively for discussions related to Sun Java Studio Creator. Please post your question at :
    http://forum.java.sun.com/forum.jspa?forumID=54
    Thanks,
    RK.

  • How to Convert array of int into array of byte - please help

    I have a 2-dim array of type int and I want to convert it to an array
    of byte. How can I do that? Also, if my 2-dim int array is one dimention
    can I use typecast as in the example below?
    private byte[] getData()
    byte []buff;
    int []data = new int[5];
    //populate data[]
    buff = (byte[]) data; <---- CAN I DO THIS??????
    return buff;

    hi, I suggest you make an array of byte arrays
    --> Byte[][] and use one row for each number
    you can do 2 things,
    take each cipher of one number and put one by one in each column of the row correspondent to that number. of course it may take too much room if the int[] is too big, but that is the easiest way I think
    the other way is dividing your number into bitsets(class BitSet) with sizes of 8 bits and then you can save each bit into each column of your array. and you still have one number in each row. To put your numbers back use the same class.
    Maybe someone has an easier way, I couldnt think of any.

  • Converting a byte array into int

    Here's my problem, I've read my data from a server into a byte array.
    the array is 12 elements in length representing three int variables.
    int flag;
    int query_a;
    int query_b;
    here's what i receive:
    0 0 0 0 34 0 0 -2 21 0 0 0
    how do i convert these into the int values i need.
    i know the first four are for flag = 0, but how does it convert?
    0000 = 0 for each byte
    00000000 00000000 00000000 00000000 = 0 for each bit?
    or is there a method to convert from a byte to int?

    Look at the ByteBuffer class (part of 1.4.1) - before that, you would have had to manually build your integers using left shift and & operator (not that big of a deal, really).
    Be sure you know the "Endian"-ness of the platform you are reading data from though, otherwise, your ints will not be what you expect!
    - K

  • Convert byte array to table of int

    [http://www.codeproject.com/KB/database/PassingArraysIntoSPs.aspx?display=Print|http://www.codeproject.com/KB/database/PassingArraysIntoSPs.aspx?display=Print] Hello friends.
    I'm pretty new with PL/SQL.
    I have code that run well on MSSQL and I want to convert it to PL/SQL with no luck.
    The code converts byte array to table of int.
    The byte array is actually array of int that was converted to bytes in C# for sending it as parameter.
    The TSQL code is:
    CREATE FUNCTION dbo.GetTableVarchar(@Data image)
    RETURNS @DataTable TABLE (RowID int primary key IDENTITY ,
    Value Varchar(8000))
    AS
    BEGIN
    --First Test the data is of type Varchar.
    IF(dbo.ValidateExpectedType(103, @Data)<>1) RETURN
    --Loop thru the list inserting each
    -- item into the variable table.
    DECLARE @Ptr int, @Length int,
    @VarcharLength smallint, @Value Varchar(8000)
    SELECT @Length = DataLength(@Data), @Ptr = 2
    WHILE(@Ptr<@Length)
    BEGIN
    --The first 2 bytes of each item is the length of the
    --varchar, a negative number designates a null value.
    SET @VarcharLength = SUBSTRING(@Data, @ptr, 2)
    SET @Ptr = @Ptr + 2
    IF(@VarcharLength<0)
    SET @Value = NULL
    ELSE
    BEGIN
    SET @Value = SUBSTRING(@Data, @ptr, @VarcharLength)
    SET @Ptr = @Ptr + @VarcharLength
    END
    INSERT INTO @DataTable (Value) VALUES(@Value)
    END
    RETURN
    END
    It's taken from http://www.codeproject.com/KB/database/PassingArraysIntoSPs.aspx?display=Print.
    The C# code is:
    public byte[] Convert2Bytes(int[] list)
    if (list == null || list.Length == 0)
    return new byte[0];
    byte[] data = new byte[list.Length * 4];
    int k = 0;
    for (int i = 0; i < list.Length; i++)
    byte[] intBytes = BitConverter.GetBytes(list);
    for (int j = intBytes.Length - 1; j >= 0; j--)
    data[k++] = intBytes[j];
    return data;
    I tryied to convert the TSQL code to PL/SQL and thats what I've got:
    FUNCTION GetTableInt(p_Data blob)
    RETURN t_array --t_array is table of int
    AS
    l_Ptr number;
    l_Length number;
    l_ID number;
    l_data t_array;
    BEGIN
         l_Length := dbms_lob.getlength(p_Data);
    l_Ptr := 1;
         WHILE(l_Ptr<=l_Length)
         loop
              l_ID := to_number( DBMS_LOB.SUBSTR (p_Data, 4, l_ptr));
              IF(l_ID<-2147483646)THEN
                   IF(l_ID=-2147483648)THEN
                        l_ID := NULL;
                   ELSE
                        l_Ptr := l_Ptr + 4;
                        l_ID := to_number( DBMS_LOB.SUBSTR(p_Data, 4,l_ptr));
                   END IF;
                   END IF;
    l_data(l_data.count) := l_ID;
              l_Ptr := l_Ptr + 4;
         END loop;
         RETURN l_data;
    END GetTableInt;
    This isn't work.
    This is the error:
    Error report:
    ORA-06502: PL/SQL: numeric or value error: character to number conversion error
    06502. 00000 - "PL/SQL: numeric or value error%s"
    I think the problem is in this line:
    l_ID := to_number( DBMS_LOB.SUBSTR (p_Data, 4, l_ptr));
    but I don't know how to fix that.
    Thanks,
    MTs.

    I'd found the solution.
    I need to write:
    l_ID := utl_raw.cast_to_binary_integer( DBMS_LOB.SUBSTR(p_Data, 4,l_ptr));
    instead of:
    l_ID := to_number( DBMS_LOB.SUBSTR (p_Data, 4, l_ptr));
    The performance isn't good, it's take 2.8 sec to convert 5000 int, but it's works.

  • How do you invoke a method with native int array argument?

    Hi,
    Will someone help me to show me a few codes samples on how to invoke a method which has only one argument, an int [] array.
    For exampe:
    public void Method1(int [] intArray) {...};
    Here is some simple code fragment I used:
    Class<?> aClass = Class.forName("Test2");
    Class[] argTypes = new Class[] {int[].class};
    Method method = aClass.getDeclaredMethod("Method_1", argTypes);
    int [] intArray = new int[] {111, 222, 333};
    Object [] args = new Object[1];
    args[0] = Array.newInstance(int.class, intArray);
    method.invoke(aClass, args);I can compile without any error, but when runs, it died in the "invoke" statement with:
    Exception in thread "main" java.lang.IllegalArgumentException: object is not an instance of declaring class
         at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
         at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
         at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
         at java.lang.reflect.Method.invoke(Unknown Source)
         at Test1.invoke_Method_1(Test1.java:262)
         at Test1.start(Test1.java:33)
         at Test1.main(Test1.java:12)
    Any help is greatly appreciated!
    Jeff

    Sorry, my bad. I was able to invoke static methods and instance methods with all data types except native int, short, double and float, not sure the proper ways to declare them.
    After many frustrating hours, I posted the message for help, but at that time, my mind was so numb that I created a faulted example because I cut and pasted the static method invocation example to test the instance method passing int array argument.
    As your post suggested, "args[0] = intArray;", that works. Thanks!
    You know, I did tried passing the argument like that first, but because I was not declaring the type properly, I ended up messing up the actual passing as well as the instantiation step.
    I will honestly slap my hand three times.
    jml

Maybe you are looking for

  • System variales

    Hi ,      what is system variable to find the number of records in an internal table and what is the diff between sy-tabix and sy-index .

  • How to Restore cube's content after compounding on its IObject

    Dear all, I have 1 BW connected to 2 Source-systems who share the same master-datas. However, discrepancy in the master data started to arise recently between the R3 systems; therefore I decided to activate the compounding option for the concerned ma

  • What are the video effects used in this video

    I was just wondering if anybody could help me. I was intrigued to find out what kind of video effect is used in this video at 0:16 - 0:18 and if theres a name for this type of video and editing used throughout the video such as the continous stream o

  • InDesign CS5.5 - Crashes When Packaging

    Using: InDesign CS5.5, 7.5.2 On:  Mac OSX 10.6.8 When trying to package certain of our jobs, InDesign will momentarily hangup during font or link collection before crashing completely.  Initially, this was only happening on large multiple-page, image

  • RMI - What's the point?

    I'm having a hard time understanding the reasons for using RMI. The client needs the remote server classes locally anyway in the classpath so why bother calling the remote classes? Is it the fact that you don't need all the remote classes locally, on