Integer array reverse
* arrayReverse method
* intArray = {1,2,3,4,5,6,7,8,9,10}, this method is supposed to
* reverse the values (e.g. 10,9,8,7,6,5,4,3,2,1..)
public void arrayReverse()
for (int index = 0; index < 4; index++)
for (int scan = 9; index > 5; scan--)
int temp = intArray[index];
arrayChange(index, intArray[scan]);
arrayChange(scan, intArray[temp]);
}I've been attempting this for the better part of my evening and can't seem to make out what I'm doing wrong.
I know for instance, that my for loops are at fault; but I haven't made one step forward in switching any of the values.
any help would be greatly appreciated
v/r,
mess
Suggestions:
Instead of
int next = 9;Do
int next = intArray.length;And instead of
for (int index = 0; index < 4; index++)do
for (int index = 0; index < intArray.length/2; index++)This will make your code work no matter if intArray has 10 elements, 3 elements or 25 elements. And it's what I meant when I said to get rid of the magic numbers.
Similar Messages
-
Code for how to read an integer array from the command prompt...
hello,
Could anyone give me the code for how to read an integer array from the command prompt...its very urgent!..If you are using a recent version of Java (5 or later) you can use Scanner:
http://java.sun.com/javase/6/docs/api/java/util/Scanner.html
That page has some example code on it, too. -
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 -
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. -
How to bind SelectManyChoice to Integer array parameter
Hi.
I am using JDev TP4. I need to populate an integer array with the keys of the items selected in a SelectManyChoice.
I have created a page with a parameter form for the three parameters and a readonly table for the result class from a data control for this method:
public FreeGuaranteeModel[] getFreeGuarantees(Timestamp firstDate, Timestamp lastDate, Integer[] companyIds)
In the parameter form i have created a SelectManyChoice which displays a list
from a viewObject by dragging the companyIds parameter onto the parameter form, creating a SelectSingle component and then converted it to a SelectManyChoice.
The page renders ok, I can select one or more items in the list, but when I press the button to execute the method, the companyIds array is empty.
(The two date parameters are populated).
What am I missing? Is the binding wrong? I am new to JDev so if there is some other way to do this, please let me know.
This is the relevant part of the jspx:
<af:selectManyChoice value="#{bindings.companyIds.inputValue}"
label="#{bindings.companyIds.label}"
shortDesc="#{bindings.companyIds.hints.tooltip}"
binding="#{backing_ViewFinancialResult.selectOneListbox1}"
id="selectOneListbox1">
<f:selectItems value="#{bindings.companyIds.items}"
binding="#{backing_ViewFinancialResult.selectItems1}"
id="selectItems1"/>
</af:selectManyChoice>
The pagedef contains this:
<?xml version="1.0" encoding="UTF-8" ?>
<pageDefinition xmlns="http://xmlns.oracle.com/adfm/uimodel"
version="11.1.1.49.49" id="ViewFinancialResultPageDef"
Package="com.ispartner.gvg.pageDefs">
<parameters/>
<executables>
<variableIterator id="variables">
<variable Type="java.sql.Timestamp" Name="getFreeGuarantees_firstDate"
IsQueriable="false"/>
<variable Type="java.sql.Timestamp" Name="getFreeGuarantees_lastDate"
IsQueriable="false"/>
<variable Type="java.lang.Integer[]" Name="getFreeGuarantees_companyIds"
IsQueriable="false"/>
</variableIterator>
<methodIterator Binds="getFreeGuarantees.result"
DataControl="CapacityReader" RangeSize="25"
BeanClass="com.ispartner.gvg.util.capacity.FreeGuaranteeModel"
id="getFreeGuaranteesIterator"
RefreshCondition="#{adfFacesContext.postback == true}"
Refresh="renderModelIfNeeded"/>
<iterator Binds="CompanyLOV1" RangeSize="-1"
DataControl="ChoiceListAMDataControl" id="CompanyLOV1Iterator"/>
</executables>
<bindings>
<methodAction id="getFreeGuarantees" RequiresUpdateModel="true"
Action="invokeMethod" MethodName="getFreeGuarantees"
IsViewObjectMethod="false" DataControl="CapacityReader"
InstanceName="CapacityReader.dataProvider"
ReturnName="CapacityReader.methodResults.getFreeGuarantees_CapacityReader_dataProvider_getFreeGuarantees_result">
<NamedData NDName="firstDate" NDType="java.sql.Timestamp"
NDValue="${getFreeGuarantees_firstDate}"/>
<NamedData NDName="lastDate" NDType="java.sql.Timestamp"
NDValue="${getFreeGuarantees_lastDate}"/>
<NamedData NDName="companyIds" NDType="java.lang.Integer[]"
NDValue="${bindings.getFreeGuarantees_companyIds}"/>
</methodAction>
<attributeValues IterBinding="variables" id="firstDate">
<AttrNames>
<Item Value="getFreeGuarantees_firstDate"/>
</AttrNames>
</attributeValues>
<attributeValues IterBinding="variables" id="lastDate">
<AttrNames>
<Item Value="getFreeGuarantees_lastDate"/>
</AttrNames>
</attributeValues>
<tree IterBinding="getFreeGuaranteesIterator" id="FreeGuaranteeModel">
<nodeDefinition DefName="com.ispartner.gvg.util.capacity.FreeGuaranteeModel">
<AttrNames>
<Item Value="companyId"/>
<Item Value="name"/>
<Item Value="guaranteeRequired"/>
<Item Value="guaranteeToDate"/>
<Item Value="guaranteeAmount"/>
<Item Value="bookedValue"/>
<Item Value="freeGuarantee"/>
</AttrNames>
</nodeDefinition>
</tree>
<list IterBinding="variables" id="companyIds" DTSupportsMRU="false"
StaticList="false" ListIter="CompanyLOV1Iterator"
NullValueFlag="start" NullValueId="companyIds_null">
<AttrNames>
<Item Value="getFreeGuarantees_companyIds"/>
</AttrNames>
<ListAttrNames>
<Item Value="CompanyId"/>
</ListAttrNames>
<ListDisplayAttrNames>
<Item Value="ShortName"/>
</ListDisplayAttrNames>
</list>
</bindings>
<ResourceBundle>
<PropertiesBundle xmlns="http://xmlns.oracle.com/adfm/resourcebundle"
PropertiesFile="com.ispartner.gvg.gvg-webBundle"/>
</ResourceBundle>
</pageDefinition>
Regards,
TLHi,
Thank you for your answer.
Following the example I was able to get the selected entries into an Integer array property with accessors which I created in a managed bean.
But I have not been able to get the values into the companyIds parameter of the method to execute.
Is there a way to bind directly to this parameter, or do I have to collect all parameters through separate properties and then call my method manually when the button is pressed?
TL -
Passing a integer array client to server
Hi
Is it possible to pass integer array from client to server
Through soap.
Basically i want to pass this array buffer
int[] buffer = new int[(int)len];
for(int i=0;i<len;i++){
buffer[i] = F.read();
System.out.print(buffer[i]+ " ");
Nams ThanksYes, if the server is written to accept one.
To create a server to accept one, create a service endpoint
interface that has a method that takes a int[] as a parameter and
generate the service from that by following the steps in the jaxrpc
tutorial. Then generate the client from the generated WSDL. -
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?
-
Guys!! any one can help me in recursive permutation of integer array!!
this is the description of my problem:
We are supposed to develop a recursive method with the following header:
public static boolean nextPermutation(int[] array)
The method receives an integer array parameter which is a permutation of integers 1, 2, �, n. If there is �next� permutation to the permutation represented by the array, then the method returns true and the array is changed so that it represents the �next� permutation. If there is no �next� permutation, the method returns false and does not change the array.
Here is a verbal description of the recursive algorithm you need to implement:
1. The first permutation is the permutation represented by the
sequence (1, 2, �, n).
2. The last permutation is the permutation represented by the
sequence (n, �, 2, 1).
3. If is an arbitrary permutation, then the �next� permutation is
produced by the following procedure:
(i) If the maximal element of the array (which is n) is not in the first
position of the array, say , where , then just swap and . This
will give you the �next� permutation in this case.
(ii) If the maximal element of the array is in the first position, so ,
then to find the �next� permutation to the permutation , first find
the �next� permutation to , and then add to the end of thus
obtained array of (n-1) elements.
(iii) Consecutively applying this algorithm to permutations starting
from (1, 2, �, n), you will eventually list all possible
permutations. The last one will be (n, �, 2, 1).
For example, below is the sequence of permutations for n = 3 , listed by the described algorithm:
(0 1 2) ; (0 2 1) ; (2 0 1) ; (1 0 2) ; (1 2 0) ; (2 1 0)
if any one can help me then please help me!! i am stucked at this position to find permutation of the integer array.
thanks,Sure. Why don't you post the code you already have done, and maybe
someone here can help you with it. -
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();
} -
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 KontosHere'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();
} -
Saving modifled ARGB values in an Integer array to a jpeg file?
Hi,
I have searched sites and forums and it seems that the key to this is to use BufferedImage and Graphics's drawImage(). But how can I use the drawImage when I only have an array of integer values?
I went through the docs and seems that BufferedImage class's setRGB() method may suit my purpose but the results were negative. The saved jpeg was just painted black instead of the photo.
Does my code below make any sense or am I missing out something here? Any help will be greatly appreciated!
//from my code, oneDPix is an int[] array containing modified ARGB values
BufferedImage buff = new BufferedImage(imgCols,imgRows,BufferedImage.TYPE_INT_ARGB);
Graphics2D g = buff.createGraphics();
buff.setRGB(0,0,imgCols,imgRows,oneDPix,0,imgCols);
try {
String targetFile = "/Users/cover.jpg";
ImageIO.write(buff,"jpg", new File(targetFile));
} catch (IOException ex) {
ex.printStackTrace();
}hi, if your array has the right values, then you could use the createImage method of the class Toolkit and teh class MemoryImageSource for making the image before, something like this:
Image ima = Toolkit.getDefaultToolkit().createImage(new MemoryImageSource(numOfColumns, numOfRows, ColorModel.getRGBdefault(), array, 0, numOfColumns));
BufferedImage bi = new BufferedImage(numOfColumns, numOfRows, BufferedImage.TYPE_INT_RGB);
Graphics g = bi.getGraphics();
g.drawImage(ima, 0, 0, null);
g.dispose();
ImageIO.write(bi,"jpg",new File(targetFile));hope this helps -
Want to pass 2D integer array from VB 6.0 to LabView (v 8.0) DLL
I was able to pass 1D arrays from VB 6.0 to LabView 8.0 with no problem. I checked the literature for help regarding 2D arrays and found
scant help unless it was for VB.NET, C or single dimensional arrays. Thanks.
I wrote a simple test VB program to pass 2D arrays shown below after which I get a memory crash:
Private Declare Sub Test2D Lib _
"C:\Documents and Settings\Owner\My Documents\builds\Test2DArray\Test2DArray\Test2DArray.DLL" _
Alias "Test2darray" (ByRef varInArray As Variant, ByRef varOutArray As Variant)
Private Sub cmdStart_Click()
On Error GoTo handle_error
Dim intInArray(8, 8) As Integer
Dim intOutArray(8, 8) As Integer
Dim varInArray As Variant, varOutArray As Variant
Dim i As Long, j As Long, k As Integer
For i = 0 To 7
k = i * 8
For j = 0 To 7
intInArray(i, j) = k + j
Next j
Next i
varInArray = intInArray
varOutArray = intOutArray
Test2D varInArray, varOutArray
Exit Sub
handle_error:
MsgBox Err.Description, , ""
End Sub
In the Labview DLL I have a definition of the exported function call as:
void Test2darray(TD1Hdl * InArray, TD1Hdl * OutArray)
(in the Labview DLL I take the input array, add 1 to each of the elements and then stuff it into the output)jd162,
The following discussing forum may help out:Pass array to "Labview 7" DLL in Visual Basic . Let us know if this helps out at all.
Chris C
Chris Cilino
National Instruments
LabVIEW Product Marketing Manager
Certified LabVIEW Architect -
1D Boolean Array to 1D Integer Array conversion for FPGA FIFO
Hello, I am using a PXI7813R card. I would like to pass some data between the target (FPGA) vi and the host vi using the FIFO. I have a FIFO setup to 1023 "32 bit integer" samples. I have a boolean array of 32000 samples which would be the same as 1000 32 bit integers, that I acquired using the PXI7813R card. I would like to convert the 1D boolean array to a 1D "32 bit intger" array. This seems like a more a difficult problem than I first thought as the labview functions are reduced when targetting a FPGA device. I have attached a jpg of how I would like to do it. I am getting a "Arrays must be fixed size in current target" error for the output from the array subset function. I know this is because one of the inputs is not exactly a constant, i.e. the index input for array subset, but regardless of the index, I will only ever be taking 32 bits from the boolean array at any time to convert to a 32 bit integer to then place in the FIFO. Any suggestions of how I may get around this problem would be gratefully recieved. Regards, Michael.
Message Edited by Michael_Limerick on 02-08-2008 04:54 AM
Attachments:
fifo_out1.JPG 52 KBHi Daniel,
Thanks for your reply.
I had a look at the thread that you suggested and I'm not sure if that would solve the problem I was having, the option box was checked as default. I think my issue has to do with the limitations of the different LV functions when targeting a FPGA device.
I have decided to take another route anyway, it seems that trying to compile a large array (even a 1D boolean array) for a FPGA target both takes a long time and also a lot of FPGA resources.
Thanks again for your reply,
Regards,
Michael. -
An integer array with a string?
Sockets in my server program are stored in an array of course. I want to attach a string with it in the array
Conceptually like this:
public static OutputStream usr [] = new OutputStream[6], "name" ;
So i can track their login names with their sockets. By association. Calling an array slot would somehow return the integer and the string name.
Can anyone help me out? Thanksclass conn{
OutputStream out;
String name;
public static conn usr [] = new conn[6];
for(int i = 0; i < conn.length; i++ )
conn[ i ] = new conn( myOutputStream, "My String" );
}You should declare a class that can holds any number of members, modify the code to meet your needs
GoodLuck
Mohammed Saleem -
Creating a dynamic Integer Array
Hi there.
This may seem trivial, but how do I create a dynamic array to store integers?
I tried Integer integerArray [] = new Integer (); but i get Cannot Resolve Symbol Error.
I am using Java 1.4.2 version.
Any suggestions would be helpful. ThanksDoesnt an ArrayList store values as
String? Even if i did use Integer.parseInt to cast to
Integer from String doesnt it become tricky if i have
to do much calculations?Hi,
An ArrrayList can store any object you wish not just String. All you need to specify when retrieving an object is the type of object you want.
For example, if you have an ArrayList of integers an you want to retrieve an integer from the list you would use:-
int myInt = (int)myArrayList.get(myIndex);Therefore if you want to store an arbitrary object foo in an ArrayList the code is thus:-
//replace foo with the object you are storing.
foo foobar = (foo)myArrayList.get(myIndex);There is a slight change with ArrayLists in Java 5 where you should declare the objects that should be stored in the list but hopefully the above helps you to understand that an ArrayList or any other Collection as it happens can store objects of your choosing.
Regards,
Chris
Maybe you are looking for
-
Files and Streams in java -- How to display successive records
Hi, I developed an application in which I enter name and id in a gui. Each time I enter, the records are added in the sequential file. Then I have a button to open that file. It also opens. Then I have a button to read the records(which has name and
-
The right side of my window has been cut. Many efforts of resizing it have not helped. The left side is unusually larger.
-
MARKERS NOT SHOWING ON THE VIEWER
After editing the marker, I can see my notes on the viewer, later they disappear. Sometimes even after I edit it, I write the note, the marker is there but nothing appears on the viewer. When I open the same marker to edit, the note is gone. Show ove
-
ConfigMgr 2012 MP – suspending SCOM agent/health service
Hi, I use SCOM agent/health for our SLA reporting. I found a handful of servers last month with something like 99.9% uptime even though I knew they had been up all of the time. Looking in the Operations Manager event log I have found the following ev
-
An error occurred verifying the host credentials
Hi, I'd like to reorganize a segment in grid control 10g. I go through the reorganize wizard smoothly from the Type, Objects, Options and Impact report. But when I reach the Schedule step, I was asked to enter the host credentials. Though the user I