'Using sentinel-controlled loop
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();
}
Solution 1:[1]
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));
Solution 2:[2]
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
Solution 3:[3]
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!");
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | stefan |
| Solution 3 | Idle_Mind |
