有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

Java匹配不同的数组

所以我尝试在两个不同的用户输入之间获取基本的输入值,比如ab,匹配它们,然后打印一个循环的分数,然后也打印累计分数。我觉得我做得不错,但每次我的分数都会打印出0的值。所以我们假设键值是a a a,and值是a b a。这将打印出值2,并持续运行,同时将分数重置为0

    InputStreamReader reader = new InputStreamReader(System.in);
    BufferedReader input1 = new BufferedReader(reader);
    BufferedReader input2 = new BufferedReader(reader);

    String inputValue;
    String[] key;
    String[] ans;
    int totalScore = 0;

    inputValue = input1.readLine();
    key = inputValue.split("\\s+");

    while(true){

       int score = 0;

       inputValue = input2.readLine();
       ans = inputValue.split("\\s+");

       if(key[0] == ans[0])
          score += 1;
       if(key[1] == ans[1])
          score += 1;
       if(key[2] == ans[2])
          score += 1;

       totalScore = score;

       System.out.print(score + "\n");
       System.out.print(totalScore + "\n");
  }

共 (1) 个答案

  1. # 1 楼答案

    你在比较字符串;用.equals()代替==

    例如:

    if (key[0].equals(ans[0])) {}
    

    记住:(几乎)总是使用.equals()进行字符串比较