I am currently learning JAVA using Aleks Rudenko book, and as a newbie in JAVA I still cannot figure out simple compilation errors. I tried to create a simple code that takes an array X and multiply every single term of it by Y. Finally, the array*Y should be printed out as follows:
public class CurrencyConverter {
double[] answers = new double[] {};
public double[] Times2 (double[] x, double y) {
for (int i=1; i<x.length+1;i++) {
answers.add(x[i]*y);
}
return answers;
}
public static void main(String[] args) {
CurrencyConverter cc = new CurrencyConverter();
double [] rates= new double[] {63,3.0,3.0,595.5,18.0,107.0,2.0,0.0};
System.out.println(cc.Times2(rates,2));
}
}
the error message is
error: cannot find symbol
answers.add(x[i]*y);
^
symbol: method add(double)
location: variable answers of type double[]
1 error
I cannot figure out what is the reason for this compilation error. Thanks for the help !
add is not defined for arrays. If you want to add elements, use List.
There are several ways to fix your code:
a) use List:
import java.util.*;
List<Double> list = new ArrayList<Double>();
public List<Double> Times2 (double[] x, double y) {
for (int i=0; i<x.length;i++) {
list.add(x[i]*y);
}
return list;
}
b) Don't add elements, just write them into array:
double[] answers;
public double[] Times2 (double[] x, double y) {
answers = new double[x.length];
for (int i=0; i<x.length;i++) {
answers[i] = x[i]*y;
}
return answers;
}
..Also, watch out for the array index out of bounds. First element has index 0 and last item has index length - 1.
And one last thing, you will probably encounter problem with printing your results.
If you want to use list, use System.out.println(cc.Times2(...).toString()); and if you want to use array, use System.out.println(Arrays.toString(cc.Times2(...)));
Better to use a while loop, instead of a for loop, for this use case. And use a Vector:
Vector<Object> answers = new Vector<Object>();
You are using . dot operator on an array. answers is an array and its values can be accessed like answers[0] -> first element or answers[9] -> gives 9th element. Had answers been an object with say a variable called status, then you would access status from answers as answers.status
Similar if answers have method say bestAnswer() then you would access it as answers.bestAnswer()
And if you want to hold a bunch of objects of your custom type Answer in an array then you would instantiate each Answer object first and add it to the array answers array as:
Answer firstAnswer = Answer();
Answer secondAnswer = Answer();
...
answers[0] = firstAnswer;
answers[1] = secondAnswer;
...
Arrays in java don't have any methods. You access stuff by index. Your code should look
public static class CurrencyConverter {
public double[] Times2(double[] x, double y) {
double[] answers = new double[x.length];
for (int i=0; i < x.length; i++) {
answers[i] = x[i] * y;
}
return answers;
}
}
Notice that the for loop starts with i as 0. the first index of an array is always 0, not 1. the answers array is init'ed inside the method as it's best to keep variables hidden (scoped) from things that don't need them. it's also init'ed with the size it needs to be.
Some of the other answers here say to use stuff based on java.util.AbstractCollection. While you could but there's no good reason for extra overhead for something simple like this.
Related
So I've been trying to code static, methods in my class to practice what I've learned.My understanding of generic types and ArrayLists are still null Which is why I ask here since troubleshooting has been horrendous (I'm currently reading Java Core 9th edition first book down to chapter 6).
The method is supposed to take in any number of double arrays (wich creates a multidimensional array), and check each individual one to see if they either contain less or more than three double elements, Then do things with those arrays etc... If an array contains less than two double elements, show an error and exit. If there's more than 3, create an Arraylist of that array and delete any element that are exceeding.
My issue comes when I try to create an ArrayList of the array "d" in the for each loop of my multidimensional array "DDs". I took every suggestion from this question but none worked, I've tried a few other suggestions from other websites but again none functioned. Here is a snippet of my code.
public static final void Calcs(double[]... DDs)
{
for(double[] d : DDs)
{
if(d.length < 3)
{
System.out.println("Variable Error 1 :: Array Distributed exceeds 3 types");
System.exit(0);
}else if(d.length > 3)
{
ArrayList<Double> tmp = new ArrayList<>(Arrays.asList(d));
//Type mismatch: cannot convert from ArrayList<double[]> to ArrayList<Double>
}
}
}
My Hypothesis is that the array d is encased in by another array. but I am not sure and rather ask someone who does:
What I think x should look like:
d = [x]
what I think it might look like:
d = [[x]]
Any troubleshooting ideas? I am very new to generic types and that error doesn't tell me much. Thanks a lot for the feedback.
You have two options here. You can either treat your 2D array (because varargs is practically an array) as a List of double[], or a List of List<Double>
The first way would be
List<double[]> list = new ArrayList<>(Arrays.asList(DDs)); //Arrays.asList() returns a fixed size list so we'll put it into a flexible list
The second way would be
List<List<Double>> list = new ArrayList<>();
for (double[] doubles : DDs) {
List<Double> listDoubles = new ArrayList<>(); //Cannot use Arrays.asList() because that will return List<double[]> with a single element
for (double innerDouble : doubles) {
listDoubles.add(innerDouble);
}
list.add(listDoubles);
}
This compiles, but I am not certain if it is what you seek:
public static final void Calcs ( double[]... DDs ) {
for ( double[] d : DDs ) {
if ( d.length < 3 ) {
System.out.println("Less than 3");
System.exit(0);
}
ArrayList<double[]> tmp = new ArrayList<>(Arrays.asList(d));
}
}
Maybe this, then:
public static final void Calcs ( double[]... DDs ) {
for (double[] d : DDs ) {
if (d.length < 3) {
System.out.println("Less than 3");
System.exit(0);
}
ArrayList<Double> tmp = new ArrayList<>(d.length);
for ( double od : d ) tmp.add(od);
}
}
This question already has answers here:
What's the simplest way to print a Java array?
(37 answers)
Closed 8 years ago.
What I am trying to do is add an array to an arraylist. I've looked at other examples that tell me to do what I am doing, but I get nonsense output when I run the program. I would also like to access certain elements of an array within the arraylist, and I have no idea how to do that.
static int elements = 10; //Or whatever number you'd like
public static void main(String[] args)
{
int[] person = new int[4];
ArrayList personID = new ArrayList();
experiment(personID, person);
}
private static void experiment(ArrayList personID, int[] person)
{
for(int i = 0; i < elements; i++)
{
person[0] = i;
person[1] = i;
person[2] = i;
person[3] = i;
personID.add(person);
}
System.out.print(personID);
}
Output:
[[I#e1cba87, [I#e1cba87, [I#e1cba87, [I#e1cba87, [I#e1cba87, [I#e1cba87, [I#e1cba87, [I#e1cba87, [I#e1cba87, [I#e1cba87]
Not that much of an explanation is needed, but I declare the array and arraylist, pass them to a function which keeps giving the array's elements different values and then, supposedly, adding the array itself to the arraylist for each iteration.
The output, though, it nothing like what I am looking for. I could do another loop to print each array element for each spot along the array list, but I don't know how to do that. I figured
System.out.print(personID.get(i[0]);
Or
System.out.print(personID.get(i)[0];
But it doesn't work and I'm lost...
Thank you for dealing with me!
It's just a problem with the way you're printing the arrays. Try this instead:
for (int[] a : personID)
System.out.println(Arrays.toString(a));
Not only are you attempting to print arrays by implicitly invoking toString, but also adding the same array over and over to the list. The variable called person is a reference to an array object. You keep changing its elements and adding the same reference.
Were your print routine to be correct, the output would only show an array of four 10s repeated 10 times.
Arrays doesn't implement its own toString() implementation it uses Object#toString() and that is why you are watching that output
getClass().getName() + '#' + Integer.toHexString(hashCode())
[I means that is an Integer array plus # followed with it's hashcode e1cba87.
One way to solve it is using Arrays.toString()
For example:
public static void main(String[] args){
int[] person = new int[4];
List<int[]> personID = new ArrayList<>();
experiment(personID, person);
//now print
for(int[] array : personID){
System.out.println(Arrays.toString(array));
}
}
public static void main(String[] args) {
LinkedList test = new LinkedList();
int[] numberPair;
numberPair = new int[2];
numberPair[0] = 1; numberPair[1] = 2;
test.add(numberPair);
}
How would I go about accessing the array in the first node of this list and printing it? I've tried all kinds of casting with test.getFirst(), but either it prints out the memory address or I get a long list of casting errors for objects.
Try using Arrays.toString().
See the javadoc for details.
Edit:
As other answers have pointed out, you should also use generics with your List. You should declare it as a LinkedList<int[]>. And then as you iterate over the elements, use Arrays.toString to convert each element into a string and print the result.
If using java 1.5+ use java generics like so:
LinkedList<int[]> test = new LinkedList<int[]>();
int[] top = test.getFirst();
for (int i: top){
System.out.print(i+" ");
}
System.out.println();
You should use a generic type instead of a raw type.
LinkedList<int[]> test = new LinkedList<int[]>();
When do test.getFirst(), you are getting an int array back, so just iterate through it.
int[] bla = test.getFirst();
for ( int i : bla )
System.out.println(i);
Or use
Arrays.toString(test.getFirst());
I have an arraylist where I want to add elements via a for loop.
Answer answer1;
Answer answer2;
Answer answer3;
ArrayList<Answer> answers = new ArrayList(3);
for (int i=0; i<3; i++)
{
answers.add( /* HOWTO: Add each of the answers? */ );
}
How would this go if I have, let's say, 50 Answer elements?
You can't do it the way you're trying to... But you can perhaps do something like this:
List<Answer> answers = new ArrayList<Answer>();
for(int i=0; i < 4; i++){
Answer temp = new Answer();
// Do whatever initialization you need here
answers.add(temp);
}
That can't be done with a for-loop, unless you use the Reflection API. However, you can use Arrays.asList instead to accomplish the same:
List<Answer> answers = Arrays.asList(answer1, answer2, answer3);
I assume Answer as an Integer data type, so in this case you can easily use Scanner class for adding the multiple elements (say, 50).
private static final Scanner obj = new Scanner(System.in);
private static ArrayList<Integer> arrayList = new ArrayList<Integer>(50);
public static void main(String...S) {
for (int i=0; i<50; i++) {
/* Using Scanner class object to take input. */
arrayList.add(obj.nextInt());
}
/* You can also check the elements of your ArrayList. */
for (int i=0; i<50; i++) {
/* Using get function for fetching the value present at index 'i'. */
System.out.print(arrayList.get(i) + " ");
}
}
This is a simple and easy method for adding multiple values in an ArrayList using a for loop.
As in the above code, I presume the Answer as Integer. It could be String, Double, Long, etc. So, in that case, you can use next(), nextDouble(), and nextLong(), respectively.
If you simply need a list, you could use:
List<Answer> answers = Arrays.asList(answer1, answer2, answer3);
If you specifically require an ArrayList, you could use:
ArrayList<Answer> answers = new ArrayList(Arrays.asList(answer1, answer2, answer3));
There's always some reflection hacks that you can adapt. Here is some example, but using a collection would be the solution to your problem (the integers you stick on your variables name is a good hint telling us you should use a collection!).
public class TheClass {
private int theField= 42;
public static void main(String[] args) throws Exception {
TheClass c= new TheClass();
System.out.println(c.getClass().getDeclaredField("theField").get(c));
}
}
You do not need a for loop for this. The solution is very obvious:
answers.add(answer1);
answers.add(answer2);
answers.add(answer3);
That's it. No for loop needed.
Another option is to put the answers into an array and iterate over it:
List<Answer> answers = new ArrayList<Answer>(3);
for (Answer answer : new Answer[] {answer1, answer2, answer3}) {
list.add(answer);
}
But see João's answer for a much better solution.
Thomas's solution is good enough for this matter.
If you want to use a loop to access these three Answers, you first need to put there three into an array-like data structure ---- kind of like a principle. So a loop is used for operating on an array-like data structure, not just simply to simplify the typing task. And you cannot use a for loop by simply just giving increasing-number-names to the elements.
Using the Random function to generate numbers and iterating them on al using a for loop:
ArrayList<Integer> al = new ArrayList<Integer>(5);
for (int i=0; i<=4; i++){
Random rand = new Random();
al.add(i, rand.nextInt(100));
System.out.println(al);
}
System.out.println(al.size());
In PHP, you can dynamically add elements to arrays by the following:
$x = new Array();
$x[] = 1;
$x[] = 2;
After this, $x would be an array like this: {1,2}.
Is there a way to do something similar in Java?
Look at java.util.LinkedList or java.util.ArrayList
List<Integer> x = new ArrayList<Integer>();
x.add(1);
x.add(2);
Arrays in Java have a fixed size, so you can't "add something at the end" as you could do in PHP.
A bit similar to the PHP behaviour is this:
int[] addElement(int[] org, int added) {
int[] result = Arrays.copyOf(org, org.length +1);
result[org.length] = added;
return result;
}
Then you can write:
x = new int[0];
x = addElement(x, 1);
x = addElement(x, 2);
System.out.println(Arrays.toString(x));
But this scheme is horribly inefficient for larger arrays, as it makes a copy of the whole array each time. (And it is in fact not completely equivalent to PHP, since your old arrays stays the same).
The PHP arrays are in fact quite the same as a Java HashMap with an added "max key", so it would know which key to use next, and a strange iteration order (and a strange equivalence relation between Integer keys and some Strings). But for simple indexed collections, better use a List in Java, like the other answerers proposed.
If you want to avoid using List because of the overhead of wrapping every int in an Integer, consider using reimplementations of collections for primitive types, which use arrays internally, but will not do a copy on every change, only when the internal array is full (just like ArrayList). (One quickly googled example is this IntList class.)
Guava contains methods creating such wrappers in Ints.asList, Longs.asList, etc.
Apache Commons has an ArrayUtils implementation to add an element at the end of the new array:
/** Copies the given array and adds the given element at the end of the new array. */
public static <T> T[] add(T[] array, T element)
I have seen this question very often in the web and in my opinion, many people with high reputation did not answer these questions properly. So I would like to express my own answer here.
First we should consider there is a difference between array and arraylist.
The question asks for adding an element to an array, and not ArrayList
The answer is quite simple. It can be done in 3 steps.
Convert array to an arraylist
Add element to the arrayList
Convert back the new arrayList to the array
Here is the simple picture of it
And finally here is the code:
Step 1:
public List<String> convertArrayToList(String[] array){
List<String> stringList = new ArrayList<String>(Arrays.asList(array));
return stringList;
}
Step 2:
public List<String> addToList(String element,List<String> list){
list.add(element);
return list;
}
Step 3:
public String[] convertListToArray(List<String> list){
String[] ins = (String[])list.toArray(new String[list.size()]);
return ins;
}
Step 4
public String[] addNewItemToArray(String element,String [] array){
List<String> list = convertArrayToList(array);
list= addToList(element,list);
return convertListToArray(list);
}
You can use an ArrayList and then use the toArray() method. But depending on what you are doing, you might not even need an array at all. Look into seeing if Lists are more what you want.
See: Java List Tutorial
You probably want to use an ArrayList for this -- for a dynamically sized array like structure.
You can dynamically add elements to an array using Collection Frameworks in JAVA. collection Framework doesn't work on primitive data types.
This Collection framework will be available in "java.util.*" package
For example if you use ArrayList,
Create an object to it and then add number of elements (any type like String, Integer ...etc)
ArrayList a = new ArrayList();
a.add("suman");
a.add(new Integer(3));
a.add("gurram");
Now you were added 3 elements to an array.
if you want to remove any of added elements
a.remove("suman");
again if you want to add any element
a.add("Gurram");
So the array size is incresing / decreasing dynamically..
Use an ArrayList or juggle to arrays to auto increment the array size.
keep a count of where you are in the primitive array
class recordStuff extends Thread
{
double[] aListOfDoubles;
int i = 0;
void run()
{
double newData;
newData = getNewData(); // gets data from somewhere
aListofDoubles[i] = newData; // adds it to the primitive array of doubles
i++ // increments the counter for the next pass
System.out.println("mode: " + doStuff());
}
void doStuff()
{
// Calculate the mode of the double[] array
for (int i = 0; i < aListOfDoubles.length; i++)
{
int count = 0;
for (int j = 0; j < aListOfDoubles.length; j++)
{
if (a[j] == a[i]) count++;
}
if (count > maxCount)
{
maxCount = count;
maxValue = aListOfDoubles[i];
}
}
return maxValue;
}
}
This is a simple way to add to an array in java. I used a second array to store my original array, and then added one more element to it. After that I passed that array back to the original one.
int [] test = {12,22,33};
int [] test2= new int[test.length+1];
int m=5;int mz=0;
for ( int test3: test)
{
test2[mz]=test3; mz++;
}
test2[mz++]=m;
test=test2;
for ( int test3: test)
{
System.out.println(test3);
}
In Java size of array is fixed , but you can add elements dynamically to a fixed sized array using its index and for loop. Please find example below.
package simplejava;
import java.util.Arrays;
/**
*
* #author sashant
*/
public class SimpleJava {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
try{
String[] transactions;
transactions = new String[10];
for(int i = 0; i < transactions.length; i++){
transactions[i] = "transaction - "+Integer.toString(i);
}
System.out.println(Arrays.toString(transactions));
}catch(Exception exc){
System.out.println(exc.getMessage());
System.out.println(Arrays.toString(exc.getStackTrace()));
}
}
}