Puzzel- Method to optimize int[ ][ ]of int[ ][ ]'s

I'm righting a class that takes an int[][], initially filled with 0 or null. A rectangular block is added to the int[][] with a value of 1 - 9. Another rectangular block is added to the int[][] with a different value from the first, usually the next int (2). The current setting is
final static int width = 47;
final static int height = 3800;
public int[][] grid = new int[47][3800];
I have a method addBlock(int blockWidth, int blockHeight) which adds a block to the grid. However it doesn't properly optimize the grid to fit the most efficient number of blocks. It simply adds a block to the top left corner of the grid (where the top left is grid[0][0]) and checks to make sure the next block does not overflow the width bound of 47. If it does it simply places the block at the first available grid where the grid value = 0 and does not overflow the bounds. It doesn't check to make sure that it isn't overriding other blocks, and it doesn't move existing block to make room for new blocks.
What I am looking for is a way to keep individual blocks together. There could come a situation where two blocks with the same value touch. In this case what would happen?
Also how do you move blocks once they have been added to the grid?
Finally, is there an existing algarythm for doing a best fit on a grid of grids?
Suggestions, other places to look, code, websites to check or any valuable information would be greatly appreciated.
If needed I could post the existing source, which stacks the grids from the upper left corner and works down. I have a viewer written already which reads in an int[][] and displays it in 9 colors, however I can easily expand the color recognition to as many colors as needed.

Hi again,
even if the sequential adding of block will not lead to an optimized layout of the templates on the bolt, we can improve the algorithm given by robert19791 - starting from the top left position of the bolt working towards the right bottom we can say the following:
The top-left corner of each rectangle is on the right or bottom edge of another rectangle except for the first one added. So, when we search for a position, we will do it along these edges of all the rectangles added before. The test, if it fits in a certain position, can be done with an intersection check with all other already added rectangles, which right or bottom edges are not left or top of the tested position. Ofcourse the rectangle to add must be inside the bolt.
This will reduce the postions to check and also give a solution for the overlapping problem Robert has mentioned. In those cases where the fit test fails, it should be tested, how large the overlapping area is - if it is not so big, it is perhaps a good idea to shift the rectangle, which would be overlapped otherwise. During such a shift operation the rule of the top-left-corner sitting on the right or bottom edge of another rectangle can be broken, instead the rule is, that an edge is in contact with another rectangle's edge.
Ok, this for now
greetings Marsian

Similar Messages

  • Cannot find symbl method update Date(int,java.util.Date)

    I get following error
    cannot find symbl method update Date(int,java.util.Date) on compling class called GuestDataBean at line ( rowSet.updateDate( 4, guest.getDate() ); ).
    GustBean.java. I need help on why I get it.
    // JavaBean to store data for a guest in the guest book.
    package com.deitel.jhtp6.jsp.beans;
    import java.util.*;
    public class GuestBean
       private String firstName;
       private String lastName;
       private String email;
       private Date date;
       private String message;
       //Constructors
       public GuestBean(){
            public GuestBean(String firstname, String lastname, String email,Date date,String message){
                 this.firstName=firstname;
                 this.lastName=lastName;
                 this.email=email;
                 this.date=date;
                 this.message=message;
       // set the guest's first name
       public void setFirstName( String name )
          firstName = name; 
       } // end method setFirstName
       // get the guest's first name
       public String getFirstName()
          return firstName; 
       } // end method getFirstName
       // set the guest's last name
       public void setLastName( String name )
          lastName = name; 
       } // end method setLastName
       // get the guest's last name
       public String getLastName()
          return lastName; 
       } // end method getLastName
       // set the guest's email address
       public void setEmail( String address )
          email = address;
       } // end method setEmail
       // get the guest's email address
       public String getEmail()
          return email; 
       } // end method getEmail
       public void setMessage( String mess)
          message = mess;
       } // end method setEmail
       // get the guest's email address
       public String getMessage()
          return message; 
       } // end method getEmail
       public void setDate( Date dat )
          date = dat;
       } // end method setEmail
       // get the guest's email address
       public Date getDate()
          return date; 
       } // end method getEmail
    } // end class GuestBean
    GuestDataBean.java/**
    * @(#)GuestDataBean.java
    * @author
    * @version 1.00 2008/7/18
    // Class GuestDataBean makes a database connection and supports
    // inserting and retrieving data from the database.
    package com.deitel.jhtp6.jsp.beans;
    import java.sql.SQLException;
    import javax.sql.rowset.CachedRowSet;
    import java.util.ArrayList;
    import com.sun.rowset.CachedRowSetImpl; // CachedRowSet implementation
    import java.sql.*;
    public class GuestDataBean
       private CachedRowSet rowSet;
       // construct TitlesBean object
       public GuestDataBean() throws Exception
          // load the MySQL driver
          Class.forName( "org.gjt.mm.mysql.Driver" );
          // specify properties of CachedRowSet
          rowSet = new CachedRowSetImpl(); 
          rowSet.setUrl( "jdbc:mysql://localhost:3306/virsarmedia" );
          rowSet.setUsername( "root" );
          rowSet.setPassword( "" );
           // obtain list of titles
          rowSet.setCommand(
             "SELECT firstName, lastName, email,date,message FROM guest" );
          rowSet.execute();
       } // end GuestDataBean constructor
       // return an ArrayList of GuestBeans
       public ArrayList< GuestBean > getGuestList() throws SQLException
          ArrayList< GuestBean > guestList = new ArrayList< GuestBean >();
          rowSet.beforeFirst(); // move cursor before the first row
          // get row data
          while ( rowSet.next() )
             GuestBean guest = new GuestBean();
             guest.setFirstName( rowSet.getString( 1 ) );
             guest.setLastName( rowSet.getString( 2 ) );
             guest.setEmail( rowSet.getString( 3 ) );
             guest.setDate( rowSet.getDate( 4 ) );
             guest.setMessage( rowSet.getString( 5 ) );
             guestList.add( guest );
          } // end while
          return guestList;
       } // end method getGuestList
       // insert a guest in guestbook database
       public void addGuest( GuestBean guest ) throws SQLException
          rowSet.moveToInsertRow(); // move cursor to the insert row
          // update the three columns of the insert row
          rowSet.updateString( 1, guest.getFirstName() );
          rowSet.updateString( 2, guest.getLastName() );
          rowSet.updateString( 3, guest.getEmail() );
          rowSet.updateDate( 4, guest.getDate() );
          rowSet.updateString( 5, guest.getMessage() );
          rowSet.insertRow(); // insert row to rowSet
          rowSet.moveToCurrentRow(); // move cursor to the current row
          rowSet.commit(); // propagate changes to database
       } // end method addGuest
    } // end class GuestDataBean

    This isn't a JSP question, it better belongs in the JavaProgramming, or JDBC forums.
    But the problem is because the updateDate method uses a java.sql.Date object and you are giving it a java.util.Date object. You have to convert from java.util.Date to java.sql.Date. See: [the api for java.sql.Date|http://java.sun.com/javase/6/docs/api/java/sql/Date.html] .
    Edited by: stevejluke on Jul 21, 2008 5:43 PM

  • Operator + cannot be applied to operands of type 'method group and 'int'

    Hello I have a problem that I'm trying to fire a bullet everytime I pressed the spacebar key, but I have this problem that is cropping up.
     if ((e.KeyCode == Keys.Space) && (playerOne.Bullet.Alive == false))
                                playerOne.Bullet.Alive = true;
                                playerOne.Bullet.getX = playerOne.getXposition + 15;
                                playerOne.Bullet.getY = playerOne.getYposition + 10;
    It says in the error list: "Opeartor '+' cannot be applied to operands of type 'method group' and 'int'", I have no clue. I'm also new to programming.

    I want to get the bullet to shoot where the player is, here is the code:
    class Player
            // attributes here  -   Int other words data types and variables:
            int health = 3;
            float xPosition;
            float yPosition;
            Bitmap playerGraphics;
            int score = 0;
            bool leftPressed;
            bool rightPressed;
            float Width = 50;
            public Bullet Bullet = new Bullet();
            // functions here:
            public void Init()
                // Get Player_Bat.png from resources, so that we can work with it:
                playerGraphics = new Bitmap(Green_Aliens.Properties.Resources.Player_Bat);
                health = 3;
                score = 0;
                xPosition = 375;
                yPosition = 540;
                leftPressed = false;
                rightPressed = false;
                Bullet Bullet = new Bullet();
            public float getWidth()
                return Width;
            public void toggleLeftPressed()
                if (leftPressed == true)
                    leftPressed = false;
                else
                    leftPressed = true;
            public void toggleRightPressed()
                if (rightPressed == true)
                    rightPressed = false;
                else
                    rightPressed = true;
            public bool getLeftPressed()
                return leftPressed;
            public bool getRightpressed()
                return rightPressed;
            public Bitmap getGraphics()
                return playerGraphics;
            public float getXposition()
                return xPosition;
            public float getYposition()
                return yPosition;
            public int getHealth()
                return health;
            public int getScore()
                return score;
            public void moveLeft()
                xPosition -= 10;
            public void moveRight()
                xPosition += 10;
            public void loseLife()
                health--;
            public void adScore(int valueAdd)
                score += valueAdd;
            //Resets the player to the start position:
            public void resetPosition()
                xPosition = 400;
                yPosition = 550;

  • 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

  • SAX-ContentHandler -characters methods gets wrong int end sometimes

    Hi
    I am having problems with SAX-ContentHandler -characters methods. It gets wrong int end values time to time ---means that it chops up my strings when it reads large XML files.
    Is there any way to correct it? Any suggestions will be very helpful. Thank you.
    My code is below.
    public class MyContentHandlerDemo extends Thread implements ContentHandler{
    private ArrayList hitList = new ArrayList(1000);
    private ArrayList hitId = new ArrayList(1000);
    private ArrayList hspNum = new ArrayList(1000);
    private ArrayList hitLength = new ArrayList(1000);
    private ArrayList queryFrom = new ArrayList(1000);
    private ArrayList hspith = new ArrayList(1000);
    private ArrayList idith = new ArrayList(1000);
    private String localname;
    private Locator locator;
    private int know=1;
    private int knowid=1;
    private int knowlength=1;
    private int knowhitlength=1;
    private int knowhspnum=1;
    private int knowhspnumadd=1;
    private int knowhspnumlength=1;
    private int knowquery=1;
    private int knowqueryfrom=1;
    private int processon =1;
    private int processcount = 0;
    private int hspithnum=0;
    private int idithnum=0;
    String allstr;
    String addseq;
    char [] allchar;
    int icount=0;
    int lengthsum=0;
    public synchronized void setDocumentLocator(Locator locator) {
    System.out.println(" * setDocumentLocator() called");
    // We save this for later use if desired.
    this.locator = locator;
    public synchronized void startDocument() throws SAXException {
    System.out.println("Parsing begins...");
    public synchronized void endDocument() throws SAXException {
    try {
    FileOutputStream outputfileDemo;
    PrintStream printoutDemo;
    outputfileDemo= new FileOutputStream("apoe500.fasta");
    printoutDemo=new PrintStream(outputfileDemo);
    FileOutputStream reSaxfile;
    PrintStream printoutReSax;
    reSaxfile= new FileOutputStream("reSax.txt");
    printoutReSax=new PrintStream(reSaxfile);
    int m = hitList.size();
    for (int k=0; k < m; k++) {
    int comp = (((hitList.get(k)).toString()).length());
    String strComp = Integer.toString(comp);
    String hitleng = (hitLength.get(k)).toString();
    if(strComp.compareTo(hitleng)!=0)
    {System.out.println("Warning: Length is different at hit number (-1) " + hitId.get(k));}
    for (int l=0; l < hspith.size(); l++){
    printoutReSax.println((hspith.get(l)).toString());
    outputfileDemo.close();
    printoutDemo.close();
    reSaxfile.close();
    printoutReSax.close();
    } catch (IOException e) {
    System.out.println("IOException errors");
    System.out.println("...Parsing ends.");
    public synchronized void processingInstruction(String target, String data)
    throws SAXException {
    //System.out.println("PI: Target:" + target + " and Data:" + data);
    public synchronized void startPrefixMapping(String prefix, String uri) {
    //System.out.println("Mapping starts for prefix " + prefix +
    // " mapped to URI " + uri);
    public synchronized void endPrefixMapping(String prefix) {
    //System.out.println("Mapping ends for prefix " + prefix);
    public synchronized void startElement(String namespaceURI, String localName,
    String rawName, Attributes atts)
    throws SAXException {
    localname =localName;
    int which =100;
    if (localname.equals("Hit_id")) {which = 0;}
    if (localname.equals("Hsp_num")) {which = 1;}
    if (localname.equals("Hsp_hseq")) {which = 2;}
    if (localname.equals("Hsp_align-len")) {which =3;}
    if (localname.equals("Hsp_query-from")) {which =4;}
    switch (which){
    case 0: knowid=0;
    //icount=icount+1;
    break;
    case 1: knowhspnum=0;icount=icount+1;
    break;
    case 2: know=0; //icount=icount+1;
    break;
    case 3: knowlength=0; //icount=icount+1;
    break;
    case 4: knowquery=0; //icount=icount+1;
    break;
    default: knowid=1; know=1; knowlength=1; knowhspnum=1;knowhitlength=1;knowquery=1;
    public synchronized void endElement(String namespaceURI, String localName,
    String rawName)
    throws SAXException {
    //System.out.println("endElement: " + localName + "\n");
    public synchronized void characters(char[] ch, int start, int end)
    throws SAXException {
    String s = new String(ch, start, end);
    int process=100;
    if (knowid==0) {process=0;}
    if (knowhspnum==0){process=1;}
    if (know==0) {process=2;}
    if (knowlength==0) {process=3;}
    if(knowquery==0){process=4;}
    switch(process){
    case 0:
    idithnum = idithnum+1;
    //int start1 = start;
    //int end1 = end;
    //char [] datahold1 = new char[end1];
    //for (int i=0;i<end1;i++){
    //datahold1=ch[start1+i];
    //warn if the length is differernt
    int n=s.length();
    allchar = new char[n+1];
    allchar[0] = '>';
    for (int i=0; i<n; i++){
    allchar[i+1]=s.charAt(i);
    allstr = new String(allchar);
    hitId.add(allstr);
    knowid=1;
    processon=1;
    break;
    case 1:
    hspNum.add(s);
    if ((s.compareTo(Integer.toString(1)))!=0){
    String hspallstr = new String (allstr.concat(s));
    hitId.add(hspallstr);
    knowhspnum=1;
    processon=1;
    break;
    case 2:
    hitList.add(s);
    know=1;
    processon=1;
    break;
    case 3:
    hitLength.add(s);
    knowlength=1;
    processon=1;
    break;
    case 4:
    queryFrom.add(s);
    knowquery=1;
    processon=1;
    break;
    default: processon=0;
    public synchronized void ignorableWhitespace(char[] ch, int start, int end)
    throws SAXException {
    String s = new String(ch, start, end);
    public synchronized void skippedEntity(String name) throws SAXException {

    I put some more codes in characters(). Then I got OutOfMemory: Java Heap Error.
    I probably have to write something in startElement() to limit input for characters() method.
    Could anyone help me? I need to limit inputs for charactes() in startElement().
    I added some codes in characters() method
    public synchronized void characters(char[] ch, int start, int end)
            throws SAXException {
            String s;
            StringBuffer stringbuf1;
            String finalstring1;
            int process=100;
            if (knowid==0) {process=0;}
            if (knowhspnum==0){process=1;}
            if (know==0) {process=2;}
            if (knowlength==0) {process=3;}
            if(knowquery==0){process=4;}
            switch(process){
            case 0:
            //s = new String(ch, start, end);
            idithnum = idithnum+1;
            //int start1 = start;
            //int end1 = end;
            //char [] datahold1 = new char[end1];
            stringbuf1 = new StringBuffer();
            while(ch!=null){
            stringbuf1.append(ch);   
            finalstring1 = stringbuf1.toString();
            //warn if the length is differernt
            int n=finalstring1.length();
            allchar = new char[n+1];
            allchar[0] = '>';
            for (int i=0; i<n; i++){
            allchar[i+1]=finalstring1.charAt(i);
            allstr = new String(allchar);
            hitId.add(allstr);
            knowid=1;
            processon=1;
            break;
            case 1:
            //s = new String(ch, start, end);
            stringbuf1 = new StringBuffer();
            while(ch!=null){
            stringbuf1.append(ch);   
            finalstring1 = stringbuf1.toString();
            hspNum.add(finalstring1);
            if ((finalstring1.compareTo(Integer.toString(1)))!=0){
            String hspallstr = new String (allstr.concat(finalstring1));
            hitId.add(hspallstr);
            //System.out.println(allstr);
            knowhspnum=1;
            processon=1;
            break;
            case 2:
            //s = new String(ch, start, end);
            //int lengthend=end;
            stringbuf1 = new StringBuffer();
            while(ch!=null){
            stringbuf1.append(ch);   
            finalstring1 = stringbuf1.toString();
            checklength:
            while(know==0){
            if(lengthend!=new Integer((hitLength.get(hitLength.size()-1)).toString())){
            String s1=new String(ch, start, end);
            s = (((hitList.get((hitList.size())-1)).toString()).concat(s1));
            hitList.add(s);know=1;
            break;
            hitList.add(finalstring1);
            processon=1;
            break;
            case 3:
            //s = new String(ch, start, end);
            stringbuf1 = new StringBuffer();
            while(ch!=null){
            stringbuf1.append(ch);   
            finalstring1 = stringbuf1.toString();
            hitLength.add(finalstring1);
            knowlength=1;
            processon=1;
            break;
            case 4:
            //s = new String(ch, start, end);
            stringbuf1 = new StringBuffer();
            while(ch!=null){
            stringbuf1.append(ch);   
            finalstring1 = stringbuf1.toString();
            queryFrom.add(finalstring1);
            knowquery=1;
            processon=1;
            break;
            default: processon=0;

  • Little method problem! int cannot be de-referrenced

    I have a object array of a class called rooms.
    I declared it at the beginning of the code and used it many times.
    Room[] rooms = new Room[houseRooms];
    private static void displayResults(int rooms[], int i )
              System.out.println("Room " +(i+1)+"\n width = " +rooms.getWidth()+ " length= " +rooms[i].getLength()+ ", Area = " +rooms[i].findArea() );
    As you see i am trying to input that parameter array of an object class... but its not letting me specify it self to be an integer so that i could use it. Maybe there is a way around?

    I have a object array of a class called rooms.
    I declared it at the beginning of the code and used it
    many times.
    Room[] rooms = new Room[houseRooms];
    private static void displayResults(int rooms[], int i
    System.out.println("Room " +(i+1)+"\n width = "
    +rooms.getWidth()+ " length= "
    +rooms[i].getLength()+ ", Area = "
    +rooms[i].findArea() );
    You have a field (a member variable) called rooms that is an array of Room.
    Inside displayResults you have a method variable (i.e., a local variable) call rooms taht is an array of int.
    When you refer to "rooms" which one will you be talking about?
    If you're inside displayResults (or any other method that has a local "rooms" variable, then the local one will hide the field. So in that context, rooms is an array of int, not an array of Room.
    What is that array of ints supposed to represent in the displayResults method? Did you really mean for it to be an array of Rooms? If you do need an array of ints, then you have two choices:
    1) Change the name of the method parameter, so it doesn't hide the member variable.
    2) Use "this.rooms" to refer to the member when you're inside the method.
    I recommend #1.
    Also, to the other poster, you can't extend int  because it's a primitive, and you can't extend Integer because it's final. Integer and int are not the same. However, with autoboxing/unboxing in 1.5, the switch between them can be transparent much of the time, from my understanding.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • Returning int array from C to Java as method parameter

    Hello,
    I've been trying to accomplish this
    Java
    int[] myArray = ... (filled with some data);
    int retCode = myNativeCall(myArray);
    if(retCode == 0)
    doSomethingWith(myArray); //myArray gets overwritten with new data (with new size also) during the native call...
    C
    JNIEXPORT jint JNICALL Java_GenChav_rsaEncrypt(JNIEnv *env, jobject obj, jintArray myArray){
    jintArray outbuf;
    int[] new_array = .. // some function will fill this....
    int new_array_length = ...//some function will give me the new size, not big, 512 max...
    jint tmp[new_array_length]; //allocate..need something more ??
    memcpy(tmp, new_array, new_array_lenght);
    outbuf=(*env)->NewIntArray(env, new_array_length);
    (*env)->SetIntArrayRegion(env, outbuf, 0, new_array_length, tmp);
    myArray=outbuf;
    I tought this way I would have a updated myArray ints on the Java program...
    Any thought??

    user5945780 wrote:
    Ok, let's try to be constructive here...
    How I do implement a return type for my method like a int array ?First realized it has nothing to do with JNI. So the same question and answer applies to java only.
    >
    like:
    int[] return = myNativeCall();
    Yes.
    Then I will look for return[0], if it is == to 0, fine, it means a successful calculation by the native code. Not sure what that means. The structure of what you return it up to you.
    It can help when you are unsure of what to do in JNI....write a pseudo representation of what you want to do in a java method. Then translate that java method into JNI, everything in the pseudo method must be in the JNI code.

  • Refl.Method.invoke(int)

    Hi,
    I would like to invoke a method having primitive int argument through the reflection api.
    Class[] parTypes = new Class[] {int.class};
    Method setIdMethod = myclass.getMethod("setHID", parTypes);
    int cnter = 0;
    Object[] args = new Object[] {cnter}; !!!!!!!!!!!!!! I can not do this!
    setIdMethod.invoke( obj, args);
    The problem, thet the Method.invoce have the obj and Object[] arguments. I can not pass a variable with primitive type.
    Do you know a work-around?
    Thanks,
    Tamas

    To pass primitive values, you have to wrap them in the corresponding Object type.
    E.g. to call a method taking an "int", via reflection, you have to do the actual call as follows:
      setIdMethod.invoke(obj, new Object[]{new Integer(cnter)});

  • About method 'write(int b)' in class 'OutputStream'

    Hello, everyone,
    In OutputStream class, there is a method called "write(int b)". In the API Specification, the explanation of this method is: Writes the specified byte to this output stream.
    I am just wondering, if the type of b is 'int', then how can it say " to write the byte to the stream"?

    Because the lower 8 bits of an int are the same value as a byte.
    -1 ==> 11111111 11111111 11111111 11111111 ==> 11111111
    0 ==> 00000000 00000000 00000000 00000000 ==> 00000000
    1 ==> 00000000 00000000 00000000 00000001 ==> 00000001
    255 ==> 00000000 00000000 00000000 11111111 ==> 11111111
    So it's essentially the same thing. Just chops off the upper 24 bits. The other thing is it's not uncommon to maintain byte values in ints for unsigned-ness, and if the method took a byte, it would require an explicit cast do to possible loss of precision, whereas a byte can be implicitly cast to an int with no alteration to the actual value represented.

  • Question in: charAt( int  i ) , method's of StringBuffer

    In class String Buffer() there is a method called charAt( int i ). My question are:
    a) What is the exact integer range for data type int?
    b) Consider the code below:
    =================================================================================
    buf_out     = new BufferedOutputStream(servlet_out); // servlet_out is an instant of ServletOutputStream
    int str_len     = str_buf.length(); // str_buf is an instant of StringBuffer
    for (int i = 0; i < str_len; i++) {
         buf_out.write(str_buf.charAt(i));
    =================================================================================
    Now,what are the consequences if the value of str_len is bigger than the integer range?
    Hope to c positive response from u guys. Thanks

    a) 2^31 - 1 (just shy of 2 GB) -- see Integer.MAX_VALUE
    b) All the size related methods of StringBuffer take an int as an argument. It therefore follows that a StringBuffer may not be larger than Integer.MAX_VALUE characters. Also, since StringBuffer is backed by a char[] array, it also cannot be larger than Integer.MAX_VALUE since arrays may only have at most Integer.MAX_VALUE elements.
    The whole argument is pretty much academic however -- since a StringBuffer with 2 billion elements will take up a minimum of 4 GB of RAM (chars are 32 bits), its highly unlikely that you could every create a StringBuffer that large without blowing up your JVM.

  • Trying to get the 1st character from an int

    Hello all,
    Ill try to make this as easy to explain as possible.
    I want to get the 1st number of the int that the person enters
    so for example: 100
    then i want to get 1
    200
    then 2
    and so on...
    Here is the code so far. It works, but i just dont know where to get it from and i need it to be able system.println it.
    Once again, thank you.
    package bars;
    public class Employee {
    // class constants
    // Data fields
    private String custName;
    private String custAddress;
    private double rate;
    private int custID;
    private double steve;
    public Employee(int id, String name, String adress, double ra) {
    custName = name;
    custAddress = adress;
    rate = ra;
    custID = id;
    public String toString() {
    return "Customer ID: "+ custID + "Customer Name : " + custName +
    "Customer Adrress" + custAddress + "rate: $" + rate ;
    public int getBalls(){
    return custID;
    public String getBallsy(){
    return custAddress;
    public double getRate(){
    return rate;
    the other one...
    package bars;
    import javax.swing.JOptionPane;
    import javax.swing.*;
    import java.util.*;
    public class EmployeeApp {
    //methods
    private static int readInt (String prompt){
    String numStr = JOptionPane.showInputDialog(prompt);
    return Integer.parseInt(numStr);
    private static double readDouble (String prompt){
    String numStr = JOptionPane.showInputDialog(prompt);
    return Double.parseDouble(numStr);
    public static void main (String[] args){
    //read and store the payroll data in an employee object
    Vector programmers = new Vector();
    for (int i = 0; i < 1; i++) {
    Employee programmer =
    new Employee(
    readInt("Enter Customer ID: "),
    JOptionPane.showInputDialog("Name: " ),
    JOptionPane.showInputDialog("Address: "),
    readDouble ("Enter hourly rate: ")
    int steve = programmer.getBalls();
    int bob = steve;
    programmers.add(programmer);
    System.out.println("here: " + steve);
    System.out.println(programmers.toString());

    I am not sure what you want, but this method will return the left digig.
    public int getLd(int n)
         if (n > 10) return(getLd(n/10));
              else       return(n);
    }Noah

  • Problem with defining ints

    I have a method that defines ints to 4 and uses them in the method. But I only want them defined to 4 when the method is invoked the first time.
    public static void example()
    int x = 4, y = 4;
    x -= 1;
    y -= 1;
    }Is there a way for x and y to remain at 3 after the first use of the method then go to 2 if the method is used again?

    aufde wrote:
    I'm not really sure what member variables are vs. local variables. I'm kind of new to Java and I'm not really good with the jargon yet.
    Anyways, after some experimenting, I got it to do what I wanted.
    public class example
    static int x = 4, y = 4;
    public static void minus()
    x -= 1;
    y -= 1;
    }I'm not sure if this would be the right way to do it.Yep, that's basically what I suggested but now you only have one x and one y per class because everything is static now.
    kind regards,
    Jos

  • Int to enum question

    I have an old program, the method take an int as parameter, in side the method, I check each int value and take action like:
    switch(i)
    case Const.A: ...
    case Const.B: ...
    Const is a class defined sone constant values like
    static final int A = 1;
    static final int B = 2;
    now, I would like to change Const to a enum. define A, B as enum's elements. but i don't want to change method's parameter, which means the method still take int as parameter. how can I map the passed in int to each enum element

    now, I would like to change Const to a enum. define
    A, B as enum's elements. but i don't want to change
    method's parameter, which means the method still take
    int as parameter. how can I map the passed in int to
    each enum elementWhy are you not able (or desiring) to change the method to accept an enum parameter?
    One way to get the enum's ordinality is to use the ordinal method. This is kind of the converse to what jverd was showing you.
        myMethod(myEnum.ordinal()); //changes enum to its integerBut as jverd states, best to use enums as enums and integers as integers.

  • Int printing out as scientific notation

    maybe doing something stupid here but I can't seem to pick it up.
    I have a Window that calls a subclass to display a calculator, and then returns the final value to the Window, if I input 10 digits it prints on as a 12345678E5
    something like that.
    Anywho here's the two methods that deal with value in the subclass( calculator )
    public int ReturnNumber(){//the method that will return the value from the keyboard
       int final_number = Integer.parseInt(number); 
        return final_number;   // returns value to question screen
      private void NextButtonActionPerformed (java.awt.event.ActionEvent evt) {
       if ( value.length() != allowable_answers[currentQuestionNumber] ){
                     JOptionPane.showMessageDialog(this, "Please make a valid entry.", "Invalid",
                     JOptionPane.WARNING_MESSAGE );
                     value.replace(0,counter,""); 
                     jTextField1.setText( null );
                     return;
        else {
                number = value.toString();
               setVisible(false);
               frame.final_number = ReturnNumber();
               frame.userMakeSelection = true;
               frame.FinalTimer.start();
               frame.ButtonSelected();Code from window that deals with the number
    if(Numeric[currentQuestionNumber]){
                currentAnswers[currentQuestionNumber][1] = final_number;// currentAnswers is a float[][]
                numeric_question_value[currentQuestionNumber][0] = final_number;// used in poll frequency
              }// numeric is a int[]
            else
                currentAnswers[currentQuestionNumber][currentChoice] = currentChoice;Is from trying to jam an int into float?
    Any suggestions
    Jim

    Is from trying to jam an int into float?That's exactly the cause. Here are some solutions:
    - Use java.text.DecimalFormat to format the output or cast the float to an integer type when you want to print it (presicion might become a problem).
    - Keep the number in an int or long all the time. This way you'll not lose any presicion.
    Explanation can be found in the API docs of Float.toString():"If the argument is NaN, the result is the string "NaN".
    Otherwise, the result is a string that represents the sign and magnitude (absolute value) of the argument. If the sign is negative, the first character of the result is '-' ('-'); if the sign is positive, no sign character appears in the result. As for the magnitude m:
    If m is less than 10^-3 or not less than 10^7, then it is represented in so-called "computerized scientific notation." Let n be the unique integer such that 10n<=m<1; then let a be the mathematically exact quotient of m and 10n so that 1<a<10. The magnitude is then represented as the integer part of a, as a single decimal digit, followed by '.' (.), followed by decimal digits representing the fractional part of a, followed by the letter 'E' (E), followed by a representation of n as a decimal integer, as produced by the method Integer.toString(int) of one argument."

  • Int to char - char to int

    I have 2 methods.
    The first method takes an int from 0-256 and casts it to a char and then places the char in a string:
    cCryptedString [iLoop] = (char) iCryptedValue;
    The second method reads the string and casts each character from it into an int.
    iPassStringValue = (int) aString.charAt(iLoop);
    If the iCryptedValue in the 1st method is > 127 and < 150 (because that's as far as they will go at the moment), the casting of that int (i.e. 145) to a char results in a ? being placed in cCryptedString[iLoop].
    When the 2nd method reads the string and encounters the ? placed by the first method, the casting of that char to an int results in a 63 (the ascii value of a ?) instead of the original 145.
    This was not a problem until I installed and ran WebLogic 6.0 sp2 using jdk 1.3 on a Windows 2000 machine. It is working fine under WebLogic 5.1 using jdk 1.2.2.
    Any ideas?
    Thanks,
    Mark

    Here is the 1st method:
    public String encryptString(String aString) {
    int iPassStringValue = 0;
    int iEncryptKeyValue = 0;
    int iCryptedValue = 0;
    char cCryptedString [] = new char[aString.length()];
    for (int iLoop = 0; iLoop < aString.length(); iLoop++) {
    iPassStringValue = (int) aString.charAt(iLoop);
    iEncryptKeyValue = (int) sEncryptKey.charAt(iLoop);
    iCryptedValue = iPassStringValue + iEncryptKeyValue;
    if (iCryptedValue > 255)
    iCryptedValue = iCryptedValue - 256;
    cCryptedString [iLoop] = (char) iCryptedValue;
    return new String(cCryptedString);
    Here is the 2nd method:
    public String decryptString(String aString) {
    int iPassStringValue = 0;
    int iEncryptKeyValue = 0;
    int iDecryptedValue = 0;
    char cDecryptedString [] = new char[aString.length()];
    for (int iLoop = 0; iLoop < aString.length(); iLoop++) {
    iPassStringValue = (int) aString.charAt(iLoop);
    iEncryptKeyValue = (int) sEncryptKey.charAt(iLoop);
    iDecryptedValue = iPassStringValue - iEncryptKeyValue;
    if (iDecryptedValue < 0)
    iDecryptedValue = iDecryptedValue + 256;
    cDecryptedString [iLoop] = (char) iDecryptedValue;
    return new String(cDecryptedString);
    Thanks!!

Maybe you are looking for

  • Lack of DIY hardware upgrades for retina MacBook Pro

    Can any hard-core Apple Fanboys testify that somehow built in ram on new retina MacBook Pro's is more stable than replaceable RAM modules which have come with previous models? I understand Apple's decision to move to built-in ram to make the overall

  • Itunes not organizing music

    When i add songs to itunes it doesnt put them in a folder by artist and album. it just puts them in the itunes music folder. i have the setting that makes itunes organize music checked.

  • Alternate row color for table question

    I'm alternating the row color on a table, and if I have a <a href> in the table, the background behind the <a href> isn't the same as the row color based on: <tr bgcolor="###iif(currentrow mod 2,de('ffffff'),de('efefef'))#"> Is there a way to have th

  • ITunes closes when attempting AAC.

    How come I can't get iTunes to create an AAC version of a song? It closes every time I attempt it.

  • Multiple drive backups

    Hi - I have a multiple hard drive array (system drive, audio drive, sample library drive) and wish to have autmoated backups over 3 mirrored drives... can Time Machine do this? In other words I want one backup drive to each primary drive. Thanks