java 使用哨兵控制的循环
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13634992/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Using sentinel-controlled loop
提问by user1864508
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.
我在练习要求用户提示名称并将该名称回显到屏幕上时遇到问题,直到用户输入标记值。我知道这是一个哨兵控制的循环,但我坚持要输入名称而不是整数的事实。我试图遵循我书中的一个程序,该程序仅解释了如何将标记值与整数一起使用,而不是与字符串“名称”一起使用。我尝试查找这个答案并看到类似 name.equals("stop") 的内容,如果它甚至适用于此。并在 API 上查找它,但仍然没有发现它有帮助。我想看看它作为一个整体是如何应用的。
注意:这是我到目前为止所做的,我想知道我离我有多远。
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();
}
回答by joval
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
我认为该名称中不能包含哨兵。在其他情况下,更改== -1
为
!= length(name) - 1
PS. You're declaring String name
twice.
附注。你声明了String name
两次。
PS2. Even better condition:
PS2。更好的条件:
while (!name.endsWith(String.valueOf(SENTINEL));
回答by 5377037
The use of sentinel for loop:
哨兵for循环的使用:
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.
在哨兵控制的循环中,更改部分取决于来自用户的数据。在 for 语句中执行此操作很尴尬。所以更改部分从 for 语句中省略并放在一个方便的位置。
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
更多详情:https: //chortle.ccsu.edu/java5/Notes/chap41/ch41_13.html