简体   繁体   English

将用户输入限制为仅“ R”,“ L”和0-9

[英]Limiting user input to only 'R', 'L', and 0-9

I am having trouble getting the rest of my code to have the following limits 我无法让我的其余代码具有以下限制

  1. It consists of only the following characters: 'R', 'L', and '0' through '9' 它仅包含以下字符:“ R”,“ L”和“ 0”至“ 9”
  2. The 'R' character must appear exactly twice “ R”字符必须出现两次
  3. The 'L' character must appear exactly once “ L”字符必须出现一次
  4. The 'L' character must appear between the two 'R' characters “ L”字符必须出现在两个“ R”字符之间
  5. Each 'R' and 'L' character must be followed by at least one '0' through '9' character 每个“ R”和“ L”字符必须后接至少一个“ 0”至“ 9”字符
  6. No more than two '0' through '9' characters may appear consecutively 连续出现不超过两个“ 0”到“ 9”字符

     import java.util.Scanner; public class HW04 { public static void main(String[] args) { Scanner stdIn = new Scanner(System.in); // Started by naming all the variables String combination; // char R, L; int length; boolean big_R, big_L; System.out.print("Please enter a valid turn dial lock combination : "); combination = stdIn.nextLine(); System.out.println(""); System.out.println(""); length = combination.length(); if (length <= 9 && length >= 6 ) { R = combination.charAt(0); if (R == 'R' ) big_R = true; else System.out.println(combination + " is not a valid turn dial lock combination"); if } else { System.out.println(combination + " is not a valid turn dial lock combination"); } stdIn.close(); } } 

given your list of requirements this shoudl be albo to be validated by a regular expression. 给定您的要求列表,此提示也应通过正则表达式进行验证。

maybe something like R\\d\\d?L\\d\\d?R\\d\\d? 也许像R\\d\\d?L\\d\\d?R\\d\\d?

which reads as: an R followed by 1 digit and an optional second digit an L followed by 1 digit and an optional second digit and finally a second R followed by 1 digit and an optional second digit 读为:R后跟1位数字和可选的第二位数字,L后跟1位数字和可选的第二位数字,最后是第二个R后跟1位数字和可选的第二位数字。

you can find elsewhere examples of how to apply that to your code. 您可以在其他地方找到有关如何将其应用于代码的示例。

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

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