我只想验证参数是否仅由字母数字字符组成。我已经尝试过了,但它的行为并不像我喜欢的那样:
import java.util.Scanner;
import java.util.Random;
import java.lang.Math;
public class game
{
public static void main(String [] args){
System.out.print("Number of players? ");
Scanner kb = new Scanner(System.in);
int numplayers = kb.nextInt();
String [] playersArray = new String[numplayers];
int guessesArray[] = new int [numplayers];
int currscoresArray[] = new int [numplayers];
int addscoresArray[] = new int [numplayers];
int finalscoresArray [] = new int [numplayers];
populateArray(playersArray);
makeGuess(guessesArray);
}
public static void populateArray( String[] x){
Scanner kb = new Scanner(System.in);
for (int i = 0; i<x.length ; i++){
System.out.print("Enter Player "+(i+1)+": ");
x[i]=kb.nextLine();
}
}
public static void displayMenu(){
int choice=0;
Scanner kb = new Scanner(System.in);
String[] args = {};
while(true){
System.out.println("Menu ");
System.out.println("1. Make Guess");
System.out.println("2. List Winner");
System.out.println("0. Exit");
System.out.print("Enter choice: ");
choice = kb.nextInt();
if (choice==0){
System.out.print("Do you want to play a new game? Y/N: ");
String ans = kb.next();
if (ans.equals ("Y") || ans.equals ("y")){
main(args);
}
break;
}
switch (choice){
case 1: makeGuess(); break;
case 2: System.out.println("Option 2 selected"); break;
default: System.out.println("Invalid choice");
}
}
System.out.println("End of program");System.exit(0);
}
public static void makeGuess(){
Scanner kb = new Scanner(System.in);
Random rand = new Random();
int secret = rand.nextInt(10)+1;
int guess = kb.nextInt();
int diff = (int)(Math.abs(guess - secret));
int score=0;
for (int i=0; i < x.length; i++){
System.out.print("Enter your guess player "+(i+1)+": ");
x[i]=kb.nextInt();
}
if (diff == 0){
score=score+10;
}else if(diff<=10){
score=score+5;
}else if(diff<=20){
score=score+2;
}
for (int i=0; i<x.length; i++){
x[i]=score;
}
}
返回:
something_with_underscores
我明显遗漏了一些明显的东西。有什么建议吗?
答案 0 :(得分:7)
ValidatePattern
支持正则表达式。如果模式匹配,则验证字符串。您没有验证字符串中的所有字符...只是一个!
更改正则表达式模式以匹配整个字符串将是一种方法。其他正则表达式也足够了。
[ValidatePattern('^[a-zA-Z0-9]+$')]$someVariableThatShouldOnlyContainAlphaNumerics = 'something_with_underscores'
请注意,设置默认值将绕过此验证,因为它未传递给该函数。