Iterator and regular for loop - java

I understand how iteration work but may be I need more knowledge about it. Can any one please show me the main difference between these two statements:
while (scanner.hasNext()) {
tokenizer = new StringTokenizer(scanner.nextLine());
numberOfItems = Integer.parseInt(tokenizer.nextToken());
int[] numbers = new int[numberOfItems];
for (int i:numbers) {
numbers[i] = Integer.parseInt(tokenizer.nextToken());
}
System.out.println(isJolly(numbers));
}
while (scanner.hasNext()) {
tokenizer = new StringTokenizer(scanner.nextLine());
numberOfItems = Integer.parseInt(tokenizer.nextToken());
int[] numbers = new int[numberOfItems];
for (int i = 0; i < numberOfItems; i++) {
numbers[i] = Integer.parseInt(tokenizer.nextToken());
}
System.out.println(isJolly(numbers));
}
why these giving me 2 different output?

You have created empty array (array filled with zeroes).
int[] numbers = new int[numberOfItems];
In case of
for ( int i = 0; i < numbers.length; i++ ) ...
i starts from 0 and on each iteration it is incremented (i++). Iterations are finished when i became equals or more than numbers.length (aka numberOfItems). So sequence of i values is 0,1,2,3,4,5,...
In case of
for (int i:numbers) {
You iterate on each value taken from array and you will get sequence of zeroes ( 0,0,0,0,0, ...).
And yours number[i] = will update only the number[0] element of resulting array.

Related

I don't know how assign new value to the empty array

I am a beginner in coding. I have to write a code that will divide array with random numbers into two different arrays. One array will contain odd numbers, the other one even numbers. But something is wrong, and i don't really know what to do.
According to the console the problem is in the place where there is a lot of exclamation marks. when i change those lines to System.out.println("x") it works perfectly fine.
public void P_N () {
int I_E = 0; // amount of even numbers
int I_O = 0; // amount of odd numbers
for (int i = 0; i < tab2.length; i++) { // tab2 is a array with random numbers
if (tab2[i] % 2 == 0)
I_E = I_E + 1;
else
I_O = I_O+1;
}
int [] tab_E = new int[I_E]; // array with even numbers
int [] tab_O = new int [I_O]; // array with odd numbers
for (int i = 0; i < tab2.length; i++){
if (tab2[i] % 2 == 0){
tab_E[i] = tab2[i]; //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
}
}
for (int i = 0; i < tab2.length; i++){
if (tab2[i] % 2 != 0){
tab_O[i] = tab2[i]; //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
}
}
for (int i = 0; i< tab_E.length; i++) {
System.out.println("Even array: " + tab_E[i]);
System.out.println("------------------------------------------------");
}
for (int i = 0; i< tab_O.length; i++) {
System.out.println("Odd array: " + tab_O[i]);
}
}
Problem is in going out of bounds for arrays tab_E and tab_O, when variable i is more tab_E.length. Just create another variable, for example "j". And iterate throug your array using it. Like I'v written below
int j = 0;
for (int i = 0; i < tab2.length; i++) {
if (tab2[i] % 2 == 0) {
tab_E[j++] = tab2[i];
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!
}
}
j = 0;
for (int i = 0; i < tab2.length; i++) {
if (tab2[i] % 2 != 0) {
tab_O[j++] = tab2[i];
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
}
}
I would rather use 2 ArrayLists one for even numbers and another one is for odd numbers and later convert it into array using toArray() method.
public void P_N(){
ArrayList<Integer> evenNumberList = new ArrayList<Integer>();
ArrayList<Integer> oddNumberList = new ArrayList<Integer>();
for (int i = 0; i < tab2.length; i++) { // tab2 is a array with random numbers
if (tab2[i] % 2 == 0) {
evenNumberList.add(tab2[i]);
} else {
oddNumberList.add(tab2[i]);
}
}
int[] evenNumberArray = evenNumberList.toArray();
int[] oddNumberArray = oddNumberList.toArray();
}
This will take some extra space but makes your application more efficient, I hope this helps.
You have initialized the even/odd number arrays with a quantity of the even/odd numbers accordingly:
int [] tab_E = new int[I_E]; // array with even numbers
int [] tab_O = new int [I_O]; // array with odd numbers
Ii is reasonable to assume that the sizes of even or odd number arrays are might be much smaller than the size of the original source array.
But in this even number filtering loop (as well as in the odd filtering loop) you use source array index values to address target array positions, end eventually face the ArrayIndexOutOfBoundsException.
for (int i = 0; i < tab2.length; i++)
{
if (tab2[i] % 2 == 0)
{
tab_E[i] = tab2[i]; //here the same i value is used to address non existing index in tab_E array
}
}
A quick fix might be the following:
int tab_E_index = 0;
for (int i = 0; i < tab2.length; i++){
if (tab2[i] % 2 == 0){
tab_E[tab_E_index] = tab2[i]; //i value gets incremented every loop iteration
tab_E_index++; //tab_E_index value get incremented only when even number is added to the tab_E array
}
}
Please don't just copy/paste it, but try to understand what caused the issue on the first place. Good luck and happy coding.

Creating a multi-dimensional String array from a method array parameter

I am attempting to solve a semi-difficult problem in which I am attempting to create an array and return a 3 dimensional array based on the parameter which happens to be a 2 dimensional int array. The array I'm attempting to return is a String array of 3 dimensions. So here is the code:
public class Displaydata {
static String[][][] makeArray(int[][] dimensions) {
String myArray[][][];
for (int i = 0; i < dimensions.length; i++) {
for (int j = 0; j < dimensions[i].length; j++) {
myArray[][][] = new String[i][j][]; //getting error here.
}
}
return myArray;
}
static void printArray(String[][][] a) {
for (int i = 0; i < a.length; i++) {
System.out.println("\nrow_" + i);
for (int j = 0; j < a[i].length; j++) {
System.out.print( "\t");
for (int k = 0; k < a[i][j].length; k++)
System.out.print(a[i][j][k] + " ");
System.out.println();
}
}
}
public static void main(String[] args) {
int [][] dim = new int[5][];
dim[0] = new int[2];
dim[1] = new int[4];
dim[2] = new int[1];
dim[3] = new int[7];
dim[4] = new int[13];
dim[0][0] = 4;
dim[0][1] = 8;
dim[1][0] = 5;
dim[1][1] = 6;
dim[1][2] = 2;
dim[1][3] = 7;
dim[2][0] = 11;
for (int i = 0; i < dim[3].length;i++)
dim[3][i] = 2*i+1;
for (int i = 0; i < dim[4].length;i++)
dim[4][i] = 26- 2*i;
String[][][] threeDee = makeArray(dim);
printArray(threeDee);
}
}
As you can see from the source code, I'm getting an error when I try to create an instance of my 3-dimensional array which I'm attempting to return. I'm supposed to create a three dimensional array with the number of top-level rows determined by the length of dimensions and, for each top-level row i, the number of second-level rows is determined by the length of dimensions[i]. The number of columns in second-level row j of top-level row i is determined by the value of dimensions[i][j]. The value of each array element is the concatenation of its top-level row index with its second-level row index with its column index, where indices are represented by letters : ‘A’ for 0, ‘B’ for 1 etc. (Of course, this will only be true if the indices don’t exceed 25.) I don't necessarily know where I'm going wrong. Thanks!
You should not be initializing the array on every iteration of the loop. Initialize it once outside the loop and then populate it inside the loop.
static String[][][] makeArray(int[][] dimensions) {
String[][][] myArray = new String[25][25][1];
for (int i = 0; i < dimensions.length; i++) {
for (int j = 0; j < dimensions[i].length; j++) {
myArray[i][j][0] = i + "," + j;
}
}
return myArray;
}
I just plugged in values for the size of the first two dimensions, you will need to calculate them based on what you put in there. The 'i' value will always be dimensions.length but the 'j' value will be the largest value returned from dimensions[0].length -> dimensions[n-1].length where 'n' is the number of elements in the second dimension.
Also you will need to set up a way to convert the numbers in 'i' and 'j' to letters, maybe use a Map.
I guess you should initialize the array as
myArray = new String[i][j][]; //getting error here.
I think
myArray[][][] = new String[i][j][]; //getting error here.
should be:
myArray[i][j] = new String[5]; // I have no idea how big you want to go.
And then you can fill in each element of you inner-most array like such:
myArray[i][j][0] = "first item";
myArray[i][j][1] = "second string";
...
I think you should just change that line to:
myArray = new String[i][j][]; //look ma! no compiler error
Also, you would need to initialize myArray to something sensible (perhaps null?)

How do I fill an array with consecutive numbers

I would like to fill an array using consecutive integers. I have created an array that contains as much indexes as the user enters:
Scanner in = new Scanner(System.in);
int numOfValues = in.nextInt();
int [] array = new int[numOfValues];
How do i fill this array with consecutive numbers starting from 1?
All help is appreciated!!!
Since Java 8
// v end, exclusive
int[] array = IntStream.range(1, numOfValues + 1).toArray();
// ^ start, inclusive
The range is in increments of 1. The javadoc is here.
Or use rangeClosed
// v end, inclusive
int[] array = IntStream.rangeClosed(1, numOfValues).toArray();
// ^ start, inclusive
The simple way is:
int[] array = new int[NumOfValues];
for(int k = 0; k < array.length; k++)
array[k] = k + 1;
for(int i=0; i<array.length; i++)
{
array[i] = i+1;
}
You now have an empty array
So you need to iterate over each position (0 to size-1) placing the next number into the array.
for(int x=0; x<NumOfValues; x++){ // this will iterate over each position
array[x] = x+1; // this will put each integer value into the array starting with 1
}
One more thing. If I want to do the same with reverse:
int[] array = new int[5];
for(int i = 5; i>0;i--) {
array[i-1]= i;
}
System.out.println(Arrays.toString(array));
}
I got the normal order again..
Scanner in = new Scanner(System.in);
int numOfValues = in.nextInt();
int[] array = new int[numOfValues];
int add = 0;
for (int i = 0; i < array.length; i++) {
array[i] = 1 + add;
add++;
System.out.println(array[i]);
}

Array of counter in Processing

I have to pass two arrays
1) that are filled with 1000 int's between 0-100
2) that contains ten bins to sort the 1000 numbers.
How do I create the counter to sort numbers into ten bins such as 0-9, 10-19, 20-29, 30-39, 40-49,50-59 and so on to 90-99...
Would it be with an if/else that sorts them? If so, how do I add values into each bin? Would it be something like this?
This is what I have so far:
//initialize array of 1000 elements
int[] numbers = new int[1000];
int i = 0;
//initialize array of 10 bins
int[] bins = new int[10];
void setup() {
// Populate array with random number
for (int i = 0; i < numbers.length; i++) {
numbers[i] = ceil(random(0,99));
}
}
//function that sorts random numbers into bins
void counter(int[] numbers, int[] bins) {
}
If you want every number from numbers in the right bin then I would use an array of 10 ArrayLists as the datastructure for your bins.
int[] numbers = new int[1000];
ArrayList[] bins = new ArrayList[10];
void setup() {
for(int i = 0; i<bins.length; i++) {
bins[i] = new ArrayList();
}
for (int i = 0; i < numbers.length; i++) {
numbers[i] = floor(random(0,100));
}
}
void counter(int[] numbers, ArrayList[] bins) {
for (int i = 0; i < numbers.length; i++) {
bins[floor(float(numbers[i])/10.0)].add(numbers[i]);
}
}
You then get a bin with (for example the first bin consisting of numbers with values 0-9):
int sizeBin = bins[0].size();
for(int i=0; i<sizeBin; i++) {
println(bins[0].get(i));
}
If you want the count of numbers in a bin you can get it with (again an example with the bin 0-9)
bins[0].size();
the simplest way a can think of is to use a for loop to cycle through the numbers[] and then a series of if statements to evaluate whether the number is <= 9 , <= 19 etc
void counter(int[] numbers, int[] bins){
int count = 0;
int length = numbers.length;
for(int i = 0; i< length; i++){
if(numbers[i] <= 9){
bins[count] = numbers[i];
count++;
}
//and the same for 10-19 etc...
}
something like this maybe? not very eloquent but since the array is only 1000 elements it should suffice

How do I take null spaces out of an array?

I have to make a program that takes duplicate characters from an input array and prints out a new array with all unique characters.
It all works. Except when characters are taken out, it leaves an empty box at the end of that new array.
public class Deleter {
public static void main (String[] args){
Scanner keyboard = new Scanner(System.in);
char[] initialInputArray = new char[15];
System.out.println("How many characters do you wish to enter?");
int size = keyboard.nextInt();
while ( size > initialInputArray.length ) {
System.out.println("Error. Enter smaller number.");
size = keyboard.nextInt();
}
if( initialInputArray.length <= 15) {
for ( int counter = 0; counter < size; counter++ ){
initialInputArray[counter] = keyboard.next().charAt(0);
}
{
}
}
deleteRepeats(initialInputArray, size);
//Comeback to print out array
{
for ( int helloWorld = 0 ; helloWorld < size ; helloWorld ++)
System.out.print( initialInputArray[helloWorld] );
}
}
//"deleteReapets" method begins, looking for repeated user inputs
public static char[] deleteRepeats (char[] methodArray, int sizeTwo) {
if (sizeTwo == 0)
return methodArray;
if (sizeTwo == 1)
return methodArray;
int uniqueCharacter = 1;
//Start at the second entered character.
for (int x = 1; x < sizeTwo; ++x) {
int y;
for (y = 0; y < uniqueCharacter; ++y) {
if (methodArray[x] == methodArray[y]) break; // break if we find duplicate.
}
if (y == uniqueCharacter) {
methodArray[uniqueCharacter] = methodArray[x]; // add
++uniqueCharacter; // increment uniqueCharacter...[0,uniqueCharacter) is still "unique char list"
}
}
while ( uniqueCharacter < sizeTwo ) {
methodArray[uniqueCharacter] = 0;
uniqueCharacter++;
}
return methodArray;
}
}
That empty box is the null characters that you added at the end of the array. You are printing them because you are not adjusting size according to the number of unique characters (which can be less than the input size). Since you aren't creating a new array, you don't need to return a char [] from deleteRepeats. Instead, you can return the number of unique characters. That way, the calling program knows how many to print.
If your assignment requires that deleteRepeats return a char[], then you should allocate a new array that has a length exactly equal to uniqueCharacter, copy the unique characters to it, and return that. The calling program can just print that new (and shorter) array, rather than printing the first size elements of the input.
Probably the easiest way would be to make a new array to the size of your array of chars and then copy all of the chars into that. The problem with arrays is that once they have been initialized they can't be re sized. If your are familiar with arrayLists I would recommend using them. But if not try something like this...
int count = 0;
for(int i = 0; i < initialInputArray.size; i++){
count++;
}
char[] newArray = new char[count];
for(int i = 0; i < count; i++){
newArray[i] = initialInputArray[i];
}
I would suggest using a HashSet to remove duplicates and wrapping your char to Character. Something like this:
public static Character[] deleteRepeats (char[] methodArray){
HashSet<Character> set = new HashSet<Character>();
for(int index = 0; index < methodArray.length; index++){
set.add(methodArray[index]);
}
return set.toArray(new Character[set.size()]);
}
So in your main method, what you would do is something like this:
Character[] charArray = deleteRepeats(methodArray);
for(int index = 0; index < charArray.length; index++){
System.out.println(charArray[index]);
}

Categories