Hi all. I am learning Java, and having a problem with a sentinel loop to fill an array.

I want the loop to terminate when -1 is added, OR when the array is filled.

int i = 0;
int counter = 0;
int[] array = new int[40];
System.out.print("Enter values to be added to the array." +
		" Enter -1 to stop adding values. ");

array[i] = keyboard.nextInt();
	
while(array[i] != -1 && counter < array.length)
	{
	     i++;
	     counter++;
	     System.out.print("Enter values to be added to the array." +
	     " Enter -1 to stop adding values. ");
	     array[i] = keyboard.nextInt();
	}
return array;

I'm really having two problems:
(1) It is using -1 as a value in my array, thus impacting methods I use later, and
(2) If I am to add numbers not valued as -1, it goes out of bounds.

Any help to point me in the right direction would be greatly appreciated.

Recommended Answers

All 13 Replies

Your code will do what you want with a few minor changes.

int counter = -1; 	// Since Java arrays are 0-indexed (start at 0), 
			//you need to initialize counter to -1 so the first index written to is 0

while(array[i] != -1 && counter < array.length)
{
	i++;
	counter++;
	System.out.print("Enter values to be added to the array." +
	" Enter -1 to stop adding values. ");
	array[i] = keyboard.nextInt();
}
// Test for -1. Note that this works since Java short circuits
// (it will not evaluate the rest of the if statement if the first
// section checked evaluates to false, thus we can avoid an array
// index out of bounds exception if the user simply filled the array
// instead of entering '-1'
if(counter < array.length && array[i] == -1) {
	array[i] = 0;
}

Just remember that arrays start at 0 and you should be fine! Hope this helps!

Thanks for the response. I'm not sure if I should be using both of those loops, though.

It is executing with no compiler errors, but the problem now is that it is inserting "0" into all the fields including and after the sentinel is entered.

(I use another method later on in the program that averages the values it takes in, so these zeroes affect the rest of the program.)

Thanks for the response. I'm not sure if I should be using both of those loops, though.

It is executing with no compiler errors, but the problem now is that it is inserting "0" into all the fields including and after the sentinel is entered.

(I use another method later on in the program that averages the values it takes in, so these zeroes affect the rest of the program.)

maybe try something like this in the while loop:

....
        int counter = -1;//so we can make counter add to 0 on first iteration in while statement
        ....
        while (counter + 1 < array.length) {//use array and counter check to auto end loop when the array is filled
            counter++;
            System.out.print("Enter values to be added to the array."
                    + " Enter -1 to stop adding values. ");
            int tmp = 0;
            if ((tmp = keyboard.nextInt()) == -1) {//if -1 end loop now
                break;
            }
            array[i] = tmp;
            i++;
        }

maybe try something like this in the while loop:

That definitely helped stop the loop. Unfortunately, it stopped the rest of the program from running as well, so the methods used later were never called.

That definitely helped stop the loop. Unfortunately, it stopped the rest of the program from running as well, so the methods used later were never called.

are there methods in your while loop that must be called? because i dont understand how it would stop them? unless they must be called from within the while loop? Maybe showing your code would help for me to understand

Sorry if I am not very clear; the lingo is still new to me.

When I run the program as is, it fills in the rest of the fields with zero.

public class part1
{

	public static void main(String[] args)
	{
		int[] numbers = new int[40];
		double average;

		//Call the getValues method
		numbers = getValues();
		//Call the getAverage method
		average = getAverage(numbers);
		//Call the lessThanAverage method
		lessThanAverage(average, numbers);
	}
	
	/* 
	 * The getValues method will take values from the user.
	 * If the user enters '-1,' the method will stop taking values.
	 * @returnThe numbers[] array fully populated
	*/
	private static int[] getValues()
	{
		Scanner keyboard = new Scanner(System.in);
		int counter = -1;
		int i =0 ;
		int[] array = new int[40];
		
		System.out.print("Enter values to be added to the array." +
					   " Enter -1 to stop adding values. ");
		array[i] = keyboard.nextInt();	
		while (counter + 1 < array.length) 
		{
			counter++;
			System.out.print("Enter values to be added to the array."
			+ " Enter -1 to stop adding values. ");
			int input = 0;
			if ((input = keyboard.nextInt()) == -1) 
				{
				break;
				}
			array[i] = input;
			i++;
		}	
		return array;	
     }
		

		
	/* 
	 * The getAverage method will get the average value of the numbers
	 * array, and return it to main.
	 * @param The array with the values, to b averaged.
	 * @return The average value of he array numbers.
	 */
	
	private static double getAverage(int[] numbers)
	{
		double sum =0;
		double average;
		double count = 0;
		int i = 0;
					
		for(int index = 0; index < numbers.length; ++index)
		{
			sum += numbers[index];
		}
		average = sum / numbers.length;
		System.out.println("The average value in the array is " + average + ".");
		return average;
	}
	/*
	 * The lessThanAverage method will compare the double 'average' with
	 * the array numbers[], and print out which values of numbers[] are 
	 * less than the average.
	 * @param1 The average of the array
	 * @param2 The array with values
	 */
	
	private static void lessThanAverage(double average, int[] numbers)
	{
		for(int i =0; i < numbers.length; ++i)
		{
			if(numbers[i] < average)
				System.out.println(numbers[i] + " is below the average.");
		}
	}
}
public class part1
{

	public static void main(String[] args)
	{
		int[] numbers = new int[40];
		double average;

		//Call the getValues method
		numbers = getValues();
		//Call the getAverage method
		average = getAverage(numbers);
		//Call the lessThanAverage method
		lessThanAverage(average, numbers);
	}
	
	/* 
	 * The getValues method will take values from the user.
	 * If the user enters '-1,' the method will stop taking values.
	 * @returnThe numbers[] array fully populated
	*/
	private static int[] getValues()
	{
		Scanner keyboard = new Scanner(System.in);
		int counter = -1;
		int i =0 ;
		int[] array = new int[40];
		
		System.out.print("Enter values to be added to the array." +
					   " Enter -1 to stop adding values. ");
		array[i] = keyboard.nextInt();	
		while (counter + 1 < array.length) 
		{
			counter++;
			System.out.print("Enter values to be added to the array."
			+ " Enter -1 to stop adding values. ");
			int input = 0;
			if ((input = keyboard.nextInt()) == -1) 
				{
				break;
				}
			array[i] = input;
			i++;
		}	
		return array;	
     }
		

		
	/* 
	 * The getAverage method will get the average value of the numbers
	 * array, and return it to main.
	 * @param The array with the values, to b averaged.
	 * @return The average value of he array numbers.
	 */
	
	private static double getAverage(int[] numbers)
	{
		double sum =0;
		double average;
		double count = 0;
		int i = 0;
					
		for(int index = 0; index < numbers.length; ++index)
		{
			sum += numbers[index];
		}
		average = sum / numbers.length;
		System.out.println("The average value in the array is " + average + ".");
		return average;
	}
	/*
	 * The lessThanAverage method will compare the double 'average' with
	 * the array numbers[], and print out which values of numbers[] are 
	 * less than the average.
	 * @param1 The average of the array
	 * @param2 The array with values
	 */
	
	private static void lessThanAverage(double average, int[] numbers)
	{
		for(int i =0; i < numbers.length; ++i)
		{
			if(numbers[i] < average)
				System.out.println(numbers[i] + " is below the average.");
		}
	}
}

how has it stopped the rest of the program from running? put a println under your method call to getValues() and it should show the println it does in mine?

numbers = getValues(); 
for(int i=0;i<numbers.length;i++){System.out.println(numbers[i]);}//should print the array out after method call

how has it stopped the rest of the program from running? put a println under your method call to getValues() and it should show the println it does in mine?

Sorry if I am not very clear; the lingo is still new to me. It's not stopping the program, i just had a little mistake that needed fixing.

The problem I am now encountering is when I run the program as is, it fills in the rest of the fields with zero. This throws my getAverage method off.

Sorry if I am not very clear; the lingo is still new to me. It's not stopping the program, i just had a little mistake that needed fixing.

The problem I am now encountering is when I run the program as is, it fills in the rest of the fields with zero. This throws my getAverage method off.

well what would you like it to fill in the rest of the uninitialized values with? as it will only fill a zero if there is no value set in the array? if you would like to skip the zeros try:

if(array[i]!=0) {//if  not zero do something
} else {//its a zero
}

Thank you so much for the help. I have it (almost) working.

Looks like a very small tweak should finish me off.

Right now my output (if I enter 1,2,3,-1) into the array:

Enter values to be added to the array. Enter -1 to stop adding values. 1
Enter values to be added to the array. Enter -1 to stop adding values. 2
Enter values to be added to the array. Enter -1 to stop adding values. 3
Enter values to be added to the array. Enter -1 to stop adding values. -1
There were 3 values given by the user.
The average value in the array is 1.6666666666666667.
0 is below the average.

I'm not sure where that zero is coming from.

Either way, I really appreciate all your help!

Thank you so much for the help. I have it (almost) working.

Looks like a very small tweak should finish me off.

Right now my output (if I enter 1,2,3,-1) into the array:


I'm not sure where that zero is coming from.

Either way, I really appreciate all your help!

its coming from the array where there is no initialized variable -i think- can i see your new code...

import java.util.Scanner;

public class part1
{

	public static void main(String[] args)
	{
		int[] numbers = new int[40];
		double average;
		int counter = 1;

		//Call the getValues method
		numbers = getValues();
		for(int i = 0; i<numbers.length; ++i)
			{
			if(numbers[i] == -1)
				break;
			if(numbers[i] == 0)
				break;
			++counter;
			}
		
		//Call the getAverage method
		average = getAverage(numbers, counter);
		//Call the lessThanAverage method
		lessThanAverage(average, numbers, counter);
	}
	
	/* 
	 * The getValues method will take values from the user.
	 * If the user enters '-1,' the method will stop taking values.
	 * @returnThe numbers[] array fully populated
	*/
	private static int[] getValues()
	{
		Scanner keyboard = new Scanner(System.in);
		int counter = -1;
		int i =0 ;
		int[] array = new int[40];
		
		System.out.print("Enter values to be added to the array." +
					   " Enter -1 to stop adding values. ");
		array[i] = keyboard.nextInt();	
		while (counter + 1 < array.length) 
		{
			counter++;
			System.out.print("Enter values to be added to the array."
			+ " Enter -1 to stop adding values. ");
			int input = 0;
			if ((input = keyboard.nextInt()) == -1) 
				{
				break;
				}
		
			array[i] = input;
			i++;
		}	
		return array;
		
}
		

		
	/* 
	 * The getAverage method will get the average value of the numbers
	 * array, and return it to main.
	 * @param The array with the values, to b averaged.
	 * @return The average value of he array numbers.
	 */
	
	private static double getAverage(int[] numbers, int counter)
	{
		double sum =0;
		double average;
		System.out.println("There were " + counter + " values given by the user.");
		for(int index = 0; index < numbers.length; ++index)
		{

			sum += numbers[index];
			
		}
		average = sum / counter;
		System.out.println("The average value in the array is " + average + ".");
		return average;
	}
	/*
	 * The lessThanAverage method will compare the double 'average' with
	 * the array numbers[], and print out which values of numbers[] are 
	 * less than the average.
	 * @param1 The average of the array
	 * @param2 The array with values
	 */
	
	private static void lessThanAverage(double average, int[] numbers, int counter)
	{
		for(int i =0; i < counter; ++i)
		{
			if(numbers[i] < average)
				System.out.println(numbers[i] + " is below the average.");
		}
	}
}
import java.util.Scanner;

public class part1
{

	public static void main(String[] args)
	{
		int[] numbers = new int[40];
		double average;
		int counter = 1;

		//Call the getValues method
		numbers = getValues();
		for(int i = 0; i<numbers.length; ++i)
			{
			if(numbers[i] == -1)
				break;
			if(numbers[i] == 0)
				break;
			++counter;
			}
		
		//Call the getAverage method
		average = getAverage(numbers, counter);
		//Call the lessThanAverage method
		lessThanAverage(average, numbers, counter);
	}
	
	/* 
	 * The getValues method will take values from the user.
	 * If the user enters '-1,' the method will stop taking values.
	 * @returnThe numbers[] array fully populated
	*/
	private static int[] getValues()
	{
		Scanner keyboard = new Scanner(System.in);
		int counter = -1;
		int i =0 ;
		int[] array = new int[40];
		
		System.out.print("Enter values to be added to the array." +
					   " Enter -1 to stop adding values. ");
		array[i] = keyboard.nextInt();	
		while (counter + 1 < array.length) 
		{
			counter++;
			System.out.print("Enter values to be added to the array."
			+ " Enter -1 to stop adding values. ");
			int input = 0;
			if ((input = keyboard.nextInt()) == -1) 
				{
				break;
				}
		
			array[i] = input;
			i++;
		}	
		return array;
		
}
		

		
	/* 
	 * The getAverage method will get the average value of the numbers
	 * array, and return it to main.
	 * @param The array with the values, to b averaged.
	 * @return The average value of he array numbers.
	 */
	
	private static double getAverage(int[] numbers, int counter)
	{
		double sum =0;
		double average;
		System.out.println("There were " + counter + " values given by the user.");
		for(int index = 0; index < numbers.length; ++index)
		{

			sum += numbers[index];
			
		}
		average = sum / counter;
		System.out.println("The average value in the array is " + average + ".");
		return average;
	}
	/*
	 * The lessThanAverage method will compare the double 'average' with
	 * the array numbers[], and print out which values of numbers[] are 
	 * less than the average.
	 * @param1 The average of the array
	 * @param2 The array with values
	 */
	
	private static void lessThanAverage(double average, int[] numbers, int counter)
	{
		for(int i =0; i < counter; ++i)
		{
			if(numbers[i] < average)
				System.out.println(numbers[i] + " is below the average.");
		}
	}
}

do this here:

private static void lessThanAverage(double average, int[] numbers, int counter)
	{
		for(int i =0; i < counter; ++i)
		{
                    if(numbers[i]!=0) {
			if(numbers[i] < average)
				System.out.println(numbers[i] + " is below the average.");
                    }
		}
	}
commented: Very nice guy, very helpful guy. +1
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.