I don't think I fully understand the concept of looping.

Below is what I put into eclipse and the results I get, am I doing something wrong to get the correct results if you could help thanks

/*  Working with a sentinel value
    Anderson, Franceschi
*/
import java.util.Scanner;

public class EchoUserInput
{
  public static void main( String [] args )
  {
     final int SENTINEL = -1;
     int number;

     Scanner scan = new Scanner( System.in );

     // priming read
     System.out.print( "Enter an integer, or -1 to stop > " );
     number = scan.nextInt( );

     while ( number != SENTINEL )
     {
        // processing
        System.out.println( number );

        // update read
        System.out.print( "Enter an integer, or -1 to stop > " );
        number = scan.nextInt( );
     }

     System.out.println( "Sentinel value detected. Goodbye" );
  }
}

results

Enter an integer, or -1 to stop > 23

Dani

  1. You don't show what the problem is.
  2. This would be better done with a do {...} while (condition) loop instead of your while() {...} loop. Example: (eliminating the priming read)

    do
    {
    System.out.print( "Enter an integer, or -1 to stop > " );
    number = scan.nextInt( );

    // processing
    if (number != SENTINEL)
    {
        System.out.println( number );
    }
    

    }
    while (number != SENTINEL );

Normally, we don't recomment do...while loops, but there are times when they are called for. This may be an instance of such.

What seems to be the issue?

Sentintel value

AFter entering 23 do you enter a space or a carriage return? (If you just type 23 the it will be waiting for the next character in case that will be a digit.)

I entered a space after the 23

Dani

1- when you enter your number from the keyboard, you should press enter to commit the value entered.
2- your code is 100% correct:

while (condition is true)
{
    do something here
}

so while the number!= -1, you keep entering new number, when the number you entered is equal -1, that means the condition in while statment is false, so you will exit the while loop.

i hope this help you.

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.