1

我需要知道这段代码有什么问题,每次我运行它时答案总是正确的(即使它是错误的),如果有人知道编写这段代码的更短方法......也有帮助:) 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++;

                }


        }


    }
}
4

3 回答 3

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();
于 2013-10-23T12:16:41.223 回答
2

尝试这个:

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

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

于 2013-10-23T12:15:30.673 回答
0

我认为用

 if (!random.equals(answer))

而不是这个

if (random != answer)
于 2013-10-23T12:19:36.650 回答