1. Array coderanch.comWelcome to Java Ranch, "S!" This is clearly a homework problem, but I'll bite, anyway. Here's a nice, straightforward algorithm: Use any implementation of the java.util.Map interface. Create Integer objects to be both the keys and the values. The keys would be the numbers in the array, the values would be the counts. To add a number to the map, you ... |
|
You could write a merge method ( or I can ): public Object[] merge( Object obj1, Object obj2 ) { //create an array large enough to hold both arrays Object[] merged = new Object[obj1.length + obj2.length]; //index to add to the new array int merge_index; //add all the elements of obj1 to the new array for( merge_index = 0; merge_index < ... |
The soul is dyed the color of its thoughts. Think only on those things that are in line with your principles and can bear the light of day. The content of your character is your choice. Day by day, what you do is who you become. Your integrity is your destiny - it is the light that guides your way. - ... |
5. Array coderanch.comFirst I get the data from database and define an object,put the data into three dimention Resultset rs = stmt.executeQuery(); Object a[][][] = new Object[x][y][z]; while(!rs.next()) { i = rs.getObject("id").intvalue(); a[i][j][0] = 123; a[i][j][1] = 234; a[i][j][2] = 456; j++; } x will put the kind value y is the record number z is the field now I put j to ... |
Hello world, I am hoping to write a stock controlling program. In that, I have a function to print a bill. Which the user can add items to the bill with the quantyties... I am doing this in 'SWING' and I am using the JTable class to show the bill. Means that it has columns such as 'items code', qty, price ... |
Hi, I'm posting this here because I'm obviously a beginner. If it belongs elsewhere, please let me know. TIA Now, I have a program that is comming along nicely, kudos to you folks here... but the following code causes me some problems. Com1 is a text field, & I want to set it to th i-th element of an array (Comment1), ... |
|
|
Hello. I am trying to fill this entire array with new data objects using "for" loops adn then set the value of each objects variable i in the array by calling each objects setl() method. I am a little confused and lost about trying to add these modifications. Could anyone offer any suggestions or ideas. Again, I am new to Java ... |
What do you mean by three different elements? Three different kinds of objects? You can use an Object array to hold any kind of objects, like Object[] myArray = { "A string", Color.RED, new Point(1, 2) }; But if you're going to count on a certain object being in a certain position (and I know that's what you're going to do!) ... |
I have a question about arrays. I'm learning about 2 dimensional arrays ( array[][] ). If I declare an array such as int number[][] = { { 1, 2 }, { 3 }, { 4, 5, 6, } }; does this implicitly create a 3 X 3 array? There would be three rows, of course. One row has one column, one ... |
|
I'm writting this program that searches a data file for cars that match the users preferences. I'm having a problem with the line I marked with **, I keep getting a java error that says " cannot resolve symbol" and I don't understand why? anybody have any suggestions, Thanks CarDataList carDataList=new CarDataList(); int listSize=carDataList.getListSize(); //Start of the loop for (int i=0; ... |
public class reverse { public static void main(String[] args) { int[] m = {0,1,2,3,4,5,6,7,8,9}; System.out.println("the real order is "); printR(m); reverseR(m); System.out.println("the reverse order is "); printR(m); } static void printR(int[] list) { for(int i=9;i=0;i--){ list[i] = i; } } } |
Hi ranchers ! Is such thing as array of interface supported in Java ? I understand that I can create array of Object and then cast each element to my interface. I understand also that in incoming java 1.5 will be generics. (that not only make the language more complex, but (prabably) can help in the case) I understand also about ... |
|
Jaysingh, When you create a primitive array you can only populate it with those primitives. In your case, you can only place integers into the array (not another array). The first line is valid because the compiler is converting the line for you to make it valid: int[][] i={{1,2,3},new int[]{3,4,5},{333},{},{6,7,8}}; is actually the same as: int[][] i = { {1,2,3}, {3,4,5}, ... |
|
Can someone explain the answer to this problem, master exam says that answer C below "is wrong because C tries to assign a two-dimensional array where a one-dimensional array is expected." I can see that b is a two-dimensional array, but it looks like b2 is four-dimensional array. So I would expect the answer to say "C is wrong because C ... |
|
In reading some books on Java Array declaring then writting small files to try and compile I did found that if I declare an Array reference outside of a method, then try to create the array using the array ref = new array_type[size], the program will not compile, but if I do the same inside a method it works Example (file ... |
I have a quick question. My main method listed below will not pass my array values into my constructor WordCounter. Is is due to the instantiation of t1 in my for loop? I know the array is being filled correctly with the strings because I can test it with a SOP, and it outputs correctly. Im just wondering why this doesn't ... |
Hey Yall, I'm back again. I just can't seem to get this method to work. I really can't figure out a way to decrease the capacity of myArray. I am supposed to change the capacity of this vector to capacity. If the new capacity is smaller than the current size, remove items from the end of this vector until the size ... |
|
Larry / Lost One, Note that the naming policy prohibits obviously fictitious names. The names of well-known fictitious characters definitely fall into this category. Please try again! Also, please don't post questions to more than one forum -- duplicates just waster people's time. I've deleted the other copy of this message. Now, finally, on to your question: The way we like ... |
I am trying to input an integer thru JOptionPane and have that number become the size of a one dimensional table. The MyDriver main calls the method class MyArray. i am getting a compile error on my System.out.println because "counter" is unresolved. Any idea why or what i am doing wrong and whether the scheme will work otherwise? ??? thanx djb ... |
i fear i may not be learning this or maybe you just need to repeat your mistakes a number of times. ANY SUGGESTIONS? compiler errors are: MyArray.java [39:1] unreachable statement System.out.println(sumVal); ^ MyArray.java [35:1] missing return statement { ^ 2 errors Errors compiling MyArray. //START main import javax.swing.JOptionPane; import java.text.*; public class MyDriver { public static void main (String[ ] arg) ... |
You can declare and instantiate in one line outside of a method, so // allowed int bok[] =new int[12]; but you can not instantiate on a separate line like you are trying // not allowed int bok[]; bok[]=new int[12] The compiler was looking for an identifier to start the second line and that's responsible for one of the compilation errors. You ... |
Yes I certainly agree with Mark, but you obviously need to know how to do this. here is a little sample, also you need to make sure that your array will handle the new element, or else you will get an exception. To ensure this from happening you need to increase your array.lenght to array.length*2. public void addElement(int n) { for(int ... |
Is there any way of returning an array? I have created an array that holds a series of numbers. However, i need to use this in another method which basically gets the matrix and returns it so that it can be retrieved by another class. Can this be done? I know that to an array can be passed to another method ... |
31. Array coderanch.comHi Look at the API document. Arrays (Java 2 Platform SE v1.4.2) I have two questions. 1. Why "arrycopy" function is defined in the System class instead of Array class. 2. Look at the "All classes" list in the API document. I do see entry for class - Array - Array (in italic) - Arrays My questions is, what is that ... |
well hello all and thanks for taking me in. i have a litlle stupid array prob. i have a class called ArrayReverse with an array like "char charArray[]" and an instance of it called ArrRev. i am trying to do this: "ArrRev.charArray[2]={a,b};" and i keep gettin the message "illegal start of expression" pointing at the "{". what is that? can anyone ... |
I'd try something like this: 1. String.split() to split at the '+' character. Store each string separately (duh :-) ) 2. Use String.split() again, but this time split at the characters '(', ',' ' ' (space) and ')'. This should give you a String array of the individual numbers. You will (I think) get an empty array if there were no ... |
Hi - I've got a 2-dimensional array with 10 rows and 10 columns. I need to be able to check what the value of each of the array element's neighbours are - that is the eight elements that are one column and or row removed - and if they are a specific value, a counter gets incremented. Now, I can loop ... |
35. Arrays coderanch.comThis code shows three ways to create an array of integers. public class B { public static void main(String[] args) { int[] numbersA = { 1, 2, 3 }; int[] numbersB = new int[] { 4, 5, 6 }; int[] numbersC = new int[3]; numbersC[0] = 7; numbersC[1] = 8; numbersC[2] = 9; show(numbersA); show(numbersB); show(numbersC); } static void show(int[] nums) ... |
First point: you need to have Acc be an object that you have already defined in a class named Acc.java. You might have done this OK, but I don't have that information here. Next point: you must have a value given to i before you can use it to define the size of your array you named "bank". You might have ... |
To avoid the details of protected and (default), I'll just say you can access the array directly from another object if the array is public. You can not access it directly if it is private. If your array was marked as private, you can still provide access to it through what is called an accessor method which might look something like ... |
Hi everyone! I need to create two methods numbersInRange and nearestToTarget. The first method numbersInRange, which I have completed, just returns an integer giving the number of elements in the array whose value is greater than the parameter 60 and less than the parameter 80. The second method is supposed to return the value of the integer in array closest to ... |
I don't know how should i debug the error (Cannot reslove symbols) regarding my arrayList.. Pls help me, and point out if i have did something wrongly.. public boolean findapp(Object date, Object Month, Object Year) { FindDay f; AppList al = new AppList(); <----- error try { AppList = al.getAppointments(); <----- error } catch(IOException ex){ <----- error } for (int i=0; ... |
I have an assignment where I should write an abstract class which will be the base to calculate some points of a competition. The points will be assigned different depending on weather the person is a boy,girl,man or woman. I have 2 boys, 3 women,2 girls and 2 men. I just type the number of item each one collected, but I ... |
hi, i need some help creating a phonebook (array). ok, heres the code wat i got so far; Phonebook class public class PhoneBook { private int arraySize; private Contact[] array; public PhoneBook(int maxArraySize) { array = new Contact[maxArraySize]; arraySize =0; } public void addAContact(String name, int number) { Contact theContact = new Contact (name, number); array[arraySize] = theContact; arraySize++; } private ... |
hi all, what i'm trying to do here is to let the user create an array depending on the number he/she inputs, then add new records to it. for eg: 1st time user creates 2 accounts, then user adds 1 more account so total number of accounts will become 3. System.out.println("How many accounts do you want to create?"); i = cs.readInt(); ... |
new String[] {"Tube","Bus","Railway","Bicycle"} creates a new array object. It's a String array with four components - the strings "Tube", "Bus", "Railway", and "Bicycle". That square bracket part, [new Random.nextInt(4)], is concerned with referencing a component in the array, at a randomly selected index. (If the use of a Random object is unfamiliar territory, perhaps you'd appreciate a look at the Random ... |
|
45. Arrays coderanch.comHello, I am having a problem with arrays. I want to put five varables in array [0]. Can this be done. //Array String buyCarArray [] = new String [10]; for (int x = 0; x < buyCarArray.length; x++) buyCarArray [0] = manufacturerIn, modelIn, regNumberIn, engineSizeIn, mileageIn milesPerGallonIn; System.out.println("\nManufacturer: " + manufacturerIn[0]+ "\n"); System.out.println("\nModel: " + modelIn[0]+ "\n"); System.out.println("\nRegistration No.: " + ... |
I'd like to help but I don't understand your question. You have only declared one array here, so there isn't another one to "jump" to. Can you give more details about what you are trying to do? It looks like you have some other variables that I assume are declared before this snippet. If you are just trying to print out ... |
|
Ok I have an array full of 10 objects. This array is called carArray.. Now I wish to add a new object to the array but am having trouble. I started off thinking that I should create a tempoary array one index bigger then the current array, copy the information from the first array to the second array and then create ... |
i am writing a method that returns an array full of students names. The students names are given in a file, so my method called ReadFile, reads the file and adds each line(name) to the array i'm not sure my code is correct, plus i'm not familiar with writing methods that return and array. If someone could comment on this code, ... |
I'm working my way though the sun.java.com trails and have a question that is just not making sense to me. I should know this, but alas I do not. In the first loop how is the array being read? (see full source below) for (int i = arrayOfInts.length; --i >= 0; ) { ... I mean is it being read starting ... |
|
ok, i'm trying to put some items into an array based on the outcome of an if statement. I keep getting an error that says i haven't initialized my array properly or something. I'm not sure how to initialize an array if you don't want to put values in straight away, but a bit later on. Anyway, the code is public ... |
Ok so, i have this code where i have 1 button linked to a method to calculate something(the method is in another class) and it returns an array with what it was supposed to calculate. then i have another method which needs to display all of it.. the thing i need help with is getting the thing it returned from 1 ... |
Hello all, The following code is compiling successfully. public class arraryTest { public static void main(String[] args) { short[][] b = new short[4][4]; short[][][][] b2 = new short[2][3][2][2]; b2[1][1] = b; } } My assumption is, any element b[x][y], where x is in (0,1) and y is in (0,1,2), should be a two dimensional array of size 2x2. But short array ... |
You can empty an array by running through it with a for loop and by assigning each place in the array to null or whatever your definitaion of empty is. If it is an array of arrays then you need to run two for loops, one to loop through the outer array and one to loop through the inner arrays. Try ... |
56. array coderanch.comhi 1. i have public static final int BOX = 0; public static final int CIRCLE = 1; if i want to put the elements into an array do the array have to be public static final or it can be private and then i just write set and get methods to access and update array 2. is it how I ... |
|
Ok, Say I have the following: public static int[] makeArray(int n) and when I call this method from main I want an array to print out from 1 to n. Makes since? I really am new to this stuff so a lot of detail would be appreciated, not just the answer thanks |
|
|
|
I am trying to understand how to create this array... Actually I am trying to understand why an array should be used? Would my first array be something like; int [ ] coins = { 1, 5, 10, 25 }; ? Thanks, -Giles ---- Use an array to store the four values corresponding to coin types. Also, use an array to ... |
Hi gang, I'm currently building a cribbage game and am running into a weird issue with 2 arrays getting mysteriously set to null. First some code, then an explanation: snippet from GUI class: public void actionPerformed(ActionEvent e) { if (e.getSource() == dealButton) { gameFlow gFlow = new gameFlow(m_theGame); } if (e.getSource() == discardButton) { m_theGame.getFlow().discard(); } } from gameFlow class: public ... |
I have an assignment that requires me to create an array of three objects Each Object has five varreables I am supposed to ask the user to input the varreables and check them for right type and range. Then I am supposed to output the data back to the screen naming it object1 with its five varreables object 2 with its ... |
Hi Miki, I see no problems there. You can definately declare an array as final and static both. If you are having a problem somewhere in a program, I guess it might be because you are either declaring the array inside a static context, or may be you are trying to change the reference of this array . I am writing ... |
66. Arrays coderanch.comHi, I am a beginer in java.In the below clode class Array1 is compilng whereas class Array2 is not compiling. in Array1 class i have declared and initialised the array inside the method foo whereas in the class Array2 i have initialised the array in the class itself. public class Array1 { public void foo(){ int[] j; j = new int[10]; ... |
Consider class test { int i = 0; } versus class test { int i; i = 0; } The first compiles just fine, whereas in the second example the compiler complains "identifier required". The reason is the following: classes have state and behavior. The state is given in the instance variables, which may be instantiated at once (1st example), and ... |
68. arrays coderanch.comI'm trying to write a program that takes an integer number as input argument and returns the number of digits in that number. This is what I came up w/ so far. In my main program I ask them to enter some integers. And now i want to get the size of the integers they enter in so i can assign ... |
|
I have a class called main program. Another two called Student and Storage. In my main program I am getting the name of the student the course they are enrolled on. //This is in a for loop studentDetails [lp] =new Student (name, course); //This is the end of the for loop. I then want to do other things with the student ... |
|
public void calcVehicle (Vehicle types) //The input into this method is coming from another program //it has been tested ok Vehicle [ ] types= new Vehicle [numberOfVehicles]; for (int i=0; i<(numberOfVehicles); { System.out.println ("The Vehicle type is: "+types); }//end for loop }//end method calcVehicle I have also tried for (int i=0; i<(numberOfVehicles); { Vehicle type = types[i]; //and then printing out ... |
I want to take an array i.e. A[] and array B[] and add them together. for instance if array A contains "abcd" and array B contains "efgh" i want to add them together and print out "abcdefgh". Can you use arraycopy? I am at a lost for the logic to do so. |
74. Arrays coderanch.comHi, Jugal - Sun has a free downloadable extensive Java tutorial, which includes discussions of arrays. Here's a quickie overview: Think of a two dimensional array as a set of boxes. For example, if you have an array that is 3x2, you would have three big boxes each holding two little boxes, and each little box stores data of whatever type ... |
|
76. Arrays coderanch.comI've been working on this problem all evening and any help would be appreciated. I have a 5 element array (of type integer). I need to find the element of the array that holds the maximum value and keep the original corresponding index of that element. The Arrays.sort won't work on this one becuase the index changes for the element with ... |
I have a simple array that allows the user to enter in integer values, then prints the values of each index of the array. Is it possible to restrict each index to a different integer. In other words if the user enters in the same integer more than once it only gets stored once. Is this possible? array[0] = 4 array[1] ... |
do you mean this (which you can do): public class A { protected int[] array; } public class B extends A { public void doSomething() { array = new int[] { 1,2,3 }; } } or this (which you cannot): public class A { protected C[] array; public A() { array = new C[] { new C("E"), new C("F") }; } ... |
Escape sequences are handled by the Java compiler, and therefore they must appear in the Java source code. The compiler will see, for example, a '\' followed by a 'n', and replace them both with a single newline character. If the characters '\' and 'n' are read at runtime from a file or from the command line, they're just two separate ... |
|
Hello, I have a few class exercises to do for practice to help me learn arrays.. Have no idea how to start and complete this one.. Some help would be appreciated, thanks! OBJECTIVE: Given an intvariable k , an intarray incompletes that has been declared and initialized, an intvariable studentID that has been initialized, and an intvariable numberOfIncompletes , write code ... |
public class Database { // instance variables - replace the example below with your own private ArrayList exits; /** * Constructor contruct a emtpy database with default 10 slots * for exits of class Database. */ public Database() { // initialise instance variables exits = new ArrayList(); } /** * All exits available in the game */ public void addExits(GameEngine theExits) ... |
Hi, This is the piece of code.I am getting Null pointer exception when I return cf.When I tried to print the length of cf ,the value returned was 30 where as there are not so many elements stored.Please help.. public File[] f1= new File[30]; public File[] cf=new File[30]; int count=0; for(int j=0;j |
Ok i have a program that takes 4 orchards over a 5 year span. I need to get the average of each orchard. Which I have..now i need to get the Total of the 4 orchards for each of the 5 years..then the average for each year which I'm having a real trouble doing. int arraySize, salesNum; double amount; BufferedReader keyboard ... |
Hey There! Maybe this code can help you out a little, may not be the way you want to do it though. I am a beginner at java, but this is how I would do it. Just make a Boolean Array the size of sixty and make it all false, once a number is generated it becomes true I put the ... |
I have the following code: package module6; class ErrorInfo { String msgs[] = { "Output Error", "Input Error", "Disk Error", "Index Out-Of-Bounds" }; int howBad[] = new int[3]; for(int i = 0; i < howBad.length; i++) howBad[i] = i * 2; Err getErrorInfo(int i) { if(i >= 0 & i < msgs.length) return new Err(msgs[i], howBad[i]); else return new Err("Invalid Error ... |
Hi, I have created a class ShoppingCart that constructs a new arry from a class called Item. The Item array consists of 10 elements. Each Item element holds an Item object that contains the instance variables private String name; private double price; private int quantity; private int barcode; When the array is first created the first index of the array becomes ... |
The array reference on the left hand side of the assignment is evaluated first, to arr[5]. After this evaluation, i is incremented to 6. Then the right hand is evaluated. First i is incremented to 7. This value is remembered, and then the "i++" is evaluated, giving 7. This second 7 is remembered, and then then i is incremented again, and ... |
89. Arrays coderanch.comHi Guys...It's been a while, but I surely need some help.. I'm trying to write this program that has arrays in it, where I can input a employee's hours in, and then show the results on the screen... Here's a sample of what I have so far... public void setHours( ) //This is just a stub. Stub...not done yet. { { ... |
with enum being a java keyword as of java 1.5, you should avoid using it as an variable identifier. other than that, you're almost there. an array has a length property, so: for( int i = 0; i < array.length; ++i (or i++, makes no difference here) ) will iterate through an array named array. Also, java arrays are zero based. ... |
I find your question a little bit ambigous... If you want to find the Sum of two number (lets say A and B) you simply write: A + B If you want to find the Mean for 9 grades (in your example) you write: (grade[0] + grade[1] + ... + grade[8]) / grade.length; It won't get any simpler than that!!! |
|
Hi, could someone explain to me how a synchronised array works, or point me to a page that explains them well. I have been given some code for a order processing system and I am very stuck on my current task to do on it, we are on a break at the moment, but I want to get this done. I ... |
Hi! I have a problem whit Array(int [ ]v={5,2,7,3,5 ,6,9,5,6} :wink: My program prints out three numbers: Index nbr 05 45 75 The program is ok, but I try to print out: 1-just second 5 not first and last. 2-just the first and second 5. 3-just the second and last 5. class MyProgram { int [ ]v={5,2,7,3,5 ,6,9,5,6}; public int find(int ... |
Hello all, Nice community you have here. I've got a question about something that has been keeping me busy for a day or too. I'm a beginner at java, and i'm not really good at explaining stuff with their names, because i dont know them, so please excuse me, and correct me if i'm wrong My problem is: My main class(which ... |
Hey there! I am having a problem in one of my programs and i cant seem to get ir right. I have an array, that holds an object. I go through this array with a for loop checking if any of the slots in the array are null, if a spot is null return true, if the entire array is full, ... |
I realize this is a theoretical question, but there are some problems with the code snippet. As in it won't compile or work as expected. 1. The int i in the for loop needs to be initialized. 2. someArray.length should be used rather than someArray[].length. 3. the loop test should be < rather than greater than since it's using "i++" and ... |
In your test class you are creating a new Storage object each time through the loop. Create your storage object outside of the loop, and use the generic constructor. Then when you call the addStudent method pass not only the name but also the index of the array (you'll have to change the method signature to accept an int) insert the ... |
I have a question about arrays. I have an array that I want to reverse the order on and then make into another. I can read the first array forwards and backwards no problem but for some reason when I go to put it into another array it doesn't work. The second array is still empty. I've got to be doing ... |
Hi, I have been trying to get a definition for a subscript array. What type of array it is. Its a requirement for a class assignment I have, but the professor has not supplied us (the students) with documentation on this subject. Could someone educate me or point me to a reference? |