在Java中生成随机字符

时间:2013-10-23 12:06:47

标签: java random

我需要知道这段代码有什么问题,每次运行它时答案总是正确的(即使它是假的), 如果有人知道更短的方式来编写这段代码...也有帮助:) THK

以下是该程序的代码:

import java.io.Console;
import java.util.Random;
import java.util.Scanner;
public class texting {

    public static void main(String[] args) {
        int le = 1;
        int fail = 0;

       System.out.println ("Writting Check");
       System.out.println("Write The Lettes Fast you can and try to not worng, you have 60 sec");
       System.out.println("Press Enter To Continue");
        while (fail < 3)
        {
            String random = "";
            Random r = new Random();
            String chars = "abcdedfghijklmnopqrstuvwxyz";
            int time=60;
            int lives = 3-fail;
            System.out.println("Live Remiend:" + lives);

                for (int i = 0; i < le; i++)
                {
                    random += chars.charAt(r.nextInt(chars.length()));

                }
                System.out.println("Write The letters and prees enter");
                System.out.println(random);
                Scanner sc = new Scanner(System.in);
                String answer = sc.nextLine();
                System.out.println(random != answer);

                if (random != answer)
                {
                    System.out.println("Text Is Worng Try Again");
                    fail++;
                }
                else
                {
                    le++;

                }


        }


    }
}

3 个答案:

答案 0 :(得分:3)

您无法将字符串与==或!=进行比较。您需要使用.equals()方法。 字符串是对象,因此将字符串与==进行比较,如果它们是否引用相同的对象,则会进行比较,而不是它们的内容。

String a = "abc";
String b = "abc";
System.out.println(a == b);    //prints false, a and b are 2 different objects
System.out.println(a.equals(b));    //prints true, the content of both string objects are equal;
b = "def";
System.out.println(a);    //prints "abc"
b = a;
System.out.println(a==b);    //prints true, a and b refer to the same String object
System.out.println(b);    //prints "abc";

当动态构建字符串时,最好使用StringBuilder,而不是仅仅连接字符串。

作为第三个:角色只不过是一个数字的表示。

// 'a'=97, 'z'=122
Random r = new Random();
StringBuilder randomString = new StringBuilder();
for (int i = 0; i < le; ++i) {
    int j = 97 + r.nextInt(122-97);
    char c = (char) j;
    randomString.append(c);
}
randomString.toString();

答案 1 :(得分:2)

试试这个:

if (!random.equals(answer))
     {
        System.out.println("Text Is Worng Try Again");
        fail++;
     }

在Java中,新手遇到的最常见错误之一是使用==和!=来比较字符串。你必须记住,==和!=比较对象引用,而不是内容。

答案 2 :(得分:0)

我认为用

替换这一行
 if (!random.equals(answer))

而不是

if (random != answer)