Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
First off apologies if this is a simple question, but I am very stuck with it.
I need to create an array with a total number of elements, there is 14. I want to add each of the 14 elements to the array and was recommended doing this with a loop as I will be doing more tasks like this but with much more elements. I have tried this code so far but am having no luck;
int [] deviceID;
for(int i = 292; i <= 305; i++)
{
deviceID[i];
}
but I get the exception insert "AssignmentOperator Expression" to complete Expression.
So then I changed the line to
deviceID = deviceID[i];
Now I get a Type Mismatch: cannot convert from int to int[]
just to be clear I want slot 0 of the array have the value 292, slot 1 have 293........slot 14 have 305
Can anyone help me on this? What I thought would be basic and easy is turning into a bit of a nightmare for me.
You need to initialize array int[] deviceId = new int[20];
I guess you want to add 292 to 305 in array.
int [] deviceID= new int[14];//total element 14 (index 0 to 13)
int j=0;//counter which provides index during loop
for(int i = 292; i <= 305; i++)
{
if(j<deviceID.length)//chech whether j<14 as we want to add upto index 13
deviceID[j++]=i;//store i to the array at index j
//increments j to provide next index
}
I suggest you to read about Arrays from Java Doc it will clear all your dobts and bring some extra energy in you to start coding again.
I don't understand what you want to do, but if you want to have values from 292 to 305 in an array you should do:
int [] deviceID = new int[305];
for(int i = 292; i <= 305; i++)
{
deviceID[i] = i;
}
But it's really weird. What is your purpose ?
If you're trying to fill your integer array deviceID with those values of i, you'll need to first make sure the array is big enough, and then simply fill the array. Your problem was from trying to set your entire array equal to a single integer from one index (hence the type mismatch error).
int[] deviceID = new int[necessarySize]; // Creates an array with size "necessarySize"
int counter = 0;
for(int i = 292; i <= 305; i++)
{
deviceID[counter] = i; // Fills the array at index "counter" with value "i"
counter++;
}
If this is your entire array, then you'd only need (305-292)+1 = 14 spaces in your array.
DO THIS
int[] deviceId = new int[14]; //this creates a new array with size 14
int j=0; // for array index
for(int i = 292; i <= 305; i++)
{
deviceID[j] = i; //this inserts value of i at array position j
j++; //this keeps on adding 1 to previous value
}
You need to instantiate the array.
int[] deviceId = new int[sizeOfArray];
Where sizeOfarray, is an integer value indicating the size of the array.
Then to assign the position, you must use
deviceId[index] = value;
deviceID[i] just gets the i'th element in deviceID and does nothing with it.
deviceID = deviceID[i] is trying to assign an int to an object declared as a list, hence your error.
What you want to do is:
List<int> deviceID = new List<int>()
for(int i = 292; i <= 305; i++)
{
deviceID.add(i);
}
This should give you a list with only the numbers 292-305 in it
Related
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
I have been coding a basic method to take an array of strings, find the largest length and return a string array containing on values that are equal to the highest length of the array. I keep getting a null pointer exception and i am not sure why. The code is:
String[] allLongestStrings(String[] inputArray) {
int compare = 0;
int k = 0;
String[] use = new String[20];
for (int i = 0; i < inputArray.length; i++) {
if (inputArray[i].length() > compare)
compare = inputArray[i].length();
}
for (int j = 0; j < 20; j++) {
if (inputArray[j].length() - compare == 0) {
use[k] = inputArray[j];
k++;
}
}
return use;
}
for (int j = 0; j < 20; j++) {
if (inputArray[j].length() - compare == 0) {
use[k] = inputArray[j];
k++;
}
}
This will only work if inputArray has at least 20 elements. In the code above, you're doing the correct thing: for (int i = 0; i < inputArray.length; i++). I think you just need to change this second for statement to be the lesser of 20 or the length of inputArray.
inputArray doesn't contain 20 elements. Don't just throw out and hard code a length value for your the array you're going to return. Actually determine what the true length is going to be because you could be too low on that value and if your not then you could end up with a bunch of null elements.
If allowed use an ArrayList or String List object which doesn't require a preset length (size) instead of a 1D String Array which does require length initialization: List<String> list = new ArrayList<>();. You can simply just add to it with the List.add() method.
If you must use a Single Dimensional Array then use another for loop to determine how many string elements actually have the same length as what is held within the compare integer variable. Always iterate through the original array (inputArray). This for loop would be very much like your second for loop except you would increment a integer counter variable upon all elemental lengths that equal the value held within the compare variable.
Eliminate the formula in your if statement condition contained within your second for loop. I think (IMHO): if (inputArray[i].length() == compare) {...} should be sufficient, it's much easier on the eyes. ;)
Just a thought for pizazz....perhaps add the actual Array index to the string that is added to the 1D String array named used. Use a delimiter of some sort to separate the two.
This question already has answers here:
How to find the index of an element in an array in Java?
(15 answers)
Closed 6 years ago.
In the below code I can get the length and element of array. if I have to check what is the index number at run time for every element, how can I check that?
If I print the value of i from loop every time with the array element it will give the same value, will that be correct to consider the value of i as index value of array?
Another confusion in during the debug in eclipse it shows id value of array is different than the loop value.
public class FirstArray {
public static void main(String[] args) {
int[] arr = {11,12,13,14,15,16,17,18,19,20};
int onelength = arr.length;
System.out.println("Size of Array is: " + onelength);
for(int i = 0; i < arr.length; i++){
System.out.println("element of aray is: "+ arr[i]);
}
}
}
Yes, value of i will be the index value. I would suggest you to go through basics of Java arrays.
The question itself is not clear. The loop bounds are definitely different from the index value of the array. If you want to print the loop bounds along with the value at the index, just print i in the loop.
For your question "what is the index number at run time for every element, how can i check that?" Refer to the solution bellow:
Where is Java's Array indexOf?
For your question "If i print the value of i from loop every time with the array element it will give the same value, will that be correct to consider the value of i as index value of array?"
The array index starts from 0, so if your array length is 10 then index values will be 0 to 9. Thus, if you start your loop from i=0 then the index value will be same as i, but if you start your loop from i=1 then the index value will be i-1.
Will that be correct to consider the value of i as index value of
array?
Of course it'll be correct, i is actually the index of the array.
Another confusion in during the debug in eclipse it shows id value of
array is different than the loop value
Yes, it shows because it's really different, take a look:
for(int i = 0; i < arr.length; i++) {
System.out.println("element of aray is "+ arr[i]); // It prints the element itself -> 11 12 13 14 15.. and so on
System.out.println("iteration number "+ i); // It prints the index of iteration -> 0 1 2 3 4 5.. and so on
}
You may want to clarify what exactly you are searching for.
An array stores a value at a given index (starting at index zero, and going up to index length-of-the-array-minus-one).
The traditional way of creating an array is the following:
// Create an empty array that is able to hold 3 values
int[] numbers = new int[3];
numbers[0] = 11;
numbers[1] = 15;
numbers[2] = 13;
If we now print the values in the index order, we receive 11, 15 and 13. Here's the code:
for (int i = 0; i < numbers.length; i++) {
System.out.println(numbers[i]);
}
So, we see with numbers[i] = 14 we can assign the value 14 to the index i of the array. And with System.out.println(numbers[i]), we can print the value the array has stored at index i.
An array has a fixed length which needs to be specified at creation, it is not a flexible data structure (but pretty fast and small). Thus, if you are trying to access numbers[100] but we said numbers can only hold 3 values, then you will get an ArrayIndexOutOfBoundsException.
Your provided code is a short-hand for the traditional way:
int[] arr = {11,12,13};
which does the same as
int[] arr = new int[3];
arr[0] = 11;
arr[1] = 12;
arr[2] = 13;
If you want to search for the index, given the value (assuming the values are unique), you need to search the whole array until you find the index. Here's some code:
public int getIndex(final int[] array, final int value) {
for (int i = 0; i < array.length; i++) {
if (array[i] == value) {
// Value found
return i;
}
}
// Value not found
return -1;
}
Note that the search code is pretty slow, because you may need to search the whole length of the array (worst case). Other data structures may be more useful depending on your usage.
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
I couldn't find a solution for this in Java. I need to write code that will take an integer n, and an array of integers that has numbers up to n(some may be missing), and the method will print out which numbers are missing
ex: {2; 3; 5; 1; 2; 3} should print out 4, 6
Edit: Here is what I got from the comments suggestion, but it doesn't seem to work. What did I do wrong?
public static void findMissingNum(int n, int[]a) {
boolean A[] = new boolean[n];
for(int i = 0; i < a.length; i++) {
A[a[i]] = true;
}
for(int j = 0; j < A.length; j++) {
if (A[j] = false) {System.out.print(A[j]);}
}
}
I've seen this used as a homework or quiz problem before, the question is begging you to use a hash table. Create an empty Boolean array of size n and for each number in the list set array[num] to True. Loop over the new array, and record all the instances of False, you know ahead of time how many there should be.
The following ought to work:
public void find() {
Scanner s = new Scanner(System.in);
int[] nums = {2, 3, 5, 1, 2, 3};
int n = s.nextInt();
boolean[] included = new boolean[n+1];
for(int i = 0; i < nums.length; i++) included[nums[i]] = true;
for(int z = 0; z < included.length; z++) {
if(included[z] == false) System.out.print(z+ ",");
}
}
This will print out all missing numbers including n (if it is missing). If n is not included then do new boolean[n]
The way it works is by first using Scanner to read in your int n. It has two arrays, an int array which has your numbers, and a boolean array which serves as a set of flags. The boolean array is initalized to the size of n. Then it loops through the nums array and sees what numbers are included in the array. If the number is included, its element in the boolean arary is flagged as true. Finally, it loops through the flags/boolean array, if the element at that flag is true, do nothing since its already there, otherwise if its false (meaning the # wasn't included) then print it.
Try to implement this solution in Java:
Create second array A = [0,..,n] of booleans. Initialize it with false values.
Iterate through input array: for i = 0 to length(inputArray): A[inputArray[i]] := true.
Check which indexes in array have value false, those are the values that You want to return.
List< Integer > list = Arrays.asList(yourArray);
Then you can just create an array from 1 up to n with all numbers in order, and iterate through its elements checking for each one if your list contains it or not, adding it to another missingValues list if not.
I'm having difficulty understand how to write this array. I need it to out-print 10x5 (50 elements total), and have the first 25 elements equal to the sqrt of the index that it is in, and the last 25 to equal 3 * the index. Yes, this is homework but I'm not asking for you to do it for me, I just need help! I'm getting errors when using Math saying that I cant use double and the double array together. Here is what I have so far:
public class snhu4 {
public static void main(String args[]) {
double alpha[][] = new double[10][5];
double[] sum, sum2;
for (int count=0; count<=25;count++) {
alpha[count]= Math.sqrt(count);
}
for (int count=26; count<=50;count++) {
alpha[count]= count *3;
}
for (int count=0; count<=50;count++) {
System.out.print(alpha[count]);
}
}
}
Because alpha is a multidimensional array, you can't refer to its elements like a normal array.
int myarray[][] = new int[2][2];
In the above example, the array myarray is multidimensional. If I wanted to access the second element in the first array, I would access it like this:
int myint = myarray[0][1];
You are trying to access a multidimensional array by using the access for a normal array. Change
alpha[count]
to
alpha[0][count]
or similar.
Read here for more information on multidimensional arrays.
you defined alpha as a 2D array with lets say 10 items in the first dimension and 5 in the second, and 5x10 is 50 elements.
When using your array to assign values to these elements, u must call upon the array using 2 indices, one for each dimension:
alpha[i][j] = /*double value*/; //with 0<=i<=9 and 0<=j<=4
So the first 25 elements going from left to right in dimension order is going to be:
[0to9][0] and [0to9][1] and [0to4][2]
the next 25 will be
[4to9][2] and [0to9][3] and [0to9][4]
from then on i cannot give you the answers to your homework, but the loops should look like this:
int j;
for(int i = 0; i<25; i++)
{
j=i/10; //integer division will return 0 for i<10, 1 for 10<i<20, etc..
alpha[i%10][j] = Math.sqrt(i);
}
and you can figure out the rest
The 10x5 appears to be an output constraint, not a design constraint.
You are using Java, so use Java constructs, not C-language constructs;
specifically store the values in a List not an array.
Here are some hints:
List<Integer> valuesList = new ArrayList<Integer>();
for (int index = 0; index < 25; ++index)
Integer currentValue = Math.sqrt(index);
valuesList.add(currentValue);
for (int index = 25; index < 50; ++index)
Integer currentValue = index * 3;
valuesList.add(currentValue)
int count = 1;
for (Integer current : valuesList)
if ((count % 5) == 0) // write a newline.
System.out.print(current);
++count
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
public class mdar {
public void cont(){
Random rand = new Random();
int con = 100;
int multi[][]=new int [con][6];
for(int x = 0;x<multi.length;x++){
for(int y = 0;y<multi[x].length;y++){
int temp = rand.nextInt(9);
multi[x][y] = multi[x+1][temp]; //this line is going bad
}
}
for(int i=0;i<multi.length;i++){
System.out.print("contester "+multi[i]);
for(int j=0;j<multi[i].length;j++){
System.out.println(" has "+multi[i][j]+" ");
}
System.out.println();
}
}
}
I deleted my old project and so i was trying to remake it and i can't figure it out anymore :S
Could someone help me out here?
The second dimention of multi is 6;
int multi[][]=new int [con][6];
However you call anything up to 8 on that second dimention
int temp = rand.nextInt(9);
multi[x][y] = multi[x+1][temp]; //temp could be between 0 and 8 from the random function
As such you get an array index out of bounds, in your case temp was 7.
Addtionally your loop goes between 0 and multi[x].length-1
for(int y = 0;y<multi[x].length;y++){
But you call multi[x+1] which will at the end of the loop be one larger that the largest index of multi, but you'll hit this exception after the other one (99% of the time)
multi[x][y] = multi[x+1][temp];
I think you meant to write
multi[x][y] = temp;
//This would set multi[x][y] to a random int in the range [0,8] (inclusive)
instead of
multi[x][y] = multi[x+1][temp]; //this line is going bad
//This will assign the int value at multi[x+1][temp] to the variable multi[x][y]
There are 2 things wrong with this:
1) x is a for loop counter in range [0,multi.length) [inclusive, exclusive)
for(int x = 0;x<multi.length;x++)
x+1 is outside the bounds of the array
2) temp is a random int in range [0,8] [inclusive, inclusive]
int temp = rand.nextInt(9);
however the multi array is defined with a 2nd dimension size of 6 (valid locations multi[x][0] through multi[x][5])
int multi[][]=new int [con][6];
The random variable temp will be outside of the valid range 3/9 times (for 6, 7, 8), therefore you will encounter this error 33% of the time that nextInt(9) is called. Since it is called many times in a single call to cont() you will almost never have an execution that runs without error, however, it is still logically incorrect code whether it executes with or without error.
without an idea of what the code is supposed to do, it hard for us to give a solution. The error is quite clear. See in the last iteration of your outer loop x = multi.length - 1. So when you ask for multi[x+1][temp] you are asking for multi[multi.length] which is out of bounds since multi goes from [0 to multi.length-1].
In addition to that int temp = rand.nextInt(9) will also cause an out of bounds exception if it returns values 6,7 or 8, since the second dimension of multi must be in the range [0 to 5]
Again without an idea of what needs to be done, I can't know if the solution i propose below does what you want to do:
for(int x = 0;x<multi.length - 1;x++){
for(int y = 0;y<multi[x].length;y++){
int temp = rand.nextInt(multi[x+1].length);
multi[x][y] = multi[x+1][temp];
}
}
When your
int temp = rand.nextInt(9);
gives value as "7". You are getting this error. Debug and find.
You geting out of the length of the array, try to do this:
if(x+1 < multi.length)
{
multi[x][y] = multi[x+1][temp];
}
multi[x][y] = multi[x+1][temp];
at the end of loop x+1 making it.
You are declaring your 2D array with second dimension 6:
int multi[][]=new int [con][6];
Valid index of second dimension will be in range 0..5.
But then you access it with random number like 7 which is out of bounds:
int temp = rand.nextInt(9);
multi[x][y] = multi[x+1][temp]; //this line is going bad
int temp = rand.nextInt(9);
System.out.println(temp);
multi[x][y] = multi[x+1][temp];
here when temp goes beyond 5 it will give you exception as you have multi[][]=new int [con][6];
change the line int temp = rand.nextInt(5);
also you have another issue multi[x+1], when you have x=99 that time it will try to make 100 which is causing the issue, remember array index starts with 0