0

I'm having trouble with an exercise asking to have a user prompt a name and echoes that name to the screen until user enters a sentinel value. I understand this is a sentinel-controlled loop but I'm stuck on the fact that I'm dealing with entering a name instead of an integer. I tried to follow a program in my book which only explains how to use a sentinel value with integers but not with String "name". I tried looking up this answer and saw something like name.equals("stop") if it even applies to this. and looked it up on the APIs and still didn't find it helpful. I would like to see how it applies as a whole.
Note: here is what I have done so far and I want to know how far off I am.

import java.util.*;

public class SentinelControlledLoop {

    static Scanner console = new Scanner(System.in);
    static final int SENTINEL = #;

    public static void main (String[] args) {

        String name;
        System.out.println("Enter a name " + "ending with " + SENTINEL); 
        String name = reader.next();

        while (!name.equals(“stop”)) {
            name = reader.next();
        }
Lahiru
  • 1,428
  • 13
  • 17
user1864508
  • 19
  • 1
  • 1
  • 3

3 Answers3

0
do {
    name = reader.next();
} while (name.lastIndexOf(SENTINEL) == -1);

I assume that name cannot contain the sentinel in it. In other case, change == -1 to

!= length(name) - 1

PS. You're declaring String name twice.

PS2. Even better condition:

while (!name.endsWith(String.valueOf(SENTINEL));
joval
  • 466
  • 1
  • 6
  • 15
0

The use of sentinel for loop:

In a sentinel controlled loop the change part depends on data from the user. It is awkward to do this inside a for statement. So the change part is omitted from the for statement and put in a convenient location.

import java.util.Scanner;

class EvalSqrt
{
  public static void main (String[] args )
  {
    Scanner scan = new Scanner( System.in );
    double x;

    System.out.print("Enter a value for x or -1 to exit: ")  ;
    x = scan.nextDouble();

    for (    ; x >= 0.0 ;   )  
    {
      System.out.println( "Square root of " + x + " is " + Math.sqrt( x ) ); 

      System.out.print("Enter a value for x or -1 to exit: ")  ;
      x =  scan.nextDouble();
    }
  }
}

For more details: https://chortle.ccsu.edu/java5/Notes/chap41/ch41_13.html

0

an exercise asking to have a user prompt a name and echoes that name to the screen until user enters a sentinel value.

I would expect to see something more like:

  public static void main(String[] args) {
    Scanner reader = new Scanner(System.in);
    String SENTINEL = "stop";
    String name;
    do { 
      System.out.print("Enter a name ('" + SENTINEL + "' to quit): "); 
      name = reader.nextLine();
      if (!name.equals(SENTINEL)) {
        System.out.println(name);
      }
    } while (!name.equals(SENTINEL));
    System.out.println("Goodbye!");
  } 
Idle_Mind
  • 38,363
  • 3
  • 29
  • 40