繁体   English   中英

如何在有条件的循环中检查输入的字符串?

[英]How to check entered String in a loop with condition?

我想编写一个程序,该程序检查给定字符限制(例如10个字符)的用户输入字符串。 如果输入的字符串超过10个字符,则系统应再次提示用户输入有效的字符串(10个字符的单词),直到用户输入有效的字符串为止。

我已经有一些代码了,但是它还不能用,因为我不知道如何将进程重新启动(到第1行)以重新提示用户,或者还有其他简单的方法吗?

System.out.print("Input: ");
String inputChars = Input.readString();

while (inputChars.length() > 10){
    System.out.print("Input: ");
    String inputChars = Input.readString();  // here is mistake now
}
System.out.print("Output: ");
System.out.print("The enter has 10 chars");

我只想检查输入的单词(如果超过10个字符),然后跳过它并再次提示用户输入不超过10个字符的单词。 我的Java语言还不太好,所以如果这个问题很愚蠢,请向我解释如何解决。 提前致谢

看一下你的循环:

while (inputChars.length() > 10){
    System.out.print("Input: ");
    String inputChars = Input.readString();
}

循环主体的第二行重新声明inputChars变量。 您不能这样做,因为它已经在范围内。 您只想替换先前的值

inputChars = Input.readString();

但是,您还应该考虑重组代码,以避免重复:

String inputChars;
do {
    System.out.print("Input: ");
    inputChars = input.readString();
} while (inputChars.length() > 10);

请注意,我还如何将Input变量重命名为input以遵循常规Java命名约定。 其实我可能会改变这两种inputinputChars更描述性的-尤其是,有没有什么样的输入数据意味着此刻的意思表示。

只需在开头删除String

  while (inputChars.length() > 10){
     System.out.print("Input: ");
     inputChars = Input.readString();  // here is mistake now
  }

通过以String开头,您正在尝试再次重新定义相同的名称变量。

改成:

String inputChars = ""
do {
    System.out.print("Input: ");
    inputChars = Input.readString();
} while (inputChars.length() > 10)
System.out.print("Output: ");
System.out.print("The enter has 10 chars");

之前,在循环之前已经声明了inputChars ,因此您无需重新声明变量。

do-while循环在这里是一个更好的构造,因为它可以使您的意图更清晰,并使您的代码更清晰。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM