字符串与字符串数组元素之间的比较

时间:2017-12-31 14:56:46

标签: java string immutability

我的部分代码:

  int t,w;
  String day;
  String[] week=new String[]{"mon","tues","wed","thurs","fri","sat","sun"};
  .
  .
  .
  day=sc.nextLine();
  .
  .
   for(i=0;i<7;i++)
   {
           if(day.equals(week[i]))
           {

                break;
           }
    }

&#39; .equals()&#39;方法正在返回&#39; false&#39;每次即使字符串包含相同。输出也不会随着array.e.g的初始化而改变。 &#39; String [] week = {&#34; mon&#34;,&#34; tues&#34;,......}&#39;给出相同的输出。当内存位置不同时,此方法返回false吗?请澄清。

3 个答案:

答案 0 :(得分:0)

当您使用scanner.nextLine()时,您阅读的内容超过输入的字符串。你也在阅读EOL。尝试调试这个并查看&#34; day&#34;中实际包含的字符串。变量。

答案 1 :(得分:0)

下面的Ankush对我来说很好,请确保你使用相同的情况下这个代码。如果你想匹配任何案例,请使用 equalsIgnoreCase 而不是等于

package com.java;

import java.util.Scanner;

public class Test {

    static void check() {
        String day;
        String[] week = new String[] { "mon", "tues", "wed", "thurs", "fri", "sat", "sun" };

        Scanner sc = new Scanner(System.in);

        day = sc.nextLine();

        for (int i = 0; i < 7; i++) {
            if (day.equals(week[i])) {
                System.out.println("break");
                break;
            }
        }

        sc.close();
    }

    public static void main(String args[]) {
        Test.check();
    }
}

答案 2 :(得分:0)

您可能只想从扫描仪中读取一个单词,但之后您需要清除在输入结尾输入的新行字符,然后按“Enter”:

int t,w;
String day;
String[] week = new String[] {"mon","tues","wed","thurs","fri","sat","sun"};

 . . . 

day = sc.next();
 . . 
for (i = 0; i < week.length; i++) {
    if(day.equalsIgnoreCase(week[i])) {
        break;
    }
}
sc.nextLine(); // here you get rid of remaining new line character
sc.close();