1

Anybody got any idea on how I can check if an array indexes(not just one index) are empty and if is empty or zero put a value there. And also if all the indexes are all not empty print an error.

Sorry unfortunately I can't give rep.

import java.util.Scanner; 

public class Myhash {

/**
 * @param args
 */
public static void main(String[] args) {
    // TODO Auto-generated method stub

    int [] myData = new int[17]; 

    int [] newData = new int [17];

    System.out.println("Please enter 16 integer numbers");
    for(int i= 0; i<myData.length; i++){
        //System.out.print("Please enter 16 numbers");
        Scanner input = new Scanner(System.in);
        int data =input.nextInt(); 
        myData[i]=data; 
        int num3 = data % 17;
        newData[num3]=data; 
    }       

    System.out.println("These are the numbers you entered\n");      
    System.out.printf("%s%8s \n", "Index", "Value"); 

    for(int t=0; t<myData.length; t++){
        System.out.printf("%5d%8d\n", t, myData[t]);
    }

    System.out.println("\n");
    System.out.println("The Hash Function:\n\n");
    System.out.printf("%5s%8s \n", "Index", "Value"); 

            for(int s=0; s<newData.length; s++){
        System.out.printf("%5d%8d\n", s, newData[s]);
            }   
    }
}

on here:

    for(int s=0; s<newData.length; s++){
    System.out.printf("%5d%8d\n", s, newData[s]);
    }

how do check for more than one index(if empty? If the index is empty how do check for the next index and if that one is not empty how do i check the next one, etc?

user1244123
  • 163
  • 1
  • 1
  • 6

2 Answers2

11

Elements in primitive arrays can't be empty. They'll always get initialized to something

If you declare the array like so

 int [] newData = new int [17];

then all of the elements will default to zero.

For checking if an element is not entered, you can use a simple loop :

 for(int i=0;i<newData.length;i++)
    {
        if(newData[i]==0)
            System.out.println("The value at " + i + "is empty");
    }

Although , the above code will not work in your case, because the user might enter 0 as an input value and still this code will consider it to be empty.

What you can do is, initialize the array with all values as -1, and specify at the input prompt that only values >=0 can be entered . The initialization can be done like this:

int[] newData = new int[17];
for(int i=0;i<newData.length;i++)
{
   newData[i]= -1;   
}

Then you can ask the user for input and do the processing. Then you can use this:

for(int i=0;i<newData.length;i++)
    {
        if(newData[i]==-1)
           System.out.println("The value at " + i + "is empty");
    }
HighBit
  • 258
  • 1
  • 2
  • 9
2

Here:

for(int i = 0; i < array.length; i++)
{
    if(array[i] == null)
        continue;
}
Liam Haworth
  • 848
  • 1
  • 9
  • 27