Storing an array of integers in a session
using the following code:
int stateCount = 50;
int[] stateId = new int[stateCount];
for(int i = 0; i<stateCount;i++){
stateId[i] = i + 1;
//so far this all works
//my problem
session.setAttribute("stateId", stateId);
int[] session_statesId = (int[]) session.getAttribute("statesId");
System.out.print(session_statesId.length);
//using this code I recieve an error. I have been able to so this storing a String array in a session but I can't figure out why the int is not working any suggestions?
that's an easy one: you do not use the same id for storing and retrieving. ever thought of using a defined constant?
private final static String STATES_KEY = "statesId";
robert
Similar Messages
-
How to convert the record stored iin byte array to integers
im making a simple game in j2me and i want to get the max scores and show it for each player , what i face right now that i cant convert the records which i stored in bytes to integers when i read it from file to get the max.
thankshave a look at java.io.DataInputStream
-
Constructing a linked list from an array of integers
How do I create a linked list from an array of 28 integers in a constructor? The array of integers can be of any value that we desire. However we must use that array to test and debug methods such as getFirst(), getLast(), etc...
I also have a method int getPosition(int position) where its suppose to return an element at the specified position. However, I get an error that says cannot find symbol: variable data or method next()
public int getPosition(int position){
LinkedListIterator iter=new LinkedListIterator();
Node previous=null;
Node current=first;
if(position==0)
return current.data;
while(iter.hasMore()){
iter.next();
if(position==1)
return iter.data;
iter.next();
if(position==2)
return iter.data;
iter.next();
if(position==3)
return iter.data;
iter.next();
if(position==4)
return iter.data;
iter.next();
if(position==5)
return iter.data;
iter.next();
if(position==6)
return iter.data;
iter.next();
if(position==7)
return iter.data;
iter.next();
if(position==8)
return iter.data;
iter.next();
if(position==9)
return iter.data;
iter.next();
if(position==10)
return iter.data;
iter.next();
if(position==11)
return iter.data;
iter.next();
if(position==12)
return iter.data;
iter.next();
if(position==13)
return iter.data;
iter.next();
if(position==14)
return iter.data;
iter.next();
if(position==15)
return iter.data;
iter.next();
if(position==16)
return iter.data;
iter.next();
if(position==17)
return iter.data;
iter.next();
if(position==18)
return iter.data;
iter.next();
if(position==19)
return iter.data;
iter.next();
if(position==20)
return iter.data;
iter.next();
if(position==21)
return iter.data;
iter.next();
if(position==22)
return iter.data;
iter.next();
if(position==23)
return iter.data;
iter.next();
if(position==24)
return iter.data;
iter.next();
if(position==25)
return iter.data;
iter.next();
if(position==26)
return iter.data;
iter.next();
if(position==27)
return iter.data;
iter.next();
if(position==28)
return iter.data;
if(position>28 || position<0)
throw new NoSuchElementException();
}How do I create a linked list from an array of 28 integers
in a constructor? In a LinkedList constructor? If you check the LinkedList class (google 'java LinkedList'), there is no constructor that accepts an integer array.
In a constructor of your own class? Use a for loop to step through your array and use the LinkedList add() method to add the elements of your array to your LinkedList.
I get an error that
says cannot find symbol: variable data or method
next()If you look at the LinkedListIterator class (google, wait for it...."java LinkedListIterator"), you will see there is no next() method. Instead, you typically do the following to get an iterator:
LinkedList myLL = new LinkedList();
Iterator iter = myLL.iterator();
The Iterator class has a next() method. -
Storing an array of checkbox booleans into preferences and retrieving them
Just wondering how to go about storing an array of JCheckBoxes into a preference and retrieving it. There's 32 checkboxes so if they select, say, 6 of these randomly it should store it in a preference file and retrieve it when the application is loaded so that the same 6 checkboxes remain selected. I'm currently getting a stack overflow error, though.
import java.util.prefs.*;
public class Prefs {
Preferences p;
GUI g = new GUI();
public Prefs() {
p = Preferences.userNodeForPackage(getClass());
g = new GUI();
public void storePrefs() {
for (int i = 0; i < g.symptoms.length; i++) {
p.putBoolean("symptoms", g.symptoms.isSelected());
public void retrievePrefs() {
for (int t = 0; t < g.symptoms.length; t++) {
p.getBoolean("symptoms", g.symptoms[t].isSelected());
symptoms is the array of checkboxes in the GUI class. Not sure where I am going wrong here. I can do it with strings from textfields etc but this is proving to be an annoyance. :(
Thanks in advanceActually, I have a better example, see below
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import java.util.prefs.*;
public class PreferencesTest {
private Preferences prefs;
public static final String PREF_OPTION = "SELECTED_MENU_ITEM";
public void createGui() {
prefs = Preferences.userNodeForPackage(this.getClass());
JMenuItem exitAndCloseMenuItem = new JMenuItem("Exit");
exitAndCloseMenuItem.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
System.exit(0);
JMenu fileMenu = new JMenu("File");
fileMenu.add(exitAndCloseMenuItem);
JCheckBoxMenuItem[] preferenceItems = {
new JCheckBoxMenuItem("pref 1"),
new JCheckBoxMenuItem("pref 2"),
new JCheckBoxMenuItem("pref 3"),
new JCheckBoxMenuItem("pref 4")};
int selectedMenuItem = prefs.getInt(PREF_OPTION, 0);
preferenceItems[selectedMenuItem].setSelected(true);
ButtonGroup preferencesGroup = new ButtonGroup();
JMenu preferenceMenu = new JMenu("Preferences");
for(int i = 0;i<preferenceItems.length;i++){
preferenceItems.setActionCommand(Integer.toString(i));
preferenceItems[i].addActionListener(new menuItemActionListener());
preferencesGroup.add(preferenceItems[i]);
preferenceMenu.add(preferenceItems[i]);
JMenuBar menuBar = new JMenuBar();
menuBar.add(fileMenu);
menuBar.add(preferenceMenu);
JFrame f = new JFrame("Prefernce Test");
f.setJMenuBar(menuBar);
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
public static void main(String[] args){
new PreferencesTest().createGui();
class menuItemActionListener implements ActionListener{
public void actionPerformed(ActionEvent e) {
JCheckBoxMenuItem jcbm = (JCheckBoxMenuItem)e.getSource();
prefs.put(PREF_OPTION, jcbm.getActionCommand()); -
Hi,
Is there a way of storing an array permanently, so that it stays saved somewhere in a file or something? I need to create an application that stores this array and reads the values from it, without having to re-create the array everytime I run the application.
Thanks for any help.Serialization is flakey (can have many problems when JDK or class is updated), wasteful of space, and IMO should be the implementation of last resort.
Here's a code snippet of what I would do:
public void saveArray(Object[] array, File f) throws IOException {
PrintWriter writer = new PrintWriter(new FileWriter(file));
for (int i = 0; i < array.length; i++)
writer.println(array.toString);
writer.close(); -
Storing an array into the database using jdbc
Hi,
i�ve got a problem storing an array into a database. I want to store objects consisting of several attributes. One of these attributes is an array containing several int values. I don�t know exactly what is the best way to store these objects into a database. I have created two tables connected by a one to many relationship of which one stores the array values and the other table stores the object containing the array. Is that ok or should I use another way. It�s the first time I�m trying to store objects containing arrays into a database so I�m very uncertain in which way this should be done.
Thanks in advance for any tips1. You should use blob or longvarbianry type colum to stor that array.
2. All object in that array should be Serializable.
3. Constuct a PreparedStatement object
4. Convert array to byte[] object
ByteArrayOutputStream baos=null;
ObjectOutputStream objectOutputStream=null;
baos = new ByteArrayOutputStream(bufferSize);
objectOutputStream = new ObjectOutputStream(baos);
objectOutputStream.writeObject(array);
objectOutputStream.flush();
baos.flush();
byte[] value=baos.toByteArray();
5. Now you can use PreparedStatement.setBytes function to insert byte[] value. -
Write an algorithm to sort an array of integers
"Write an algorithm to sort an array of integers"
I was asked this at an interview and required to do it in 5 mins. I don't think you can use sort them by putting them in a collection, i think you need to write an algorithm from scartch. Any idea what the best way to do this would have been?Depends what you mean by "best."
BubbleSort is probably the only one I could write off the top of my head in five minutes, but as sorting routines go for practical use, it sucks. If you know how to write MergeSort or QuickSort or dman near anything off off the top of your head, that would proabably be better.
No one sorting algorithm is "best" without any context, however.
If you don't know any sorting algorithms, use google or your data structures and algorithms textbook. -
Array of Integers please help?
pleace can someone help me? i am new in java . i want to create an array integers? Here i hava my codes that creates an array of strings? can anybody convert that so can accept integer and modified my method to add Integers instead of strings?Thanks for your time
public class Numbers implements Serializable {
* A constant: The maximum number of Random numbers
// static public int MAXSETS = 3;
static public final int MAXSETS = 3;
* The integer variable count will hold the number of states in the subset
private int count = 0;
* The array state will hold the States in the subset of states
private String number[] = new String[MAXSETS];
* Constructor method: Reserve space for the 50 Integers
public Numbers() {
for(int i=0;i < MAXSETS;i++) {
number = new String();
* addNumbers: adds a number to the collection of Numbers
* a string with the new number is passed as a parameter
public void addNumbers(String newNumber) {
number[count] = newNumber;
count++;
// System.out.println("scdsddfs"+ state);
* toString: Convert the object to a string
public String toString() {
// int num;
String str = count + " ";
for(int i=0;i < count;i++){
// num = Integer.parseInt(str);
str = number;
// str = str+" "+number;
// System.out.println("scdsddfs"+ str);
return str;pleace can someone help me? i am new in java . i want
to create an array integers? Here i hava my codes that
creates an array of strings? can anybody convert that
so can accept integer and modified my method to add
Integers instead of strings?Thanks for your time[snip]
You create an array of integers by saying
int[] myArrayOfIntegers[SIZE_I_WANT];To convert a String to an int, use the Integer.parseInt method.
Good luck
Lee -
How to add an array of integers to JList?
I know it should be easy, but I can't see a simple way to add an array of integers to a JList.
int[] per_ints = tempbean.getPercents();
//missing wrapper
JList list2 = new JList(per_ints);//wont work because JList will not take int[]what you should do is convert the int to string and then populate the list...
int[] per_ints = tempbean.getPercents();
Integer perI[] = new Integer[per_ints.length];
for (int z = 0; z< per_ints.length; z++){
perI[z] = new Integer(per_ints[z]);
JList list2 = new JList(Integer.toString(perI));
i think this should work...but if not try to convert tempbean.getPercent() to string and making that array a string array...basically store string in the list some how....probably not the best or simplest way..but i think it should work -
How to convert an array of Integers into String
So how can an array of integers be converted into a string?
As I do not have a javac with me now, I hope you guys could help.
Can it be done this way:
int [] value = new int[] {2,3,4,5,6,7}
String strValue = "";
for (i=0; i<value.length-1; i++)
strValue += value;Instead of working with Strings, I would suggest you use a StringBuffer. It will improve memory utilization.
Like this:
int [] values = new int[] {2,3,4,5,6,7};
StringBuffer sbTmp = new StringBuffer();
final int size = values.length;
for (i = 0; i < size; i++) {
String intStr = Integer.toString(values);
sbTmp.append(intStr);
String strValues = sbTmp.toString(); -
Creating colour image map from an array of integers
not really that relvant to swing, or in fact java even but i wasnt sure where to ask it so:
i have an array of integers that represents information about each pixel in an image. i.e. for every pixel there is an integer value.
at the moment i create another image from a quantised version of these integer values, which gives me a greyscale image, where black is low intensity info and white is high.
however what i want to do is create a colour image like you see, for example, on weather forecasts. where low intensity info is blue, then purple, then red, orange, yellow and then white being the highest.
i need some kind of algorithm that does this. does anybody have some code that does this already?
thanks
kevinsorry for not replying sooner sniper. thanks for your help but i have solved the problem:
thanks to my mate marc for the code.
import java.awt.Color;
/** Class to assist in assigning color to a mathematical value.
* Data values must be normalized.
* @author Marc Ramsdale
* Written 20th August 2003
public class ColorScale {
/** Receives a normalized value (between 0.0 - 1.0)
* The constructor then creates a colour according
* to the selected colour scale.
* If value is outside range 0.0 - 1.0 colour is java.awt.Color.BLACK
* @param double value - (between 0.0 - 1.0)
/** Maps the normalized value to a color
* BLUE *
* GREEN * *
* RED *
public static Color generateColour(double value) {
double red = 0.0;
double green = 0.0;
double blue = 0.0;
Color color;
int gradient = 4;
int offset1 = 2;
int offset2 = 4;
if((value >= 0.0) && (value < 0.25)) {
red = 0.0;
green = value * gradient;
blue = 1.0;
else if((value >= 0.25) && (value < 0.5)) {
red = 0.0;
green = 1.0;
blue = -(value * gradient) + offset1;
else if((value >= 0.5) && (value < 0.75)) {
red = (value * gradient) - offset1;
green = 1.0;
blue = 0.0;
else if((value >= 0.75) && (value <= 1.0)) {
red = 1.0;
green = -(value * gradient) + offset2;
blue = 0.0;
return new Color((float)(red), (float)(green), (float)(blue)); -
Java - Instance variable that can reference an array of integers?
Hello,
I have the following question in my assignment:
Your first task is to declare a private instance variable called cGroups that can
reference an array of integers. You should then write a constructor for GameN. This should
take a suitable array as its argument which should be used to initialise cGroups.
In order to test your code for declaring and initialising cGroups, you should execute
the following code
int[] coin = {2, 8, 5};
GameN aGame;
aGame = new GameN(coins);
and I have complete the code below but it's not working. maybe I'm reading it wrong or
not understandin something. Could someone correct it? or put me on the right lines
private int[] cGroups = new int[]
public GameN(int group1, int group2, int group3)
super();
this.cGroups = {group1, group2, group3};
}ShockUK wrote:
I've changed it to
private int[] coinGroups = new int[] {1};
public Nim(int group1, int group2, int group3)
super();
int[] coinGroups = {group1, group2, group3};
}But I still get the same error "Constructor error: Can't find constructor: Nim( [I ) in class: Nim"
Look at the line that error is pointing at. You're trying to use a constructor that doesn't exist. This is not a problem with creating an array. -
Functions to read and display an array of integers
Hi guys,
I am trying to implement with a class called Sort a function to read in an array of integers from a file and a function to display that array.
public class Sort
public static int[] read(String file) throws IOException
/* Create Reader object to read contents of file */
BufferedReader br = new BufferedReader(new FileReader(file));
/* Read file and store lines in ArrayList */
ArrayList<Integer> list = new ArrayList<Integer>();
/* Variable */
String in;
/* While not equal to null reads data from file */
while ((in = br.readLine()) != null)
/* Adds data from file to ArrayList */
list.add(Integer.parseInt(in));
/* Converts ArrayList into an array */
int[] array = new int[list.size()];
for(int i = 0; i < list.size(); i++)
/* Get array elements */
array[i] = list.get(i);
/* Returns array */
return array;
public int display()
for (int i = 0; i < list.size(); i++)
System.out.println(list.get(i));
}I am having one of those moments when you forget everything, I need help with display the array in a seperate function, will someone help me please?
Thanks!I know that its just implementing it.
I have:
public void display()
for(int i = 0; i < array.length; i++)
System.out.println(array);
But I'm lost on how to make this work, i.e it says "cannot find array variable". I've not done Java for a while and feel like I have forgot everything!
Edited by: mbruce10 on Nov 15, 2009 1:31 AM -
Getting Largest Int From an Array of Integers
public class TestMe
public TestMe(int ai[])
_numbers = ai;
public int getBiggest1()
int i = _numbers[0];
for(int j = 1; j < _numbers.length; j++)
if(_numbers[j] >= _numbers[j - 1] && i < _numbers[j])
i = _numbers[j];
return i;
public int getBiggest2()
double d = Math.random();
int i = _numbers[0];
for(int j = 1; j < _numbers.length; j++)
if(d >= 0.10000000000000001D && i < _numbers[j])
i = _numbers[j];
return i;
private TestMe()
private int _numbers[];
}can anyone see what is wrong with either of the two methods as regards returning the largest integer from an array of integers.
As far as I can see they work no matter what ints are in the array.
Any ideas anyone ?
Regards
SeanI used the following client program to use ur class:
I also modified ur class a bit and made the other constructor (the one with no arguments) as public to extend the class.
Both the functions, viz, getBiggest1() and getBiggest2() are working fine...
Now, I am new to JAVA so I might have made mistakes. Please correct me if there is anything wrong.
/*Here is ur class that i have modified*/
public class GetBiggest {
public GetBiggest(int ai[]) {
_numbers = ai;
public int getBiggest1() {
int i = _numbers[0];
for(int j = 1; j < _numbers.length; j++)
if(_numbers[j] >= _numbers[j - 1] && i < _numbers[j])
i = _numbers[j];
return i;
public int getBiggest2() {
double d = Math.random();
int i = _numbers[0];
for(int j = 1; j < _numbers.length; j++)
if(d >= 0.10000000000000001D && i < _numbers[j])
i = _numbers[j];
return i;
public GetBiggest() {
private int _numbers[];
/*Ur class ends here*/
/*My client program starts here*/
import java.lang.*;
public class TestBiggest extends GetBiggest
public static void main (String args[])
int[] arrNums = {30, 20, 40, 10};
GetBiggest GB = new GetBiggest(arrNums);
int greatest = 0;
try
greatest = GB.getBiggest2();
System.out.println("\nBiggest number is : " + greatest);
}//end try block
catch(Exception e)
System.out.println("Some error");
}//end catch block
}//end main
}//end class
/*End of my client program*/ -
Best way of saving an array of integers to use later?
I am having trouble figuring out where to initialize an array of integers so it is available everywhere. It's just a simple array of integers to be used as indices into another array. So I figured an ordinary C array like this is sufficient:
int arrayOfIndices[] = {3, 11, 12, 25, 26, 43, 50, 53, 58, 59, 62, 76, 77, 81, 94, 95, 110, 113, 114, 117, 118, 123, 136, 152};
It's ok to just use an ordinary C array for this, right? It seems that it is much harder to initialize a similar NSArray of integers. Or is there an easy way to do that?
One problem I'm having is I'm having trouble figure out where to stick the above array so that it is usable through the program. With my NSArray objects I've been defining them in the interface, then initializing them in viewDidLoad with retain.
Is there something analogous I can do with ordinary C int arrays? Or, alternatively, an easy way to initialize an NSArray of integers so I can deal with them like I do with other NSArrays?
Thanks,
dougNever mind. It looks like just not putting anything in the interface file and sticking the definition of the C int array at the top of my implementation file where I import files and define some other stuff works fine.
doug
Maybe you are looking for
-
Recuperar a passwor do iphone 3g
alguem me ajuda com o meu iphone... deois de uns meses sem o usar esqueci me da minha password do telefone e depois de ligar a itunes nao encontro o enderesso certo para encontar a mesma utilisando a itunes. obrigado pela ajuda...
-
How can I prevent forms from being prematurely submitted when users click on the "Enter" key?
Is there any way that I can prevent Dreamweaver CF submission forms from being prematurely submitted by the user when he/she clicks on the "Enter" key before they have completed the form? I need the users to finish form and click on the "Submit" key
-
PLD Error in Cash Payment Voucher
Dear Experts, I am trying to create a PLD for Cash Payment Voucher. In Outgoing Payment screen, when the account option is selected and in "Payment Means" window, when the option "Cash" is used, and while trying to generate print preview, system
-
WLC 2504 - French characters for guest web login page
Good day, I have recently installed a WLC 2504 and I have the following issue: When I modify the text for the web login page (Under security/Web Auth/Web Auth page), if I use french caracters such as (é, è, à, etc...) in the message body, it does not
-
Sage Pay Bug list / ETA on mending them
Hi can someone at BC give me an Estimated Completion date on this list of sage pay bugs. For other forum users I thought maybe you might want to add your Sage pay bug list here too so we can have one overall bug list of sage pay issues and hopefully