0

我正在运行我创建的存储用户输入的数据的 java 程序。特别是 4 个数组列表,分别是 songName、songArtist、songYear 和 songAlbum。我有一个“songYear”的用户输入,我只希望程序最多接受 4 位长度并给出错误,否则如何实现? 这是一个屏幕截图

这是我的添加条目方法的代码:

        public void addEntry(){
        String newName = ui.getString("Enter the name of the track");
        songName.add(newName);
        String newArtist = ui.getString("Who performs this track");
        songArtist.add(newArtist);
        String newAlbum = ui.getString("What album is this track from");
        songAlbum.add(newAlbum);
        System.out.print("What year was the track released? ");
        int newYear=input.nextInt(4);
        songYear.add(newYear);

        System.out.println("\n" + "Thank you, " +songName.get(songName.size()-1) + " has been added to the library.");
        System.out.println("\n" + "Press 2 to view your library." + "\n");
    } 
4

3 回答 3

2

您可以使用正则表达式,例如:^.{4}$

仅表示用户输入 4 位数字 - 返回 true,否则返回 false

为确保用户使用 4 个数字,请YYYY使用以下内容:

^(?=[1-9]+)\d{4}$

确保年份是 1 或 2,后跟三个数字;在这种情况下,有效范围为 1000-2999

^(?=[1-2][0-9]+)\d{4}$

最后你的代码应该是这样的:

 if(inputUserStr.matches("^(?=[1-2][0-9]+)\d{4}$")){
   // do some stuff
 }
  else{
   // print error about valid input form [YYYY]
  }
于 2012-10-24T21:52:22.437 回答
0

Depends entirely on the language but some approaches are:

  • check the string input using a len function; or
  • convert it to an integer and ensure it's less than 10,000; or
  • a regular expression like ^\d{1,4}.

No doubt there'll be other validation checks such as ensuring string input is all-numeric, and you're not trying to input a song that was written twenty years in the future, but they're added checks you should consider.

于 2012-10-24T21:50:54.447 回答
0

1) 接受用户的输入并使用子字符串方法,只保存前四个字符(指定给用户考虑前四个字符)。

2)如果不是4个字符,您可以要求用户重新输入该值:

Scanner sc = new Scanner(System.in);

String a = sc.next();
        if (a.matches("...."))
        {
             System.out.print(a);
        }
            else 
        {
             System.out.print("Input again:" );   
             a = sc.next();
        }

我已经为 4 个字符编写了一个示例正则表达式。但你总是可以改变它。

于 2012-10-24T22:03:10.503 回答