匹配随机生成的String以输入

时间:2017-02-04 23:16:28

标签: java if-statement

在Java中

如果您已生成完全随机的信件,例如" H"或" p"并且您需要验证用户是否输入了" h"或" p"使用扫描仪,你如何验证他们已经完成了这项工作而没有输入不正确的东西?

3 个答案:

答案 0 :(得分:1)

您可以使用if / else或编写条件短语来测试它:

Scanner sc = new Scanner((System.in));
char character = sc.next().charAt(0);
char temp;
Random rand = new Random();
System.out.println((temp = (char)('a' + rand.nextInt(26)))==character ? "Correct": "Incorrect, letter is: " + temp);

答案 1 :(得分:0)

基于K. Rzepeckas回答:

// generate your random string
Random r = new Random();
String s = String.valueOf((char)(r.nextInt(26) + 'a')); // generate random char a-z

// test if the user input is equal to your random string
Scanner sc = new Scanner((System.in));
String character = sc.nextLine();
System.out.println((character.equals(s) ? "Correct": "Incorrect");

编辑(使用评论中的随机函数):

// generate your random string
String s = String.valueOf(generateRandomChars("abcdefghijklmnopqrst‌​uvwxyz", 1));

// test if the user input is equal to your random string
Scanner sc = new Scanner((System.in));
String character = sc.nextLine();
System.out.println((character.equals(s) ? "Correct": "Incorrect");

答案 2 :(得分:0)

如果我理解你的问题是正确的,你想检查用户是否输入了随机的同一个字母,那么试试这段代码:

    Random rnd = new Random();
    int randomNumber = rnd.nextInt(25); // since index starts with 0
    String abc = "abcdefghijklmnopqrstuvxyz";
    char aChar = abc.charAt(randomNumber);
    String myLetter = Character.toString(aChar);
    // System.out.println(myLetter ); // so you could check the letter 
    Scanner sc = new Scanner(System.in);
    System.out.println("enter a number: ")
    String input = sc.nextLine();

    if(input.equals(myLetter)){
      System.out.println("Right" );
     }
    else{
         System.out.println("Wrong"); 
     }